diff --git a/.github/workflows/pr-analyzer.yml b/.github/workflows/pr-analyzer.yml index 84857f2..dd40a36 100644 --- a/.github/workflows/pr-analyzer.yml +++ b/.github/workflows/pr-analyzer.yml @@ -14,6 +14,15 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install dependencies + run: npm ci + - name: Run PR Analyzer uses: ./ with: diff --git a/.gitignore b/.gitignore index 3f6d363..c68853d 100644 --- a/.gitignore +++ b/.gitignore @@ -42,7 +42,7 @@ build/Release # Dependency directories node_modules/ jspm_packages/ -package-lock.json +# Note: package-lock.json should be committed for reproducible builds # Snowpack dependency directory (https://snowpack.dev/) web_modules/ @@ -154,5 +154,17 @@ dist/* !dist/index.js !dist/index.js.map +# Allow necessary directories for agent imports (needed when ncc doesn't fully bundle) +!dist/utils/ +!dist/utils/** +!dist/agents/ +!dist/agents/** +!dist/tools/ +!dist/tools/** +!dist/providers/ +!dist/providers/** +!dist/types/ +!dist/types/** + # ArchDoc configuration (contains API keys) .archdoc.config.json diff --git a/README.md b/README.md index 0dbf0eb..a992feb 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ PR Agent analyzes your code changes and provides: ```bash # Install -npm install -g pr-agent +npm install -g @techdebtgpt/pr-agent # Setup pr-agent config --init @@ -80,13 +80,13 @@ Before using PR Agent, you'll need: Install PR Agent globally using npm: ```bash -npm install -g pr-agent +npm install -g @techdebtgpt/pr-agent ``` Or use it directly with npx: ```bash -npx pr-agent analyze +npx @techdebtgpt/pr-agent analyze ``` ### Verify Installation @@ -278,6 +278,35 @@ export GOOGLE_API_KEY="..." Add to your `.bashrc`, `.zshrc`, or `.env` file for persistence. +#### Default Branch Configuration + +PR Agent automatically detects the default branch for your repository using the following priority: + +1. **Config file** (`git.defaultBranch`) - If set in `.pragent.config.json`, this takes highest priority +2. **GitHub API** - If `GITHUB_TOKEN` is available, fetches the default branch from GitHub +3. **Git commands** - Falls back to detecting from local git repository +4. **Fallback** - Defaults to `origin/main` if nothing else works + +**Examples:** + +```bash +# Set default branch in config +pr-agent config --set git.defaultBranch=origin/develop + +# For repositories using 'master' as default +pr-agent config --set git.defaultBranch=origin/master + +# Override for a single analysis +pr-agent analyze --branch origin/feature-branch +``` + +**Troubleshooting Branch Issues:** + +- **Branch not found**: Run `git fetch origin` to update remote branch references +- **Wrong branch detected**: Set `git.defaultBranch` in config or use `--branch` flag +- **GitHub API errors**: Ensure `GITHUB_TOKEN` is valid, or rely on git fallback +- **Custom default branch**: Configure it explicitly: `pr-agent config --set git.defaultBranch=origin/your-branch` + ## Architecture Documentation Integration PR Agent can leverage your project's architecture documentation for context-aware analysis. @@ -521,7 +550,8 @@ cd pr-agent ### 2. Install Dependencies ```bash -npm install +# Install dependencies (use --legacy-peer-deps to handle langchain peer dependency conflicts) +npm install --legacy-peer-deps ``` ### 3. Build the Project @@ -542,15 +572,21 @@ npm run build:action #### Test CLI ```bash -# Run directly with tsx (development) -npm run dev +# Option 1: Link locally to use 'pr-agent' command +npm link +pr-agent config --init +pr-agent analyze --staged -# Build and test -npm run build -node dist/cli/index.js analyze --help +# Option 2: Use npm script +npm run cli config --init +npm run cli analyze --staged -# Test analyze command +# Option 3: Run directly with node +node dist/cli/index.js config --init node dist/cli/index.js analyze --staged + +# Option 4: Development mode (no build needed) +npm run dev ``` #### Test GitHub Action @@ -651,10 +687,10 @@ For large or complex PRs, PR Agent uses an intelligent agent system that: ```bash # If pr-agent command not found after npm install -g -npm install -g pr-agent +npm install -g @techdebtgpt/pr-agent # Or use npx -npx pr-agent analyze +npx @techdebtgpt/pr-agent analyze ``` #### API Key Not Recognized @@ -768,6 +804,7 @@ Best for: Overall quality, architecture understanding, and complex reasoning ### OpenAI GPT +- **gpt-5.1** - Latest GPT-5.1 model (newest) - **gpt-4-turbo-preview** - Latest GPT-4 (recommended) - **gpt-4** - Stable and reliable - **gpt-3.5-turbo** - Fast and cost-effective @@ -860,7 +897,7 @@ Add to your CI pipeline: # .github/workflows/pr-check.yml - name: PR Quality Check run: | - npm install -g pr-agent + npm install -g @techdebtgpt/pr-agent pr-agent analyze --full env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} diff --git a/dist/cli/commands/analyze.command.js b/dist/cli/commands/analyze.command.js index 5ca78ee..b6e7cf3 100644 --- a/dist/cli/commands/analyze.command.js +++ b/dist/cli/commands/analyze.command.js @@ -5,6 +5,8 @@ import ora from 'ora'; import { PRAnalyzerAgent } from '../../agents/pr-analyzer-agent.js'; import { loadUserConfig, getApiKey } from '../utils/config-loader.js'; import { archDocsExists } from '../../utils/arch-docs-parser.js'; +import { resolveDefaultBranch } from '../../utils/branch-resolver.js'; +import { ConfigurationError, GitHubAPIError, GitError } from '../../utils/errors.js'; /** * Determine which files should be skipped during analysis */ @@ -47,38 +49,45 @@ async function getUntrackedFiles() { /** * Get git diff with optional command */ -async function getGitDiff(command) { +async function getGitDiff(command, defaultBranch) { try { let diff = ''; const maxBuffer = 200 * 1024 * 1024; // 200MB - if (!command || command === 'origin/main') { + if (!command || command === 'default') { + // Use resolved default branch + const branch = defaultBranch || 'origin/main'; try { - diff = execSync('git diff origin/main', { + diff = execSync(`git diff ${branch}`, { encoding: 'utf-8', maxBuffer, }); } - catch { - // Fallback to main branch - console.log(chalk.yellow('⚠️ origin/main not found, trying main branch...')); - diff = execSync('git diff main', { + catch (error) { + throw new GitError(`Failed to get diff from branch "${branch}". The branch may not exist locally. Run: git fetch origin && git checkout ${branch}`, `git diff ${branch}`); + } + } + else if (command === 'staged') { + try { + diff = execSync('git diff --staged', { encoding: 'utf-8', maxBuffer, }); } - } - else if (command === 'staged') { - diff = execSync('git diff --staged', { - encoding: 'utf-8', - maxBuffer, - }); + catch (error) { + throw new GitError('Failed to get staged changes. Make sure you have staged files with: git add ', 'git diff --staged'); + } } else { // Custom branch or reference - diff = execSync(`git diff ${command}`, { - encoding: 'utf-8', - maxBuffer, - }); + try { + diff = execSync(`git diff ${command}`, { + encoding: 'utf-8', + maxBuffer, + }); + } + catch (error) { + throw new GitError(`Failed to get diff from "${command}". The branch or reference may not exist.`, `git diff ${command}`); + } } // Normalize diff (remove trailing whitespace but preserve structure) diff = diff.trim(); @@ -203,9 +212,24 @@ function estimateDiffSize(diff) { export async function analyzePR(options = {}) { const spinner = ora('Initializing PR analysis...').start(); try { - // Load configuration - const config = await loadUserConfig(false); + // Load and validate configuration + let config; + try { + config = await loadUserConfig(false, true); // Validate config + } + catch (error) { + spinner.fail('Configuration error'); + if (error instanceof ConfigurationError) { + console.error(chalk.red(`\n❌ ${error.message}`)); + process.exit(1); + } + throw error; + } // Get provider and API key from config or environment + if (options.verbose) { + console.log(chalk.gray(` Debug: options.provider: ${options.provider || 'undefined'}`)); + console.log(chalk.gray(` Debug: config.ai?.provider: ${config.ai?.provider || 'undefined'}`)); + } const provider = (options.provider || config.ai?.provider || 'anthropic').toLowerCase(); const apiKey = getApiKey(provider, config); if (!apiKey) { @@ -219,6 +243,38 @@ export async function analyzePR(options = {}) { process.exit(1); } spinner.succeed(`Using AI provider: ${provider}`); + // Resolve default branch if needed + let defaultBranch; + if (!options.diff && !options.file && !options.staged && !options.branch) { + spinner.text = 'Resolving default branch...'; + try { + const branchResult = await resolveDefaultBranch({ + configBranch: config.git?.defaultBranch, + githubToken: process.env.GITHUB_TOKEN, + fallbackToGit: true, + }); + defaultBranch = branchResult.branch; + if (branchResult.warning && options.verbose) { + console.log(chalk.yellow(`\n⚠️ ${branchResult.warning}`)); + } + if (options.verbose) { + console.log(chalk.gray(` Using branch: ${defaultBranch} (source: ${branchResult.source})`)); + } + } + catch (error) { + if (error instanceof GitHubAPIError || error instanceof ConfigurationError) { + spinner.fail('Branch resolution failed'); + console.error(chalk.red(`\n❌ ${error.message}`)); + if (error instanceof GitHubAPIError) { + console.error(chalk.gray('\n💡 You can override the branch with:')); + console.error(chalk.gray(' pr-agent analyze --branch ')); + console.error(chalk.gray(' Or set git.defaultBranch in config: pr-agent config --set git.defaultBranch=')); + } + process.exit(1); + } + throw error; + } + } // Determine analysis mode const mode = { summary: options.summary || options.full || false, @@ -234,20 +290,35 @@ export async function analyzePR(options = {}) { spinner.text = 'Fetching diff...'; // Get the diff let diff; - if (options.diff) { - diff = options.diff; - } - else if (options.file) { - diff = fs.readFileSync(options.file, 'utf-8'); - } - else if (options.staged) { - diff = await getGitDiff('staged'); - } - else if (options.branch) { - diff = await getGitDiff(options.branch); + try { + if (options.diff) { + diff = options.diff; + } + else if (options.file) { + diff = fs.readFileSync(options.file, 'utf-8'); + } + else if (options.staged) { + diff = await getGitDiff('staged'); + } + else if (options.branch) { + diff = await getGitDiff(options.branch); + } + else { + diff = await getGitDiff('default', defaultBranch); + } } - else { - diff = await getGitDiff(); + catch (error) { + spinner.fail('Failed to get diff'); + if (error instanceof GitError) { + console.error(chalk.red(`\n❌ ${error.message}`)); + console.error(chalk.gray('\n💡 Troubleshooting:')); + console.error(chalk.gray(' • Make sure you are in a git repository')); + console.error(chalk.gray(' • Check that the branch exists: git branch -a')); + console.error(chalk.gray(' • Fetch remote branches: git fetch origin')); + console.error(chalk.gray(' • Use --branch flag to specify a different branch')); + process.exit(1); + } + throw error; } if (!diff) { spinner.fail('No diff found'); @@ -289,14 +360,43 @@ export async function analyzePR(options = {}) { } catch (error) { spinner.fail('Analysis failed'); - if (error.message && error.message.includes('rate-limits')) { + // Handle specific error types with user-friendly messages + if (error instanceof ConfigurationError) { + console.error(chalk.red(`\n❌ Configuration Error: ${error.message}`)); + console.error(chalk.gray('\n💡 Run: pr-agent config --init to fix configuration')); + process.exit(1); + } + else if (error instanceof GitHubAPIError) { + console.error(chalk.red(`\n❌ GitHub API Error: ${error.message}`)); + if (error.statusCode === 401 || error.statusCode === 403) { + console.error(chalk.gray('\n💡 Check your GITHUB_TOKEN environment variable')); + } + process.exit(1); + } + else if (error instanceof GitError) { + console.error(chalk.red(`\n❌ Git Error: ${error.message}`)); + process.exit(1); + } + else if (error.message && error.message.includes('rate-limits')) { console.error(chalk.red.bold('\n❌ Rate limit error: Your diff is too large for the API.')); console.error(chalk.yellow('\n💡 Try reducing the diff size or adjusting maxTokens in config')); + process.exit(1); } else { - console.error(chalk.red('\nError:'), error instanceof Error ? error.message : error); + // Generic error - sanitize output to avoid leaking sensitive info + const errorMessage = error.message || String(error); + // Don't log full stack traces or potential secrets + const sanitizedMessage = errorMessage + .replace(/sk-[a-zA-Z0-9_-]+/g, 'sk-***') + .replace(/ghp_[a-zA-Z0-9]+/g, 'ghp_***') + .substring(0, 500); // Limit length + console.error(chalk.red(`\n❌ Error: ${sanitizedMessage}`)); + if (options.verbose && error.stack) { + console.error(chalk.gray('\nStack trace:')); + console.error(chalk.gray(error.stack.substring(0, 1000))); + } + process.exit(1); } - process.exit(1); } } /** diff --git a/dist/cli/commands/analyze.command.js.map b/dist/cli/commands/analyze.command.js.map index 83aa56b..08e352d 100644 --- a/dist/cli/commands/analyze.command.js.map +++ b/dist/cli/commands/analyze.command.js.map @@ -1 +1 @@ -{"version":3,"file":"analyze.command.js","sourceRoot":"","sources":["../../../src/cli/commands/analyze.command.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"analyze.command.js","sourceRoot":"","sources":["../../../src/cli/commands/analyze.command.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/cli/commands/config.command.js b/dist/cli/commands/config.command.js index de746fe..d219a67 100644 --- a/dist/cli/commands/config.command.js +++ b/dist/cli/commands/config.command.js @@ -108,6 +108,7 @@ async function initializeConfig() { } else if (provider === 'openai') { modelChoices = [ + { name: 'GPT-5.1 (Latest)', value: 'gpt-5.1' }, { name: 'GPT-4 Turbo', value: 'gpt-4-turbo-preview' }, { name: 'GPT-4', value: 'gpt-4' }, { name: 'GPT-3.5 Turbo', value: 'gpt-3.5-turbo' }, diff --git a/dist/cli/commands/config.command.js.map b/dist/cli/commands/config.command.js.map index c08d8e4..05ecd84 100644 --- a/dist/cli/commands/config.command.js.map +++ b/dist/cli/commands/config.command.js.map @@ -1 +1 @@ -{"version":3,"file":"config.command.js","sourceRoot":"","sources":["../../../src/cli/commands/config.command.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"config.command.js","sourceRoot":"","sources":["../../../src/cli/commands/config.command.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/cli/commands/help.command.js b/dist/cli/commands/help.command.js index 2b63204..8024f2a 100644 --- a/dist/cli/commands/help.command.js +++ b/dist/cli/commands/help.command.js @@ -31,6 +31,13 @@ export function displayHelp() { console.log(' --branch Analyze against specific branch'); console.log(' --file Read diff from file'); console.log(' --diff Provide diff directly\n'); + console.log(chalk.dim(' Default Branch Detection:')); + console.log(' The default branch is determined in this order:'); + console.log(' 1. Config file (git.defaultBranch)'); + console.log(' 2. GitHub API (if GITHUB_TOKEN is set)'); + console.log(' 3. Git commands (local detection)'); + console.log(' 4. Fallback to origin/main'); + console.log(' Use --branch to override for a single analysis\n'); console.log(chalk.dim(' Advanced Options:')); console.log(' --provider AI provider: anthropic|openai|google'); console.log(' --model Specific model to use'); @@ -107,6 +114,7 @@ export function displayHelp() { console.log(' • claude-3-5-sonnet-20241022'); console.log(' • claude-3-opus-20240229\n'); console.log(chalk.green(' OpenAI GPT')); + console.log(' • gpt-5.1 (latest)'); console.log(' • gpt-4-turbo-preview'); console.log(' • gpt-4'); console.log(' • gpt-3.5-turbo\n'); diff --git a/dist/cli/commands/help.command.js.map b/dist/cli/commands/help.command.js.map index 84f3048..1aa82f6 100644 --- a/dist/cli/commands/help.command.js.map +++ b/dist/cli/commands/help.command.js.map @@ -1 +1 @@ -{"version":3,"file":"help.command.js","sourceRoot":"","sources":["../../../src/cli/commands/help.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B;;GAEG;AACH,MAAM,UAAU,WAAW;IACzB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,qDAAqD,CAAC,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CACP,uGAAuG,CACxG,CACF,CAAC;IAEF,cAAc;IACd,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,GAAG,iCAAiC,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,eAAe,CAAC,GAAG,yBAAyB,CAAC,CAAC;IACtE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,oDAAoD,CAAC,CAAC;IAEhG,gBAAgB;IAChB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC;IAEhD,kBAAkB;IAClB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAC5F,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,0EAA0E,CAAC,CAAC;IACxF,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAE5F,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IAEjE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,8DAA8D,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,kDAAkD,CAAC,CAAC;IAChE,OAAO,CAAC,GAAG,CAAC,sDAAsD,CAAC,CAAC;IAEpE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,mEAAmE,CAAC,CAAC;IACjF,OAAO,CAAC,GAAG,CAAC,oDAAoD,CAAC,CAAC;IAClE,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAC9E,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;IAChF,OAAO,CAAC,GAAG,CAAC,sDAAsD,CAAC,CAAC;IAEpE,iBAAiB;IACjB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IACpC,OAAO,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,uEAAuE,CAAC,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,uEAAuE,CAAC,CAAC;IAErF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,mEAAmE,CAAC,CAAC;IACjF,OAAO,CAAC,GAAG,CAAC,4DAA4D,CAAC,CAAC;IAC1E,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;IAChF,OAAO,CAAC,GAAG,CAAC,4EAA4E,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAC;IACxE,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAE9E,eAAe;IACf,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClC,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IAEjE,wBAAwB;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC;IACtD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,uEAAuE,CAAC,CAAC;IAChH,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,qEAAqE,CAAC,CAAC;IAC5G,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,4DAA4D,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,8CAA8C,CAAC,CAAC;IAEpF,oBAAoB;IACpB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzD,OAAO,CAAC,GAAG,CAAC,iFAAiF,CAAC,CAAC;IAC/F,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,6CAA6C,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,0BAA0B,CAAC,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,4BAA4B,CAAC,GAAG,mBAAmB,CAAC,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,wCAAwC,CAAC,CAAC;IAEpG,wBAAwB;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC;IAC7D,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3B,OAAO,CAAC,GAAG,CAAC,4EAA4E,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,sEAAsE,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;IACzF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+DAA+D,CAAC,CAAC,CAAC;IAExF,qBAAqB;IACrB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,mBAAmB,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC,CAAC;IACrE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;MAmBR,CAAC,CACJ,CAAC;IAEF,sBAAsB;IACtB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAC,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC,CAAC;IAClE,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC;IACzC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACzC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3B,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAChC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEpC,mBAAmB;IACnB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC;IACxD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IAC7C,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IAEzC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IAE7C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,wCAAwC,CAAC,CAAC,CAAC;IAClE,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAE/C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;IAEvD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAE1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;IAEhD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,sEAAsE,CAAC,CAAC;IAEpF,oBAAoB;IACpB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC;IAC7C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACjD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+DAA+D,CAAC,CAAC,CAAC;IAExF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC,CAAC;IAE9D,wBAAwB;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,+BAA+B,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,uCAAuC,CAAC,CAAC;IAC7F,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,sCAAsC,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,wBAAwB,GAAG,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,wBAAwB,CAAC,CAAC;IACtG,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,yCAAyC,CAAC,CAAC;IAC9F,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,wCAAwC,CAAC,CAAC;IAErG,SAAS;IACT,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC,6CAA6C,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;AAChD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAgB;IAClD,OAAO;SACJ,OAAO,CAAC,MAAM,CAAC;SACf,WAAW,CAAC,wCAAwC,CAAC;SACrD,MAAM,CAAC,GAAG,EAAE;QACX,WAAW,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACP,CAAC"} \ No newline at end of file +{"version":3,"file":"help.command.js","sourceRoot":"","sources":["../../../src/cli/commands/help.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B;;GAEG;AACH,MAAM,UAAU,WAAW;IACzB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,qDAAqD,CAAC,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CACP,uGAAuG,CACxG,CACF,CAAC;IAEF,cAAc;IACd,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,GAAG,iCAAiC,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,eAAe,CAAC,GAAG,yBAAyB,CAAC,CAAC;IACtE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,oDAAoD,CAAC,CAAC;IAEhG,gBAAgB;IAChB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC;IAEhD,kBAAkB;IAClB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAC5F,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,0EAA0E,CAAC,CAAC;IACxF,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAE5F,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IAEjE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,8DAA8D,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,kDAAkD,CAAC,CAAC;IAChE,OAAO,CAAC,GAAG,CAAC,sDAAsD,CAAC,CAAC;IAEpE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC,CAAC;IACxD,OAAO,CAAC,GAAG,CAAC,uDAAuD,CAAC,CAAC;IACrE,OAAO,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC;IACxD,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;IACvD,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,wDAAwD,CAAC,CAAC;IAEtE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,mEAAmE,CAAC,CAAC;IACjF,OAAO,CAAC,GAAG,CAAC,oDAAoD,CAAC,CAAC;IAClE,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAC9E,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;IAChF,OAAO,CAAC,GAAG,CAAC,sDAAsD,CAAC,CAAC;IAEpE,iBAAiB;IACjB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IACpC,OAAO,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,uEAAuE,CAAC,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,uEAAuE,CAAC,CAAC;IAErF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,mEAAmE,CAAC,CAAC;IACjF,OAAO,CAAC,GAAG,CAAC,4DAA4D,CAAC,CAAC;IAC1E,OAAO,CAAC,GAAG,CAAC,kEAAkE,CAAC,CAAC;IAChF,OAAO,CAAC,GAAG,CAAC,4EAA4E,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAC;IACxE,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAE9E,eAAe;IACf,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClC,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IAEjE,wBAAwB;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC;IACtD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,uEAAuE,CAAC,CAAC;IAChH,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,qEAAqE,CAAC,CAAC;IAC5G,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,4DAA4D,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,8CAA8C,CAAC,CAAC;IAEpF,oBAAoB;IACpB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzD,OAAO,CAAC,GAAG,CAAC,iFAAiF,CAAC,CAAC;IAC/F,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,6CAA6C,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,0BAA0B,CAAC,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,4BAA4B,CAAC,GAAG,mBAAmB,CAAC,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,wCAAwC,CAAC,CAAC;IAEpG,wBAAwB;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC;IAC7D,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3B,OAAO,CAAC,GAAG,CAAC,4EAA4E,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,sEAAsE,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;IACzF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+DAA+D,CAAC,CAAC,CAAC;IAExF,qBAAqB;IACrB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,mBAAmB,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC,CAAC;IACrE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;MAmBR,CAAC,CACJ,CAAC;IAEF,sBAAsB;IACtB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAC,CAAC,CAAC;IAC9D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC,CAAC;IAClE,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC;IACzC,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IACtC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACzC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3B,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAChC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEpC,mBAAmB;IACnB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC;IACxD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IAC7C,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IAEzC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IAE7C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,wCAAwC,CAAC,CAAC,CAAC;IAClE,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAE/C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;IAEvD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC,CAAC;IACrD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAE1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;IAEhD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,sEAAsE,CAAC,CAAC;IAEpF,oBAAoB;IACpB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC;IAC7C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACjD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+DAA+D,CAAC,CAAC,CAAC;IAExF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC,CAAC;IAE9D,wBAAwB;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC,CAAC;IAC5D,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,+BAA+B,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,uCAAuC,CAAC,CAAC;IAC7F,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,sCAAsC,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,wBAAwB,GAAG,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,wBAAwB,CAAC,CAAC;IACtG,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,yCAAyC,CAAC,CAAC;IAC9F,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,wCAAwC,CAAC,CAAC;IAErG,SAAS;IACT,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC,6CAA6C,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;AAChD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAgB;IAClD,OAAO;SACJ,OAAO,CAAC,MAAM,CAAC;SACf,WAAW,CAAC,wCAAwC,CAAC;SACrD,MAAM,CAAC,GAAG,EAAE;QACX,WAAW,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACP,CAAC"} \ No newline at end of file diff --git a/dist/cli/index.js b/dist/cli/index.js index 5a12ff6..0a26553 100644 --- a/dist/cli/index.js +++ b/dist/cli/index.js @@ -27,7 +27,7 @@ program .option('--staged', 'Analyze staged changes (git diff --staged)') .option('--branch ', 'Analyze against specific branch') .option('--title ', 'PR title (auto-detected from git)') - .option('--provider ', 'AI provider (anthropic|openai|google)', 'anthropic') + .option('--provider ', 'AI provider (anthropic|openai|google)') .option('--model ', 'Specific model to use') .option('--agent', 'Force intelligent agent (recommended for large diffs)') .option('--summary', 'Show summary only') diff --git a/dist/cli/index.js.map b/dist/cli/index.js.map index 579d7b4..f5b4186 100644 --- a/dist/cli/index.js.map +++ b/dist/cli/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AAEA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,sCAAsC;AACtC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEtC,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;AACtE,iCAAiC;AACjC,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAC5B,EAAE,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,CAC1C,CAAC;AAEF,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAE9B,OAAO;KACJ,IAAI,CAAC,UAAU,CAAC;KAChB,WAAW,CAAC,4DAA4D,CAAC;KACzE,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAEhC,oDAAoD;AACpD,OAAO;KACJ,OAAO,CAAC,SAAS,CAAC;KAClB,WAAW,CAAC,sCAAsC,CAAC;KACnD,MAAM,CAAC,eAAe,EAAE,4BAA4B,CAAC;KACrD,MAAM,CAAC,eAAe,EAAE,qBAAqB,CAAC;KAC9C,MAAM,CAAC,UAAU,EAAE,4CAA4C,CAAC;KAChE,MAAM,CAAC,iBAAiB,EAAE,iCAAiC,CAAC;KAC5D,MAAM,CAAC,gBAAgB,EAAE,mCAAmC,CAAC;KAC7D,MAAM,CAAC,uBAAuB,EAAE,uCAAuC,EAAE,WAAW,CAAC;KACrF,MAAM,CAAC,iBAAiB,EAAE,uBAAuB,CAAC;KAClD,MAAM,CAAC,SAAS,EAAE,uDAAuD,CAAC;KAC1E,MAAM,CAAC,WAAW,EAAE,mBAAmB,CAAC;KACxC,MAAM,CAAC,SAAS,EAAE,iBAAiB,CAAC;KACpC,MAAM,CAAC,cAAc,EAAE,sBAAsB,CAAC;KAC9C,MAAM,CAAC,QAAQ,EAAE,0BAA0B,EAAE,IAAI,CAAC;KAClD,MAAM,CAAC,aAAa,EAAE,kFAAkF,CAAC;KACzG,MAAM,CAAC,sBAAsB,EAAE,yBAAyB,EAAE,KAAK,CAAC;KAChE,MAAM,CAAC,WAAW,EAAE,uBAAuB,EAAE,KAAK,CAAC;KACnD,MAAM,CAAC,SAAS,CAAC,CAAC;AAErB,iBAAiB;AACjB,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAE/B,eAAe;AACf,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAE7B,sBAAsB;AACtB,OAAO,CAAC,KAAK,EAAE,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AAEA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,sCAAsC;AACtC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEtC,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;AACtE,iCAAiC;AACjC,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAC5B,EAAE,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,CAC1C,CAAC;AAEF,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAE9B,OAAO;KACJ,IAAI,CAAC,UAAU,CAAC;KAChB,WAAW,CAAC,4DAA4D,CAAC;KACzE,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAEhC,oDAAoD;AACpD,OAAO;KACJ,OAAO,CAAC,SAAS,CAAC;KAClB,WAAW,CAAC,sCAAsC,CAAC;KACnD,MAAM,CAAC,eAAe,EAAE,4BAA4B,CAAC;KACrD,MAAM,CAAC,eAAe,EAAE,qBAAqB,CAAC;KAC9C,MAAM,CAAC,UAAU,EAAE,4CAA4C,CAAC;KAChE,MAAM,CAAC,iBAAiB,EAAE,iCAAiC,CAAC;KAC5D,MAAM,CAAC,gBAAgB,EAAE,mCAAmC,CAAC;KAC7D,MAAM,CAAC,uBAAuB,EAAE,uCAAuC,CAAC;KACxE,MAAM,CAAC,iBAAiB,EAAE,uBAAuB,CAAC;KAClD,MAAM,CAAC,SAAS,EAAE,uDAAuD,CAAC;KAC1E,MAAM,CAAC,WAAW,EAAE,mBAAmB,CAAC;KACxC,MAAM,CAAC,SAAS,EAAE,iBAAiB,CAAC;KACpC,MAAM,CAAC,cAAc,EAAE,sBAAsB,CAAC;KAC9C,MAAM,CAAC,QAAQ,EAAE,0BAA0B,EAAE,IAAI,CAAC;KAClD,MAAM,CAAC,aAAa,EAAE,kFAAkF,CAAC;KACzG,MAAM,CAAC,sBAAsB,EAAE,yBAAyB,EAAE,KAAK,CAAC;KAChE,MAAM,CAAC,WAAW,EAAE,uBAAuB,EAAE,KAAK,CAAC;KACnD,MAAM,CAAC,SAAS,CAAC,CAAC;AAErB,iBAAiB;AACjB,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAE/B,eAAe;AACf,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAE7B,sBAAsB;AACtB,OAAO,CAAC,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/cli/utils/config-loader.d.ts b/dist/cli/utils/config-loader.d.ts index 1c163f3..384a0b1 100644 --- a/dist/cli/utils/config-loader.d.ts +++ b/dist/cli/utils/config-loader.d.ts @@ -34,7 +34,7 @@ export declare function findConfigFile(): string | null; /** * Load user configuration from file */ -export declare function loadUserConfig(verbose?: boolean): Promise; +export declare function loadUserConfig(verbose?: boolean, validate?: boolean): Promise; /** * Check if configuration exists and is valid */ diff --git a/dist/cli/utils/config-loader.js b/dist/cli/utils/config-loader.js index 4821608..43cb91a 100644 --- a/dist/cli/utils/config-loader.js +++ b/dist/cli/utils/config-loader.js @@ -1,6 +1,8 @@ import * as fs from 'fs'; import * as path from 'path'; import chalk from 'chalk'; +import { validateConfigOrThrow, validateConfig } from '../../utils/config-validator.js'; +import { ConfigurationError } from '../../utils/errors.js'; const CONFIG_FILE = '.pragent.config.json'; /** * Find config file in current directory or parent directories @@ -25,7 +27,7 @@ export function findConfigFile() { /** * Load user configuration from file */ -export async function loadUserConfig(verbose = false) { +export async function loadUserConfig(verbose = false, validate = true) { const configPath = findConfigFile(); if (!configPath) { if (verbose) { @@ -40,13 +42,34 @@ export async function loadUserConfig(verbose = false) { if (verbose) { console.log(chalk.green(`✅ Loaded configuration from: ${path.relative(process.cwd(), configPath)}`)); } + // Validate configuration if requested + if (validate) { + try { + return validateConfigOrThrow(config, configPath); + } + catch (error) { + if (error instanceof ConfigurationError) { + if (verbose) { + console.error(chalk.red(`\n❌ ${error.message}`)); + } + throw error; + } + throw error; + } + } return config; } catch (error) { + if (error instanceof ConfigurationError) { + throw error; + } + if (error instanceof SyntaxError) { + throw new ConfigurationError(`Invalid JSON in configuration file: ${error.message}\n\nRun: pr-agent config --init to recreate configuration.`, 'config'); + } if (verbose) { - console.error(chalk.red(`❌ Error loading configuration: ${error}`)); + console.error(chalk.red(`❌ Error loading configuration: ${error instanceof Error ? error.message : String(error)}`)); } - return {}; + throw new ConfigurationError(`Failed to load configuration: ${error instanceof Error ? error.message : String(error)}\n\nRun: pr-agent config --init to fix configuration.`, 'config'); } } /** @@ -61,17 +84,33 @@ export async function checkConfiguration() { return true; // Don't block execution, just warn } try { - const config = await loadUserConfig(false); + const config = await loadUserConfig(false, true); // Validate config // Basic validation - if (!config.ai?.provider && !process.env.ANTHROPIC_API_KEY) { + if (!config.ai?.provider && !process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY && !process.env.GOOGLE_API_KEY) { console.log(chalk.yellow('\n⚠️ No AI provider configured')); console.log(chalk.gray(' Run: pr-agent config --init\n')); return true; // Don't block execution } + // Validate branch configuration if present + if (config.git?.defaultBranch) { + const validation = validateConfig(config); + if (!validation.success) { + const branchErrors = validation.errors.filter((e) => e.includes('defaultBranch')); + if (branchErrors.length > 0) { + console.log(chalk.yellow('\n⚠️ Invalid branch configuration:')); + branchErrors.forEach((err) => console.log(chalk.gray(` • ${err}`))); + console.log(chalk.gray(' Run: pr-agent config --set git.defaultBranch=\n')); + } + } + } return true; } catch (error) { - console.error(chalk.red(`❌ Invalid configuration: ${error}`)); + if (error instanceof ConfigurationError) { + console.error(chalk.red(`\n❌ ${error.message}`)); + return false; + } + console.error(chalk.red(`❌ Invalid configuration: ${error instanceof Error ? error.message : String(error)}`)); return false; } } @@ -80,8 +119,11 @@ export async function checkConfiguration() { */ export function getApiKey(provider, config) { // Check config first - if (config?.apiKeys && config.apiKeys[provider]) { - return config.apiKeys[provider]; + if (config?.apiKeys) { + const key = config.apiKeys[provider]; + if (key && key.trim().length > 0) { + return key; + } } // Fall back to environment variables const envVarMap = { @@ -91,7 +133,10 @@ export function getApiKey(provider, config) { }; const envVar = envVarMap[provider.toLowerCase()]; if (envVar) { - return process.env[envVar]; + const envKey = process.env[envVar]; + if (envKey && envKey.trim().length > 0) { + return envKey; + } } return undefined; } diff --git a/dist/cli/utils/config-loader.js.map b/dist/cli/utils/config-loader.js.map index 01564c7..ffcea2d 100644 --- a/dist/cli/utils/config-loader.js.map +++ b/dist/cli/utils/config-loader.js.map @@ -1 +1 @@ -{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../src/cli/utils/config-loader.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../src/cli/utils/config-loader.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/cli/utils/config-prompts.js b/dist/cli/utils/config-prompts.js index 220ad59..501feb5 100644 --- a/dist/cli/utils/config-prompts.js +++ b/dist/cli/utils/config-prompts.js @@ -48,6 +48,7 @@ export async function promptFullConfig(projectPath, options = {}) { } else if (provider === 'openai') { modelChoices = [ + { name: 'GPT-5.1 (Latest)', value: 'gpt-5.1' }, { name: 'GPT-4 Turbo (Recommended)', value: 'gpt-4-turbo-preview' }, { name: 'GPT-4', value: 'gpt-4' }, { name: 'GPT-3.5 Turbo', value: 'gpt-3.5-turbo' }, diff --git a/dist/cli/utils/config-prompts.js.map b/dist/cli/utils/config-prompts.js.map index f71a421..eb7a396 100644 --- a/dist/cli/utils/config-prompts.js.map +++ b/dist/cli/utils/config-prompts.js.map @@ -1 +1 @@ -{"version":3,"file":"config-prompts.js","sourceRoot":"","sources":["../../../src/cli/utils/config-prompts.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"config-prompts.js","sourceRoot":"","sources":["../../../src/cli/utils/config-prompts.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 834b495..b2087ba 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,113540 +1,111 @@ -import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; -/******/ var __webpack_modules__ = ({ - -/***/ 4914: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(857)); -const utils_1 = __nccwpck_require__(302); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -function escapeData(s) { - return (0, utils_1.toCommandValue)(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return (0, utils_1.toCommandValue)(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map - -/***/ }), - -/***/ 7484: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(4914); -const file_command_1 = __nccwpck_require__(4753); -const utils_1 = __nccwpck_require__(302); -const os = __importStar(__nccwpck_require__(857)); -const path = __importStar(__nccwpck_require__(6928)); -const oidc_utils_1 = __nccwpck_require__(5306); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode || (exports.ExitCode = ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); - } - (0, command_1.issueCommand)('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - (0, command_1.issueCommand)('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - (0, file_command_1.issueFileCommand)('PATH', inputPath); - } - else { - (0, command_1.issueCommand)('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; - } - return inputs.map(input => input.trim()); -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - process.stdout.write(os.EOL); - (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - (0, command_1.issue)('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - (0, command_1.issueCommand)('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - (0, command_1.issue)('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - (0, command_1.issue)('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); -} -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(1847); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(1847); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(1976); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -/** - * Platform utilities exports - */ -exports.platform = __importStar(__nccwpck_require__(8968)); -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 4753: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -// For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const crypto = __importStar(__nccwpck_require__(6982)); -const fs = __importStar(__nccwpck_require__(9896)); -const os = __importStar(__nccwpck_require__(857)); -const utils_1 = __nccwpck_require__(302); -function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueFileCommand = issueFileCommand; -function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - const convertedValue = (0, utils_1.toCommandValue)(value); - // These should realistically never happen, but just in case someone finds a - // way to exploit uuid generation let's not allow keys or values that contain - // the delimiter. - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; -} -exports.prepareKeyValueMessage = prepareKeyValueMessage; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 5306: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(4844); -const auth_1 = __nccwpck_require__(4552); -const core_1 = __nccwpck_require__(7484); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - (0, core_1.debug)(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - (0, core_1.setSecret)(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); - } -} -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map - -/***/ }), - -/***/ 1976: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(6928)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 8968: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; -const os_1 = __importDefault(__nccwpck_require__(857)); -const exec = __importStar(__nccwpck_require__(5236)); -const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { - silent: true - }); - const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { - silent: true - }); - return { - name: name.trim(), - version: version.trim() - }; -}); -const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - var _a, _b, _c, _d; - const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { - silent: true - }); - const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; - return { - name, - version - }; -}); -const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { - silent: true - }); - const [name, version] = stdout.trim().split('\n'); - return { - name, - version - }; -}); -exports.platform = os_1.default.platform(); -exports.arch = os_1.default.arch(); -exports.isWindows = exports.platform === 'win32'; -exports.isMacOS = exports.platform === 'darwin'; -exports.isLinux = exports.platform === 'linux'; -function getDetails() { - return __awaiter(this, void 0, void 0, function* () { - return Object.assign(Object.assign({}, (yield (exports.isWindows - ? getWindowsInfo() - : exports.isMacOS - ? getMacOsInfo() - : getLinuxInfo()))), { platform: exports.platform, - arch: exports.arch, - isWindows: exports.isWindows, - isMacOS: exports.isMacOS, - isLinux: exports.isLinux }); - }); -} -exports.getDetails = getDetails; -//# sourceMappingURL=platform.js.map - -/***/ }), - -/***/ 1847: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(857); -const fs_1 = __nccwpck_require__(9896); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); - } -} -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 302: -/***/ ((__unused_webpack_module, exports) => { - - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; - } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; -} -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 5236: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(3193); -const tr = __importStar(__nccwpck_require__(6665)); -/** - * Exec a command. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code - */ -function exec(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); - } - // Path to tool to execute should be first arg - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); - }); -} -exports.exec = exec; -/** - * Exec a command and get the output. - * Output will be streamed to the live console. - * Returns promise with the exit code and collected stdout and stderr - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code, stdout, and stderr - */ -function getExecOutput(commandLine, args, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - let stdout = ''; - let stderr = ''; - //Using string decoder covers the case where a mult-byte character is split - const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); - const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - //flush any remaining characters - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); -} -exports.getExecOutput = getExecOutput; -//# sourceMappingURL=exec.js.map - -/***/ }), - -/***/ 6665: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(857)); -const events = __importStar(__nccwpck_require__(4434)); -const child = __importStar(__nccwpck_require__(5317)); -const path = __importStar(__nccwpck_require__(6928)); -const io = __importStar(__nccwpck_require__(4994)); -const ioUtil = __importStar(__nccwpck_require__(5207)); -const timers_1 = __nccwpck_require__(3557); -/* eslint-disable @typescript-eslint/unbound-method */ -const IS_WINDOWS = process.platform === 'win32'; -/* - * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. - */ -class ToolRunner extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } - } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool - if (IS_WINDOWS) { - // Windows + cmd file - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows + verbatim - else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows (regular) - else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } - else { - // OSX/Linux - this can likely be improved with some form of quoting. - // creating processes on Unix is fundamentally different than Windows. - // on Unix, execvp() takes an arg array. - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; - } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - // the rest of the string ... - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } - catch (err) { - // streaming lines to console is best effort. Don't fail a build. - this._debug(`error processing line. Failed with error ${err}`); - return ''; - } - } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; - } - } - return this.toolPath; - } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += ' '; - argline += options.windowsVerbatimArguments - ? a - : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } - } - return this.args; - } - _endsWith(str, end) { - return str.endsWith(end); - } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return (this._endsWith(upperToolPath, '.CMD') || - this._endsWith(upperToolPath, '.BAT')); - } - _windowsQuoteCmdArg(arg) { - // for .exe, apply the normal quoting rules that libuv applies - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - // otherwise apply quoting rules specific to the cmd.exe command line parser. - // the libuv rules are generic and are not designed specifically for cmd.exe - // command line parser. - // - // for a detailed description of the cmd.exe command line parser, refer to - // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 - // need quotes for empty arg - if (!arg) { - return '""'; - } - // determine whether the arg needs to be quoted - const cmdSpecialChars = [ - ' ', - '\t', - '&', - '(', - ')', - '[', - ']', - '{', - '}', - '^', - '=', - ';', - '!', - "'", - '+', - ',', - '`', - '~', - '|', - '<', - '>', - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some(x => x === char)) { - needsQuotes = true; - break; - } - } - // short-circuit if quotes not needed - if (!needsQuotes) { - return arg; - } - // the following quoting rules are very similar to the rules that by libuv applies. - // - // 1) wrap the string in quotes - // - // 2) double-up quotes - i.e. " => "" - // - // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately - // doesn't work well with a cmd.exe command line. - // - // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. - // for example, the command line: - // foo.exe "myarg:""my val""" - // is parsed by a .NET console app into an arg array: - // [ "myarg:\"my val\"" ] - // which is the same end result when applying libuv quoting rules. although the actual - // command line from libuv quoting rules would look like: - // foo.exe "myarg:\"my val\"" - // - // 3) double-up slashes that precede a quote, - // e.g. hello \world => "hello \world" - // hello\"world => "hello\\""world" - // hello\\"world => "hello\\\\""world" - // hello world\ => "hello world\\" - // - // technically this is not required for a cmd.exe command line, or the batch argument parser. - // the reasons for including this as a .cmd quoting rule are: - // - // a) this is optimized for the scenario where the argument is passed from the .cmd file to an - // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. - // - // b) it's what we've been doing previously (by deferring to node default behavior) and we - // haven't heard any complaints about that aspect. - // - // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be - // escaped when used on the command line directly - even though within a .cmd file % can be escaped - // by using %%. - // - // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts - // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. - // - // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would - // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the - // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args - // to an external program. - // - // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. - // % can be escaped within a .cmd file. - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; // double the slash - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; // double the quote - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _uvQuoteCmdArg(arg) { - // Tool runner wraps child_process.spawn() and needs to apply the same quoting as - // Node in certain cases where the undocumented spawn option windowsVerbatimArguments - // is used. - // - // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, - // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), - // pasting copyright notice from Node within this function: - // - // Copyright Joyent, Inc. and other Node contributors. All rights reserved. - // - // Permission is hereby granted, free of charge, to any person obtaining a copy - // of this software and associated documentation files (the "Software"), to - // deal in the Software without restriction, including without limitation the - // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - // sell copies of the Software, and to permit persons to whom the Software is - // furnished to do so, subject to the following conditions: - // - // The above copyright notice and this permission notice shall be included in - // all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - // IN THE SOFTWARE. - if (!arg) { - // Need double quotation for empty argument - return '""'; - } - if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { - // No quotation needed - return arg; - } - if (!arg.includes('"') && !arg.includes('\\')) { - // No embedded double quotes or backslashes, so I can just wrap - // quote marks around the whole thing. - return `"${arg}"`; - } - // Expected input/output: - // input : hello"world - // output: "hello\"world" - // input : hello""world - // output: "hello\"\"world" - // input : hello\world - // output: hello\world - // input : hello\\world - // output: hello\\world - // input : hello\"world - // output: "hello\\\"world" - // input : hello\\"world - // output: "hello\\\\\"world" - // input : hello world\ - // output: "hello world\\" - note the comment in libuv actually reads "hello world\" - // but it appears the comment is wrong, it should be "hello world\\" - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '\\'; - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 10000 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; - } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result['windowsVerbatimArguments'] = - options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; - } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { - return __awaiter(this, void 0, void 0, function* () { - // root the tool path if it is unrooted and contains relative pathing - if (!ioUtil.isRooted(this.toolPath) && - (this.toolPath.includes('/') || - (IS_WINDOWS && this.toolPath.includes('\\')))) { - // prefer options.cwd if it is specified, however options.cwd may also need to be rooted - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - // if the tool is only a file name, then resolve it from the PATH - // otherwise verify it exists (add extension on Windows if necessary) - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug('arguments:'); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on('debug', (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ''; - if (cp.stdout) { - cp.stdout.on('data', (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ''; - if (cp.stderr) { - cp.stderr.on('data', (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && - optionsNonNull.errStream && - optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr - ? optionsNonNull.errStream - : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on('error', (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on('exit', (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on('close', (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on('done', (error, exitCode) => { - if (stdbuffer.length > 0) { - this.emit('stdline', stdbuffer); - } - if (errbuffer.length > 0) { - this.emit('errline', errbuffer); - } - cp.removeAllListeners(); - if (error) { - reject(error); - } - else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error('child process missing stdin'); - } - cp.stdin.end(this.options.input); - } - })); - }); - } -} -exports.ToolRunner = ToolRunner; -/** - * Convert an arg string to an array of args. Handles escaping - * - * @param argString string of arguments - * @returns string[] array of arguments - */ -function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ''; - function append(c) { - // we only escape double quotes. - if (escaped && c !== '"') { - arg += '\\'; - } - arg += c; - escaped = false; - } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } - else { - append(c); - } - continue; - } - if (c === '\\' && escaped) { - append(c); - continue; - } - if (c === '\\' && inQuotes) { - escaped = true; - continue; - } - if (c === ' ' && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ''; - } - continue; - } - append(c); - } - if (arg.length > 0) { - args.push(arg.trim()); - } - return args; -} -exports.argStringToArray = argStringToArray; -class ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; // tracks whether the process has exited and stdio is closed - this.processError = ''; - this.processExitCode = 0; - this.processExited = false; // tracks whether the process has exited - this.processStderr = false; // tracks whether stderr was written to - this.delay = 10000; // 10 seconds - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error('toolPath must not be empty'); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } - } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } - else if (this.processExited) { - this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); - } - } - _debug(message) { - this.emit('debug', message); - } - _setResult() { - // determine whether there is an error - let error; - if (this.processExited) { - if (this.processError) { - error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } - else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } - else if (this.processStderr && this.options.failOnStdErr) { - error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - // clear the timeout - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit('done', error, this.processExitCode); - } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / - 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); - } -} -//# sourceMappingURL=toolrunner.js.map - -/***/ }), - -/***/ 1648: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(9896); -const os_1 = __nccwpck_require__(857); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = - (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } -} -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 3228: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(1648)); -const utils_1 = __nccwpck_require__(8006); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options, ...additionalPlugins) { - const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); -} -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map - -/***/ }), - -/***/ 5156: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(4844)); -const undici_1 = __nccwpck_require__(6752); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); -} -exports.getProxyAgentDispatcher = getProxyAgentDispatcher; -function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; -} -exports.getProxyFetch = getProxyFetch; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; -} -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 8006: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(1648)); -const Utils = __importStar(__nccwpck_require__(5156)); -// octokit + plugins -const core_1 = __nccwpck_require__(1897); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(4935); -const plugin_paginate_rest_1 = __nccwpck_require__(8082); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -exports.defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl), - fetch: Utils.getProxyFetch(baseUrl) - } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; - } - return opts; -} -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 4552: -/***/ (function(__unused_webpack_module, exports) { - - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map - -/***/ }), - -/***/ 4844: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -/* eslint-disable @typescript-eslint/no-explicit-any */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(8611)); -const https = __importStar(__nccwpck_require__(5692)); -const pm = __importStar(__nccwpck_require__(4988)); -const tunnel = __importStar(__nccwpck_require__(770)); -const undici_1 = __nccwpck_require__(6752); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); - } - readBodyBuffer() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - const chunks = []; - this.message.on('data', (chunk) => { - chunks.push(chunk); - }); - this.message.on('end', () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if tunneling agent isn't assigned create a new agent - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - // if agent is already assigned use that agent. - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` - }))); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); - } - return proxyAgent; - } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); - } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); - }); - } -} -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 4988: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - try { - return new DecodedURL(proxyVar); - } - catch (_a) { - if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new DecodedURL(`http://${proxyVar}`); - } - } - else { - return undefined; - } -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; - } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperNoProxyItem === '*' || - upperReqHosts.some(x => x === upperNoProxyItem || - x.endsWith(`.${upperNoProxyItem}`) || - (upperNoProxyItem.startsWith('.') && - x.endsWith(`${upperNoProxyItem}`)))) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; -function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return (hostLower === 'localhost' || - hostLower.startsWith('127.') || - hostLower.startsWith('[::1]') || - hostLower.startsWith('[0:0:0:0:0:0:0:1]')); -} -class DecodedURL extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } -} -//# sourceMappingURL=proxy.js.map - -/***/ }), - -/***/ 5207: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(9896)); -const path = __importStar(__nccwpck_require__(6928)); -_a = fs.promises -// export const {open} = 'fs' -, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; -// export const {open} = 'fs' -exports.IS_WINDOWS = process.platform === 'win32'; -// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 -exports.UV_FS_O_EXLOCK = 0x10000000; -exports.READONLY = fs.constants.O_RDONLY; -function exists(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exports.stat(fsPath); - } - catch (err) { - if (err.code === 'ENOENT') { - return false; - } - throw err; - } - return true; - }); -} -exports.exists = exists; -function isDirectory(fsPath, useStat = false) { - return __awaiter(this, void 0, void 0, function* () { - const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); - return stats.isDirectory(); - }); -} -exports.isDirectory = isDirectory; -/** - * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: - * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). - */ -function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); - } - if (exports.IS_WINDOWS) { - return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello - ); // e.g. C: or C:\hello - } - return p.startsWith('/'); -} -exports.isRooted = isRooted; -/** - * Best effort attempt to determine whether a file exists and is executable. - * @param filePath file path to check - * @param extensions additional file extensions to try - * @return if file exists and is executable, returns the file path. otherwise empty string. - */ -function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { - let stats = undefined; - try { - // test file exists - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // on Windows, test for valid extension - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - // try each extension - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = undefined; - try { - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // preserve the case of the actual file (since an extension was appended) - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield exports.readdir(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } - catch (err) { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - } - return ''; - }); -} -exports.tryGetExecutablePath = tryGetExecutablePath; -function normalizeSeparators(p) { - p = p || ''; - if (exports.IS_WINDOWS) { - // convert slashes on Windows - p = p.replace(/\//g, '\\'); - // remove redundant slashes - return p.replace(/\\\\+/g, '\\'); - } - // remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -// on Mac/Linux, test the execute bit -// R W X R W X R W X -// 256 128 64 32 16 8 4 2 1 -function isUnixExecutable(stats) { - return ((stats.mode & 1) > 0 || - ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || - ((stats.mode & 64) > 0 && stats.uid === process.getuid())); -} -// Get the path of cmd.exe in windows -function getCmdPath() { - var _a; - return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; -} -exports.getCmdPath = getCmdPath; -//# sourceMappingURL=io-util.js.map - -/***/ }), - -/***/ 4994: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(2613); -const path = __importStar(__nccwpck_require__(6928)); -const ioUtil = __importStar(__nccwpck_require__(5207)); -/** - * Copies a file or folder. - * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js - * - * @param source source path - * @param dest destination path - * @param options optional. See CopyOptions. - */ -function cp(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - // Dest is an existing file, but not forcing - if (destStat && destStat.isFile() && !force) { - return; - } - // If dest is an existing directory, should copy inside. - const newDest = destStat && destStat.isDirectory() && copySourceDirectory - ? path.join(dest, path.basename(source)) - : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } - else { - yield cpDirRecursive(source, newDest, 0, force); - } - } - else { - if (path.relative(source, newDest) === '') { - // a file cannot be copied to itself - throw new Error(`'${newDest}' and '${source}' are the same file`); - } - yield copyFile(source, newDest, force); - } - }); -} -exports.cp = cp; -/** - * Moves a path. - * - * @param source source path - * @param dest destination path - * @param options optional. See MoveOptions. - */ -function mv(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - // If dest is directory copy src into dest - dest = path.join(dest, path.basename(source)); - destExists = yield ioUtil.exists(dest); - } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } - else { - throw new Error('Destination already exists'); - } - } - } - yield mkdirP(path.dirname(dest)); - yield ioUtil.rename(source, dest); - }); -} -exports.mv = mv; -/** - * Remove a path recursively with force - * - * @param inputPath path to remove - */ -function rmRF(inputPath) { - return __awaiter(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - // Check for invalid characters - // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file - if (/[*"<>|]/.test(inputPath)) { - throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); - } - } - try { - // note if path does not exist, error is silent - yield ioUtil.rm(inputPath, { - force: true, - maxRetries: 3, - recursive: true, - retryDelay: 300 - }); - } - catch (err) { - throw new Error(`File was unable to be removed ${err}`); - } - }); -} -exports.rmRF = rmRF; -/** - * Make a directory. Creates the full path with folders in between - * Will throw if it fails - * - * @param fsPath path to create - * @returns Promise - */ -function mkdirP(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(fsPath, 'a path argument must be provided'); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); -} -exports.mkdirP = mkdirP; -/** - * Returns path of a tool had the tool actually been invoked. Resolves via paths. - * If you check and the tool does not exist, it will throw. - * - * @param tool name of the tool - * @param check whether to check if tool exists - * @returns Promise path to tool - */ -function which(tool, check) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // recursive when check=true - if (check) { - const result = yield which(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } - else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } - } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -exports.which = which; -/** - * Returns a list of all occurrences of the given tool on the system path. - * - * @returns Promise the paths of the tool - */ -function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // build the list of extensions to try - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { - for (const extension of process.env['PATHEXT'].split(path.delimiter)) { - if (extension) { - extensions.push(extension); - } - } - } - // if it's rooted, return it if exists. otherwise return empty. - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; - } - return []; - } - // if any path separators, return empty - if (tool.includes(path.sep)) { - return []; - } - // build the list of directories - // - // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, - // it feels like we should not do this. Checking the current directory seems like more of a use - // case of a shell, and the which() function exposed by the toolkit should strive for consistency - // across platforms. - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); - } - } - } - // find all matches - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); - } - } - return matches; - }); -} -exports.findInPath = findInPath; -function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null - ? true - : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; -} -function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter(this, void 0, void 0, function* () { - // Ensure there is not a run away recursive copy - if (currentDepth >= 255) - return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - // Recurse - yield cpDirRecursive(srcFile, destFile, currentDepth, force); - } - else { - yield copyFile(srcFile, destFile, force); - } - } - // Change the mode for the newly created directory - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); - }); -} -// Buffered file copy -function copyFile(srcFile, destFile, force) { - return __awaiter(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - // unlink/re-link it - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } - catch (e) { - // Try to override file permission - if (e.code === 'EPERM') { - yield ioUtil.chmod(destFile, '0666'); - yield ioUtil.unlink(destFile); - } - // other errors = it doesn't exist, no work to do - } - // Copy over symlink - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); - } - else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); - } - }); -} -//# sourceMappingURL=io.js.map - -/***/ }), - -/***/ 2227: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); - - -const ANSI_BACKGROUND_OFFSET = 10; - -const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; - -const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi256 = wrapAnsi256(); - styles.color.ansi16m = wrapAnsi16m(); - styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - - // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js - Object.defineProperties(styles, { - rgbToAnsi256: { - value: (red, green, blue) => { - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (red === green && green === blue) { - if (red < 8) { - return 16; - } - - if (red > 248) { - return 231; - } - - return Math.round(((red - 8) / 247) * 24) + 232; - } - - return 16 + - (36 * Math.round(red / 255 * 5)) + - (6 * Math.round(green / 255 * 5)) + - Math.round(blue / 255 * 5); - }, - enumerable: false - }, - hexToRgb: { - value: hex => { - const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } - - let {colorString} = matches.groups; - - if (colorString.length === 3) { - colorString = colorString.split('').map(character => character + character).join(''); - } - - const integer = Number.parseInt(colorString, 16); - - return [ - (integer >> 16) & 0xFF, - (integer >> 8) & 0xFF, - integer & 0xFF - ]; - }, - enumerable: false - }, - hexToAnsi256: { - value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), - enumerable: false - } - }); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - - -/***/ }), - -/***/ 5769: -/***/ ((module) => { - - - -const UPPERCASE = /[\p{Lu}]/u; -const LOWERCASE = /[\p{Ll}]/u; -const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; -const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; -const SEPARATORS = /[_.\- ]+/; - -const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); -const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); -const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); - -const preserveCamelCase = (string, toLowerCase, toUpperCase) => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < string.length; i++) { - const character = string[i]; - - if (isLastCharLower && UPPERCASE.test(character)) { - string = string.slice(0, i) + '-' + string.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { - string = string.slice(0, i - 1) + '-' + string.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; - } - } - - return string; -}; - -const preserveConsecutiveUppercase = (input, toLowerCase) => { - LEADING_CAPITAL.lastIndex = 0; - - return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); -}; - -const postProcess = (input, toUpperCase) => { - SEPARATORS_AND_IDENTIFIER.lastIndex = 0; - NUMBERS_AND_IDENTIFIER.lastIndex = 0; - - return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) - .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); -}; - -const camelCase = (input, options) => { - if (!(typeof input === 'string' || Array.isArray(input))) { - throw new TypeError('Expected the input to be `string | string[]`'); - } - - options = { - pascalCase: false, - preserveConsecutiveUppercase: false, - ...options - }; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - const toLowerCase = options.locale === false ? - string => string.toLowerCase() : - string => string.toLocaleLowerCase(options.locale); - const toUpperCase = options.locale === false ? - string => string.toUpperCase() : - string => string.toLocaleUpperCase(options.locale); - - if (input.length === 1) { - return options.pascalCase ? toUpperCase(input) : toLowerCase(input); - } - - const hasUpperCase = input !== toLowerCase(input); - - if (hasUpperCase) { - input = preserveCamelCase(input, toLowerCase, toUpperCase); - } - - input = input.replace(LEADING_SEPARATORS, ''); - - if (options.preserveConsecutiveUppercase) { - input = preserveConsecutiveUppercase(input, toLowerCase); - } else { - input = toLowerCase(input); - } - - if (options.pascalCase) { - input = toUpperCase(input.charAt(0)) + input.slice(1); - } - - return postProcess(input, toUpperCase); -}; - -module.exports = camelCase; -// TODO: Remove this for the next major release -module.exports["default"] = camelCase; - - -/***/ }), - -/***/ 3563: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "Zu", ({ - enumerable: true, - get: function () { - return _max.default; - } -})); -Object.defineProperty(exports, "wD", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "qg", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "As", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "bV", ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "v6", ({ - enumerable: true, - get: function () { - return _v5.default; - } -})); -Object.defineProperty(exports, "JE", ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -})); -Object.defineProperty(exports, "v7", ({ - enumerable: true, - get: function () { - return _v6.default; - } -})); -Object.defineProperty(exports, "tf", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "rE", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -var _max = _interopRequireDefault(__nccwpck_require__(6273)); -var _nil = _interopRequireDefault(__nccwpck_require__(6652)); -var _parse = _interopRequireDefault(__nccwpck_require__(724)); -var _stringify = _interopRequireDefault(__nccwpck_require__(5818)); -var _v = _interopRequireDefault(__nccwpck_require__(1650)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(6347)); -var _v2 = _interopRequireDefault(__nccwpck_require__(5208)); -var _v3 = _interopRequireDefault(__nccwpck_require__(7293)); -var _v4 = _interopRequireDefault(__nccwpck_require__(7982)); -var _v5 = _interopRequireDefault(__nccwpck_require__(5083)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(3559)); -var _v6 = _interopRequireDefault(__nccwpck_require__(9412)); -var _validate = _interopRequireDefault(__nccwpck_require__(6593)); -var _version = _interopRequireDefault(__nccwpck_require__(4419)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 6273: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 1299: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 6648: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 6652: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 724: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6593)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - let v; - const arr = new Uint8Array(16); - - // Parse ########-....-....-....-............ - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; - - // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; - - // Parse ........-....-####-....-............ - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; - - // Parse ........-....-....-####-............ - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; - - // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} -var _default = exports["default"] = parse; - -/***/ }), - -/***/ 9844: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 6270: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 8158: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 5818: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; -var _validate = _interopRequireDefault(__nccwpck_require__(6593)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); -} -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -var _default = exports["default"] = stringify; - -/***/ }), - -/***/ 1650: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(6270)); -var _stringify = __nccwpck_require__(5818); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -let _nodeId; -let _clockseq; - -// Previous uuid creation time -let _lastMSecs = 0; -let _lastNSecs = 0; - -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. We do this lazily to minimize issues - // related to insufficient system entropy. See #189 - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is - // handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v1; - -/***/ }), - -/***/ 6347: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(724)); -var _stringify = __nccwpck_require__(5818); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 5208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(2053)); -var _md = _interopRequireDefault(__nccwpck_require__(1299)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 2053: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; -var _stringify = __nccwpck_require__(5818); -var _parse = _interopRequireDefault(__nccwpck_require__(724)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - return bytes; -} -const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - if (typeof value === 'string') { - value = stringToBytes(value); - } - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } - - // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); - } - - // Function#name is not settable on some platforms (#270) - try { - generateUUID.name = name; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 7293: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(6648)); -var _rng = _interopRequireDefault(__nccwpck_require__(6270)); -var _stringify = __nccwpck_require__(5818); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(rnds); -} -var _default = exports["default"] = v4; - -/***/ }), - -/***/ 7982: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(2053)); -var _sha = _interopRequireDefault(__nccwpck_require__(8158)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 5083: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(5818); -var _v = _interopRequireDefault(__nccwpck_require__(1650)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(6347)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 3559: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(724)); -var _stringify = __nccwpck_require__(5818); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 9412: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(6270)); -var _stringify = __nccwpck_require__(5818); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 6593: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(9844)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 4419: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6593)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 6061: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "Zu", ({ - enumerable: true, - get: function () { - return _max.default; - } -})); -Object.defineProperty(exports, "wD", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "qg", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "As", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "bV", ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "v6", ({ - enumerable: true, - get: function () { - return _v5.default; - } -})); -Object.defineProperty(exports, "JE", ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -})); -Object.defineProperty(exports, "v7", ({ - enumerable: true, - get: function () { - return _v6.default; - } -})); -Object.defineProperty(exports, "tf", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "rE", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -var _max = _interopRequireDefault(__nccwpck_require__(5607)); -var _nil = _interopRequireDefault(__nccwpck_require__(5190)); -var _parse = _interopRequireDefault(__nccwpck_require__(3922)); -var _stringify = _interopRequireDefault(__nccwpck_require__(9708)); -var _v = _interopRequireDefault(__nccwpck_require__(5552)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(9829)); -var _v2 = _interopRequireDefault(__nccwpck_require__(5978)); -var _v3 = _interopRequireDefault(__nccwpck_require__(3491)); -var _v4 = _interopRequireDefault(__nccwpck_require__(8028)); -var _v5 = _interopRequireDefault(__nccwpck_require__(4117)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(7849)); -var _v6 = _interopRequireDefault(__nccwpck_require__(22)); -var _validate = _interopRequireDefault(__nccwpck_require__(687)); -var _version = _interopRequireDefault(__nccwpck_require__(677)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 5607: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 5465: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 7210: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 5190: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 3922: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(687)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - let v; - const arr = new Uint8Array(16); - - // Parse ########-....-....-....-............ - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; - - // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; - - // Parse ........-....-####-....-............ - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; - - // Parse ........-....-....-####-............ - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; - - // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} -var _default = exports["default"] = parse; - -/***/ }), - -/***/ 9194: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 9408: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 5908: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 9708: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; -var _validate = _interopRequireDefault(__nccwpck_require__(687)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); -} -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -var _default = exports["default"] = stringify; - -/***/ }), - -/***/ 5552: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(9408)); -var _stringify = __nccwpck_require__(9708); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -let _nodeId; -let _clockseq; - -// Previous uuid creation time -let _lastMSecs = 0; -let _lastNSecs = 0; - -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. We do this lazily to minimize issues - // related to insufficient system entropy. See #189 - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is - // handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v1; - -/***/ }), - -/***/ 9829: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(3922)); -var _stringify = __nccwpck_require__(9708); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 5978: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(6995)); -var _md = _interopRequireDefault(__nccwpck_require__(5465)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 6995: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; -var _stringify = __nccwpck_require__(9708); -var _parse = _interopRequireDefault(__nccwpck_require__(3922)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - return bytes; -} -const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - if (typeof value === 'string') { - value = stringToBytes(value); - } - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } - - // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); - } - - // Function#name is not settable on some platforms (#270) - try { - generateUUID.name = name; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 3491: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(7210)); -var _rng = _interopRequireDefault(__nccwpck_require__(9408)); -var _stringify = __nccwpck_require__(9708); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(rnds); -} -var _default = exports["default"] = v4; - -/***/ }), - -/***/ 8028: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(6995)); -var _sha = _interopRequireDefault(__nccwpck_require__(5908)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 4117: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(9708); -var _v = _interopRequireDefault(__nccwpck_require__(5552)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(9829)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 7849: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(3922)); -var _stringify = __nccwpck_require__(9708); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 22: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(9408)); -var _stringify = __nccwpck_require__(9708); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 687: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(9194)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 677: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(687)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 138: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "Zu", ({ - enumerable: true, - get: function () { - return _max.default; - } -})); -Object.defineProperty(exports, "wD", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "qg", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "As", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "bV", ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "v6", ({ - enumerable: true, - get: function () { - return _v5.default; - } -})); -Object.defineProperty(exports, "JE", ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -})); -Object.defineProperty(exports, "v7", ({ - enumerable: true, - get: function () { - return _v6.default; - } -})); -Object.defineProperty(exports, "tf", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "rE", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -var _max = _interopRequireDefault(__nccwpck_require__(8712)); -var _nil = _interopRequireDefault(__nccwpck_require__(5509)); -var _parse = _interopRequireDefault(__nccwpck_require__(4041)); -var _stringify = _interopRequireDefault(__nccwpck_require__(3213)); -var _v = _interopRequireDefault(__nccwpck_require__(4397)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(6180)); -var _v2 = _interopRequireDefault(__nccwpck_require__(9979)); -var _v3 = _interopRequireDefault(__nccwpck_require__(4066)); -var _v4 = _interopRequireDefault(__nccwpck_require__(7969)); -var _v5 = _interopRequireDefault(__nccwpck_require__(7832)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(7000)); -var _v6 = _interopRequireDefault(__nccwpck_require__(2447)); -var _validate = _interopRequireDefault(__nccwpck_require__(5454)); -var _version = _interopRequireDefault(__nccwpck_require__(9838)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 8712: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 7526: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 6439: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 5509: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 4041: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(5454)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - let v; - const arr = new Uint8Array(16); - - // Parse ########-....-....-....-............ - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; - - // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; - - // Parse ........-....-####-....-............ - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; - - // Parse ........-....-....-####-............ - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; - - // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} -var _default = exports["default"] = parse; - -/***/ }), - -/***/ 3725: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 2079: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 6401: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 3213: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; -var _validate = _interopRequireDefault(__nccwpck_require__(5454)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); -} -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -var _default = exports["default"] = stringify; - -/***/ }), - -/***/ 4397: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(2079)); -var _stringify = __nccwpck_require__(3213); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -let _nodeId; -let _clockseq; - -// Previous uuid creation time -let _lastMSecs = 0; -let _lastNSecs = 0; - -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. We do this lazily to minimize issues - // related to insufficient system entropy. See #189 - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is - // handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v1; - -/***/ }), - -/***/ 6180: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(4041)); -var _stringify = __nccwpck_require__(3213); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 9979: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(6280)); -var _md = _interopRequireDefault(__nccwpck_require__(7526)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 6280: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; -var _stringify = __nccwpck_require__(3213); -var _parse = _interopRequireDefault(__nccwpck_require__(4041)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - return bytes; -} -const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - if (typeof value === 'string') { - value = stringToBytes(value); - } - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } - - // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); - } - - // Function#name is not settable on some platforms (#270) - try { - generateUUID.name = name; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 4066: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(6439)); -var _rng = _interopRequireDefault(__nccwpck_require__(2079)); -var _stringify = __nccwpck_require__(3213); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(rnds); -} -var _default = exports["default"] = v4; - -/***/ }), - -/***/ 7969: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(6280)); -var _sha = _interopRequireDefault(__nccwpck_require__(6401)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 7832: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(3213); -var _v = _interopRequireDefault(__nccwpck_require__(4397)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(6180)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 7000: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(4041)); -var _stringify = __nccwpck_require__(3213); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 2447: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(2079)); -var _stringify = __nccwpck_require__(3213); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 5454: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(3725)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 9838: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(5454)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 7864: -/***/ ((module) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - createTokenAuth: () => createTokenAuth -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/auth.js -var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; -var REGEX_IS_INSTALLATION = /^ghs_/; -var REGEX_IS_USER_TO_SERVER = /^ghu_/; -async function auth(token) { - const isApp = token.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} - -// pkg/dist-src/with-authorization-prefix.js -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} - -// pkg/dist-src/hook.js -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} - -// pkg/dist-src/index.js -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 1897: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var index_exports = {}; -__export(index_exports, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(index_exports); -var import_universal_user_agent = __nccwpck_require__(3843); -var import_before_after_hook = __nccwpck_require__(2732); -var import_request = __nccwpck_require__(8636); -var import_graphql = __nccwpck_require__(7); -var import_auth_token = __nccwpck_require__(7864); - -// pkg/dist-src/version.js -var VERSION = "5.2.2"; - -// pkg/dist-src/index.js -var noop = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop; - } - if (typeof logger.info !== "function") { - logger.info = noop; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var Octokit = class { - static { - this.VERSION = VERSION; - } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static { - this.plugins = []; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static { - this.plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - } - }; - return NewOctokit; - } - constructor(options = {}) { - const hook = new import_before_after_hook.Collection(); - const requestDefaults = { - baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - this.request = import_request.request.defaults(requestDefaults); - this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); - this.log = createLogger(options.log); - this.hook = hook; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth = (0, import_auth_token.createTokenAuth)(options.auth); - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook.wrap("request", auth.hook); - this.auth = auth; - } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); - } - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 4471: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - endpoint: () => endpoint -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/defaults.js -var import_universal_user_agent = __nccwpck_require__(3843); - -// pkg/dist-src/version.js -var VERSION = "9.0.6"; - -// pkg/dist-src/defaults.js -var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; - -// pkg/dist-src/util/lowercase-keys.js -function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} - -// pkg/dist-src/util/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - if (Object.prototype.toString.call(value) !== "[object Object]") - return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) - return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} - -// pkg/dist-src/util/merge-deep.js -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject(options[key])) { - if (!(key in defaults)) - Object.assign(result, { [key]: options[key] }); - else - result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; -} - -// pkg/dist-src/util/remove-undefined-properties.js -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; -} - -// pkg/dist-src/merge.js -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); - } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} - -// pkg/dist-src/util/add-query-parameters.js -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; - } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -// pkg/dist-src/util/extract-url-variable-names.js -var urlVariableRegex = /\{[^{}}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); -} - -// pkg/dist-src/util/omit.js -function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } - } - return result; -} - -// pkg/dist-src/util/url-template.js -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value = context[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} - -// pkg/dist-src/parse.js -function parse(options) { - let method = options.method.toUpperCase(); - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format) => format.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); - } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } - } - } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} - -// pkg/dist-src/endpoint-with-defaults.js -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -// pkg/dist-src/with-defaults.js -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); -} - -// pkg/dist-src/index.js -var endpoint = withDefaults(null, DEFAULTS); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 7: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var index_exports = {}; -__export(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest -}); -module.exports = __toCommonJS(index_exports); -var import_request3 = __nccwpck_require__(8636); -var import_universal_user_agent = __nccwpck_require__(3843); - -// pkg/dist-src/version.js -var VERSION = "7.1.1"; - -// pkg/dist-src/with-defaults.js -var import_request2 = __nccwpck_require__(8636); - -// pkg/dist-src/graphql.js -var import_request = __nccwpck_require__(8636); - -// pkg/dist-src/error.js -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); -} -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } -}; - -// pkg/dist-src/graphql.js -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); - } - } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); -} - -// pkg/dist-src/with-defaults.js -function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); -} - -// pkg/dist-src/index.js -var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); -} -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 8082: -/***/ ((module) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - composePaginateRest: () => composePaginateRest, - isPaginatingEndpoint: () => isPaginatingEndpoint, - paginateRest: () => paginateRest, - paginatingEndpoints: () => paginatingEndpoints -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "9.2.2"; - -// pkg/dist-src/normalize-paginated-list-response.js -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) - return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - return response; -} - -// pkg/dist-src/iterator.js -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) - return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - return { value: normalizedResponse }; - } catch (error) { - if (error.status !== 409) - throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} - -// pkg/dist-src/paginate.js -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} - -// pkg/dist-src/compose-paginate.js -var composePaginateRest = Object.assign(paginate, { - iterator -}); - -// pkg/dist-src/generated/paginating-endpoints.js -var paginatingEndpoints = [ - "GET /advisories", - "GET /app/hook/deliveries", - "GET /app/installation-requests", - "GET /app/installations", - "GET /assignments/{assignment_id}/accepted_assignments", - "GET /classrooms", - "GET /classrooms/{classroom_id}/assignments", - "GET /enterprises/{enterprise}/dependabot/alerts", - "GET /enterprises/{enterprise}/secret-scanning/alerts", - "GET /events", - "GET /gists", - "GET /gists/public", - "GET /gists/starred", - "GET /gists/{gist_id}/comments", - "GET /gists/{gist_id}/commits", - "GET /gists/{gist_id}/forks", - "GET /installation/repositories", - "GET /issues", - "GET /licenses", - "GET /marketplace_listing/plans", - "GET /marketplace_listing/plans/{plan_id}/accounts", - "GET /marketplace_listing/stubbed/plans", - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", - "GET /networks/{owner}/{repo}/events", - "GET /notifications", - "GET /organizations", - "GET /orgs/{org}/actions/cache/usage-by-repository", - "GET /orgs/{org}/actions/permissions/repositories", - "GET /orgs/{org}/actions/runners", - "GET /orgs/{org}/actions/secrets", - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", - "GET /orgs/{org}/actions/variables", - "GET /orgs/{org}/actions/variables/{name}/repositories", - "GET /orgs/{org}/blocks", - "GET /orgs/{org}/code-scanning/alerts", - "GET /orgs/{org}/codespaces", - "GET /orgs/{org}/codespaces/secrets", - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", - "GET /orgs/{org}/copilot/billing/seats", - "GET /orgs/{org}/dependabot/alerts", - "GET /orgs/{org}/dependabot/secrets", - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", - "GET /orgs/{org}/events", - "GET /orgs/{org}/failed_invitations", - "GET /orgs/{org}/hooks", - "GET /orgs/{org}/hooks/{hook_id}/deliveries", - "GET /orgs/{org}/installations", - "GET /orgs/{org}/invitations", - "GET /orgs/{org}/invitations/{invitation_id}/teams", - "GET /orgs/{org}/issues", - "GET /orgs/{org}/members", - "GET /orgs/{org}/members/{username}/codespaces", - "GET /orgs/{org}/migrations", - "GET /orgs/{org}/migrations/{migration_id}/repositories", - "GET /orgs/{org}/organization-roles/{role_id}/teams", - "GET /orgs/{org}/organization-roles/{role_id}/users", - "GET /orgs/{org}/outside_collaborators", - "GET /orgs/{org}/packages", - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - "GET /orgs/{org}/personal-access-token-requests", - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", - "GET /orgs/{org}/personal-access-tokens", - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", - "GET /orgs/{org}/projects", - "GET /orgs/{org}/properties/values", - "GET /orgs/{org}/public_members", - "GET /orgs/{org}/repos", - "GET /orgs/{org}/rulesets", - "GET /orgs/{org}/rulesets/rule-suites", - "GET /orgs/{org}/secret-scanning/alerts", - "GET /orgs/{org}/security-advisories", - "GET /orgs/{org}/teams", - "GET /orgs/{org}/teams/{team_slug}/discussions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/invitations", - "GET /orgs/{org}/teams/{team_slug}/members", - "GET /orgs/{org}/teams/{team_slug}/projects", - "GET /orgs/{org}/teams/{team_slug}/repos", - "GET /orgs/{org}/teams/{team_slug}/teams", - "GET /projects/columns/{column_id}/cards", - "GET /projects/{project_id}/collaborators", - "GET /projects/{project_id}/columns", - "GET /repos/{owner}/{repo}/actions/artifacts", - "GET /repos/{owner}/{repo}/actions/caches", - "GET /repos/{owner}/{repo}/actions/organization-secrets", - "GET /repos/{owner}/{repo}/actions/organization-variables", - "GET /repos/{owner}/{repo}/actions/runners", - "GET /repos/{owner}/{repo}/actions/runs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", - "GET /repos/{owner}/{repo}/actions/secrets", - "GET /repos/{owner}/{repo}/actions/variables", - "GET /repos/{owner}/{repo}/actions/workflows", - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", - "GET /repos/{owner}/{repo}/activity", - "GET /repos/{owner}/{repo}/assignees", - "GET /repos/{owner}/{repo}/branches", - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", - "GET /repos/{owner}/{repo}/code-scanning/alerts", - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - "GET /repos/{owner}/{repo}/code-scanning/analyses", - "GET /repos/{owner}/{repo}/codespaces", - "GET /repos/{owner}/{repo}/codespaces/devcontainers", - "GET /repos/{owner}/{repo}/codespaces/secrets", - "GET /repos/{owner}/{repo}/collaborators", - "GET /repos/{owner}/{repo}/comments", - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/commits", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", - "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", - "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", - "GET /repos/{owner}/{repo}/commits/{ref}/status", - "GET /repos/{owner}/{repo}/commits/{ref}/statuses", - "GET /repos/{owner}/{repo}/contributors", - "GET /repos/{owner}/{repo}/dependabot/alerts", - "GET /repos/{owner}/{repo}/dependabot/secrets", - "GET /repos/{owner}/{repo}/deployments", - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", - "GET /repos/{owner}/{repo}/environments", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", - "GET /repos/{owner}/{repo}/events", - "GET /repos/{owner}/{repo}/forks", - "GET /repos/{owner}/{repo}/hooks", - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", - "GET /repos/{owner}/{repo}/invitations", - "GET /repos/{owner}/{repo}/issues", - "GET /repos/{owner}/{repo}/issues/comments", - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/issues/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", - "GET /repos/{owner}/{repo}/issues/{issue_number}/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", - "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", - "GET /repos/{owner}/{repo}/keys", - "GET /repos/{owner}/{repo}/labels", - "GET /repos/{owner}/{repo}/milestones", - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", - "GET /repos/{owner}/{repo}/notifications", - "GET /repos/{owner}/{repo}/pages/builds", - "GET /repos/{owner}/{repo}/projects", - "GET /repos/{owner}/{repo}/pulls", - "GET /repos/{owner}/{repo}/pulls/comments", - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", - "GET /repos/{owner}/{repo}/releases", - "GET /repos/{owner}/{repo}/releases/{release_id}/assets", - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", - "GET /repos/{owner}/{repo}/rules/branches/{branch}", - "GET /repos/{owner}/{repo}/rulesets", - "GET /repos/{owner}/{repo}/rulesets/rule-suites", - "GET /repos/{owner}/{repo}/secret-scanning/alerts", - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", - "GET /repos/{owner}/{repo}/security-advisories", - "GET /repos/{owner}/{repo}/stargazers", - "GET /repos/{owner}/{repo}/subscribers", - "GET /repos/{owner}/{repo}/tags", - "GET /repos/{owner}/{repo}/teams", - "GET /repos/{owner}/{repo}/topics", - "GET /repositories", - "GET /repositories/{repository_id}/environments/{environment_name}/secrets", - "GET /repositories/{repository_id}/environments/{environment_name}/variables", - "GET /search/code", - "GET /search/commits", - "GET /search/issues", - "GET /search/labels", - "GET /search/repositories", - "GET /search/topics", - "GET /search/users", - "GET /teams/{team_id}/discussions", - "GET /teams/{team_id}/discussions/{discussion_number}/comments", - "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /teams/{team_id}/discussions/{discussion_number}/reactions", - "GET /teams/{team_id}/invitations", - "GET /teams/{team_id}/members", - "GET /teams/{team_id}/projects", - "GET /teams/{team_id}/repos", - "GET /teams/{team_id}/teams", - "GET /user/blocks", - "GET /user/codespaces", - "GET /user/codespaces/secrets", - "GET /user/emails", - "GET /user/followers", - "GET /user/following", - "GET /user/gpg_keys", - "GET /user/installations", - "GET /user/installations/{installation_id}/repositories", - "GET /user/issues", - "GET /user/keys", - "GET /user/marketplace_purchases", - "GET /user/marketplace_purchases/stubbed", - "GET /user/memberships/orgs", - "GET /user/migrations", - "GET /user/migrations/{migration_id}/repositories", - "GET /user/orgs", - "GET /user/packages", - "GET /user/packages/{package_type}/{package_name}/versions", - "GET /user/public_emails", - "GET /user/repos", - "GET /user/repository_invitations", - "GET /user/social_accounts", - "GET /user/ssh_signing_keys", - "GET /user/starred", - "GET /user/subscriptions", - "GET /user/teams", - "GET /users", - "GET /users/{username}/events", - "GET /users/{username}/events/orgs/{org}", - "GET /users/{username}/events/public", - "GET /users/{username}/followers", - "GET /users/{username}/following", - "GET /users/{username}/gists", - "GET /users/{username}/gpg_keys", - "GET /users/{username}/keys", - "GET /users/{username}/orgs", - "GET /users/{username}/packages", - "GET /users/{username}/projects", - "GET /users/{username}/received_events", - "GET /users/{username}/received_events/public", - "GET /users/{username}/repos", - "GET /users/{username}/social_accounts", - "GET /users/{username}/ssh_signing_keys", - "GET /users/{username}/starred", - "GET /users/{username}/subscriptions" -]; - -// pkg/dist-src/paginating-endpoints.js -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } -} - -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 4935: -/***/ ((module) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - legacyRestEndpointMethods: () => legacyRestEndpointMethods, - restEndpointMethods: () => restEndpointMethods -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "10.4.1"; - -// pkg/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repositories/{repository_id}/environments/{environment_name}/variables" - ], - createOrUpdateEnvironmentSecret: [ - "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables" - ], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: [ - "DELETE /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" - } - ], - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getCommitAuthors: [ - "GET /repos/{owner}/{repo}/import/authors", - {}, - { - deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" - } - ], - getImportStatus: [ - "GET /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" - } - ], - getLargeFiles: [ - "GET /repos/{owner}/{repo}/import/large_files", - {}, - { - deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" - } - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - mapCommitAuthor: [ - "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", - {}, - { - deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" - } - ], - setLfsPreference: [ - "PATCH /repos/{owner}/{repo}/import/lfs", - {}, - { - deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" - } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: [ - "PUT /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" - } - ], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ], - updateImport: [ - "PATCH /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" - } - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}" - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], - createInvitation: ["POST /orgs/{org}/invitations"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteCustomOrganizationRole: [ - "DELETE /orgs/{org}/organization-roles/{role_id}" - ], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - enableOrDisableSecurityProductOnAllOrgRepos: [ - "POST /orgs/{org}/{security_product}/{enablement}" - ], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - patchCustomOrganizationRole: [ - "PATCH /orgs/{org}/organization-roles/{role_id}" - ], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}" - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], - createCard: ["POST /projects/columns/{column_id}/cards"], - createColumn: ["POST /projects/{project_id}/columns"], - createForAuthenticatedUser: ["POST /user/projects"], - createForOrg: ["POST /orgs/{org}/projects"], - createForRepo: ["POST /repos/{owner}/{repo}/projects"], - delete: ["DELETE /projects/{project_id}"], - deleteCard: ["DELETE /projects/columns/cards/{card_id}"], - deleteColumn: ["DELETE /projects/columns/{column_id}"], - get: ["GET /projects/{project_id}"], - getCard: ["GET /projects/columns/cards/{card_id}"], - getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: [ - "GET /projects/{project_id}/collaborators/{username}/permission" - ], - listCards: ["GET /projects/columns/{column_id}/cards"], - listCollaborators: ["GET /projects/{project_id}/collaborators"], - listColumns: ["GET /projects/{project_id}/columns"], - listForOrg: ["GET /orgs/{org}/projects"], - listForRepo: ["GET /repos/{owner}/{repo}/projects"], - listForUser: ["GET /users/{username}/projects"], - moveCard: ["POST /projects/columns/cards/{card_id}/moves"], - moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: [ - "DELETE /projects/{project_id}/collaborators/{username}" - ], - update: ["PATCH /projects/{project_id}"], - updateCard: ["PATCH /projects/columns/cards/{card_id}"], - updateColumn: ["PATCH /projects/columns/{column_id}"] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateCustomPropertiesValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" - ], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteTagProtection: [ - "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" - ], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" - ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ] - }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" - ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateProjectPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForProjectInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeProjectInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// pkg/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; - }, - set(target, methodName, value) { - return target.cache[methodName] = value; - }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// pkg/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 3708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - RequestError: () => RequestError -}); -module.exports = __toCommonJS(dist_src_exports); -var import_deprecation = __nccwpck_require__(4150); -var import_once = __toESM(__nccwpck_require__(5560)); -var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); -var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); -var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - request: () => request -}); -module.exports = __toCommonJS(dist_src_exports); -var import_endpoint = __nccwpck_require__(4471); -var import_universal_user_agent = __nccwpck_require__(3843); - -// pkg/dist-src/version.js -var VERSION = "8.4.1"; - -// pkg/dist-src/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - if (Object.prototype.toString.call(value) !== "[object Object]") - return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) - return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} - -// pkg/dist-src/fetch-wrapper.js -var import_request_error = __nccwpck_require__(3708); - -// pkg/dist-src/get-buffer-response.js -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -// pkg/dist-src/fetch-wrapper.js -function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - throw new Error( - "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.link.match(/<([^<>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error) => { - if (error instanceof import_request_error.RequestError) - throw error; - else if (error.name === "AbortError") - throw error; - let message = error.message; - if (error.name === "TypeError" && "cause" in error) { - if (error.cause instanceof Error) { - message = error.cause.message; - } else if (typeof error.cause === "string") { - message = error.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (/application\/json/.test(contentType)) { - return response.json().catch(() => response.text()).catch(() => ""); - } - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } - return getBufferResponse(response); -} -function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} - -// pkg/dist-src/with-defaults.js -function withDefaults(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); -} - -// pkg/dist-src/index.js -var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } -}); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 8793: -/***/ ((__unused_webpack_module, exports) => { - - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - - -/***/ }), - -/***/ 2732: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(1063); -var addHook = __nccwpck_require__(2027); -var removeHook = __nccwpck_require__(9934); - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); - -function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); -} - -function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} - -function HookCollection() { - var state = { - registry: {}, - }; - - var hook = register.bind(null, state); - bindApi(hook, state); - - return hook; -} - -var collectionHookDeprecationMessageDisplayed = false; -function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; - } - return HookCollection(); -} - -Hook.Singular = HookSingular.bind(); -Hook.Collection = HookCollection.bind(); - -module.exports = Hook; -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook; -module.exports.Singular = Hook.Singular; -module.exports.Collection = Hook.Collection; - - -/***/ }), - -/***/ 2027: -/***/ ((module) => { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} - - -/***/ }), - -/***/ 1063: -/***/ ((module) => { - -module.exports = register; - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - - -/***/ }), - -/***/ 9934: -/***/ ((module) => { - -module.exports = removeHook; - -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); - - if (index === -1) { - return; - } - - state.registry[name].splice(index, 1); -} - - -/***/ }), - -/***/ 8203: -/***/ ((module) => { - - -module.exports = function (str, sep) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - sep = typeof sep === 'undefined' ? '_' : sep; - - return str - .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') - .toLowerCase(); -}; - - -/***/ }), - -/***/ 4150: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'Deprecation'; - } - -} - -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 2415: -/***/ ((module) => { - - - -var has = Object.prototype.hasOwnProperty - , prefix = '~'; - -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} - -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} - -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} - -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - - return emitter; -} - -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} - -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} - -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) return names; - - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; -}; - -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; -}; - -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; - -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return false; - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } - - listeners[i].fn.apply(listeners[i].context, args); - } - } - } - - return true; -}; - -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; - -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; - -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; -}; - -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; -}; - -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; - -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; - -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; -} - - -/***/ }), - -/***/ 157: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "Zu", ({ - enumerable: true, - get: function () { - return _max.default; - } -})); -Object.defineProperty(exports, "wD", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "qg", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "As", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "bV", ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "v6", ({ - enumerable: true, - get: function () { - return _v5.default; - } -})); -Object.defineProperty(exports, "JE", ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -})); -Object.defineProperty(exports, "v7", ({ - enumerable: true, - get: function () { - return _v6.default; - } -})); -Object.defineProperty(exports, "tf", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "rE", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -var _max = _interopRequireDefault(__nccwpck_require__(8391)); -var _nil = _interopRequireDefault(__nccwpck_require__(6054)); -var _parse = _interopRequireDefault(__nccwpck_require__(7522)); -var _stringify = _interopRequireDefault(__nccwpck_require__(3180)); -var _v = _interopRequireDefault(__nccwpck_require__(7408)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(1205)); -var _v2 = _interopRequireDefault(__nccwpck_require__(5674)); -var _v3 = _interopRequireDefault(__nccwpck_require__(5715)); -var _v4 = _interopRequireDefault(__nccwpck_require__(9628)); -var _v5 = _interopRequireDefault(__nccwpck_require__(3586)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(5801)); -var _v6 = _interopRequireDefault(__nccwpck_require__(2246)); -var _validate = _interopRequireDefault(__nccwpck_require__(1647)); -var _version = _interopRequireDefault(__nccwpck_require__(693)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 8391: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 4601: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 4458: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 6054: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 7522: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(1647)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - let v; - const arr = new Uint8Array(16); - - // Parse ########-....-....-....-............ - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; - - // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; - - // Parse ........-....-####-....-............ - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; - - // Parse ........-....-....-####-............ - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; - - // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} -var _default = exports["default"] = parse; - -/***/ }), - -/***/ 5754: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 9088: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 292: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 3180: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; -var _validate = _interopRequireDefault(__nccwpck_require__(1647)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); -} -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -var _default = exports["default"] = stringify; - -/***/ }), - -/***/ 7408: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(9088)); -var _stringify = __nccwpck_require__(3180); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -let _nodeId; -let _clockseq; - -// Previous uuid creation time -let _lastMSecs = 0; -let _lastNSecs = 0; - -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. We do this lazily to minimize issues - // related to insufficient system entropy. See #189 - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is - // handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v1; - -/***/ }), - -/***/ 1205: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(7522)); -var _stringify = __nccwpck_require__(3180); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 5674: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(4579)); -var _md = _interopRequireDefault(__nccwpck_require__(4601)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 4579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; -var _stringify = __nccwpck_require__(3180); -var _parse = _interopRequireDefault(__nccwpck_require__(7522)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - return bytes; -} -const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - if (typeof value === 'string') { - value = stringToBytes(value); - } - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } - - // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); - } - - // Function#name is not settable on some platforms (#270) - try { - generateUUID.name = name; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 5715: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(4458)); -var _rng = _interopRequireDefault(__nccwpck_require__(9088)); -var _stringify = __nccwpck_require__(3180); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(rnds); -} -var _default = exports["default"] = v4; - -/***/ }), - -/***/ 9628: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(4579)); -var _sha = _interopRequireDefault(__nccwpck_require__(292)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 3586: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(3180); -var _v = _interopRequireDefault(__nccwpck_require__(7408)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(1205)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 5801: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(7522)); -var _stringify = __nccwpck_require__(3180); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 2246: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(9088)); -var _stringify = __nccwpck_require__(3180); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 1647: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(5754)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 693: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(1647)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 5560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var wrappy = __nccwpck_require__(8264) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), - -/***/ 2766: -/***/ ((module) => { - - -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); - - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; - - -/***/ }), - -/***/ 6459: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const EventEmitter = __nccwpck_require__(2415); -const p_timeout_1 = __nccwpck_require__(4802); -const priority_queue_1 = __nccwpck_require__(5905); -// eslint-disable-next-line @typescript-eslint/no-empty-function -const empty = () => { }; -const timeoutError = new p_timeout_1.TimeoutError(); -/** -Promise queue with concurrency control. -*/ -class PQueue extends EventEmitter { - constructor(options) { - var _a, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; - } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; - } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit('next'); - } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit('idle'); - } - } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = undefined; - } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === undefined) { - const delay = this._intervalEnd - now; - if (delay < 0) { - // Act as the interval was done - // We don't need to resume it here because it will be resumed on line 160 - this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; - } - else { - // Act as the interval is pending - if (this._timeoutId === undefined) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - // We can clear the interval ("pause") - // Because we can redo it later ("resume") - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = undefined; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit('active'); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; - } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== undefined) { - return; - } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; - } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - // eslint-disable-next-line no-empty - while (this._tryToStartAnother()) { } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { - if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return undefined; - }); - resolve(await operation); - } - catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit('add'); - }); - } - /** - Same as `.add()`, but accepts an array of sync or async functions. - - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; - } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); - } - /** - Can be called multiple times. Useful if you for example add additional items at a later time. - - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - // Instantly resolve if the queue is empty - if (this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - // Instantly resolve if none pending and if nothing else is queued - if (this._pendingCount === 0 && this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. - - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - return this._queue.filter(options).length; - } - /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; - } - /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; - } - /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; - } -} -exports["default"] = PQueue; - - -/***/ }), - -/***/ 9015: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound -// Used to compute insertion index to keep queue sorted after insertion -function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = (count / 2) | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count -= step + 1; - } - else { - count = step; - } - } - return first; -} -exports["default"] = lowerBound; - - -/***/ }), - -/***/ 5905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lower_bound_1 = __nccwpck_require__(9015); -class PriorityQueue { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; - } - const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); - this._queue.splice(index, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } -} -exports["default"] = PriorityQueue; - - -/***/ }), - -/***/ 2103: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const retry = __nccwpck_require__(5546); - -const networkErrorMsgs = [ - 'Failed to fetch', // Chrome - 'NetworkError when attempting to fetch resource.', // Firefox - 'The Internet connection appears to be offline.', // Safari - 'Network request failed' // `cross-fetch` -]; - -class AbortError extends Error { - constructor(message) { - super(); - - if (message instanceof Error) { - this.originalError = message; - ({message} = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } - - this.name = 'AbortError'; - this.message = message; - } -} - -const decorateErrorWithCounts = (error, attemptNumber, options) => { - // Minus 1 from attemptNumber because the first attempt does not count as a retry - const retriesLeft = options.retries - (attemptNumber - 1); - - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; -}; - -const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); - -const pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => {}, - retries: 10, - ...options - }; - - const operation = retry.operation(options); - - operation.attempt(async attemptNumber => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - - try { - await options.onFailedAttempt(error); - } catch (error) { - reject(error); - return; - } - - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); -}); - -module.exports = pRetry; -// TODO: remove this in the next major version -module.exports["default"] = pRetry; - -module.exports.AbortError = AbortError; - - -/***/ }), - -/***/ 4802: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const pFinally = __nccwpck_require__(2766); - -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } -} - -const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== 'number' || milliseconds < 0) { - throw new TypeError('Expected `milliseconds` to be a positive number'); - } - - if (milliseconds === Infinity) { - resolve(promise); - return; - } - - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } - - return; - } - - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); - - if (typeof promise.cancel === 'function') { - promise.cancel(); - } - - reject(timeoutError); - }, milliseconds); - - // TODO: Use native `finally` keyword when targeting Node.js 10 - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); - -module.exports = pTimeout; -// TODO: Remove this for the next major release -module.exports["default"] = pTimeout; - -module.exports.TimeoutError = TimeoutError; - - -/***/ }), - -/***/ 5546: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(7084); - -/***/ }), - -/***/ 7084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var RetryOperation = __nccwpck_require__(9538); - -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; - -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } - - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } - - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); - } - - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } - - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); - } - - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); - - return timeouts; -}; - -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; - - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - - return timeout; -}; - -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } - - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } - } - - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; - - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; - - -/***/ }), - -/***/ 9538: -/***/ ((module) => { - -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } - - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; - - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; - -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); -} - -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } - - this._timeouts = []; - this._cachedTimeouts = null; -}; - -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; - } - - this._errors.push(err); - - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } - } - - var self = this; - this._timer = setTimeout(function() { - self._attempts++; - - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); - - if (self._options.unref) { - self._timeout.unref(); - } - } - - self._fn(self._attempts); - }, timeout); - - if (this._options.unref) { - this._timer.unref(); - } - - return true; -}; - -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } - - this._operationStart = new Date().getTime(); - - this._fn(this._attempts); -}; - -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = RetryOperation.prototype.try; - -RetryOperation.prototype.errors = function() { - return this._errors; -}; - -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; - -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - - counts[message] = count; - - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } - } - - return mainError; -}; - - -/***/ }), - -/***/ 9379: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY - } - - constructor (comp, options) { - options = parseOptions(options) - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - comp = comp.trim().split(/\s+/).join(' ') - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } - } - - toString () { - return this.value - } - - test (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } - - options = parseOptions(options) - - // Special cases where nothing can possibly be lower - if (options.includePrerelease && - (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { - return false - } - if (!options.includePrerelease && - (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { - return false - } - - // Same direction increasing (> or >=) - if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { - return true - } - // Same direction decreasing (< or <=) - if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { - return true - } - // same SemVer and both sides are inclusive (<= or >=) - if ( - (this.semver.version === comp.semver.version) && - this.operator.includes('=') && comp.operator.includes('=')) { - return true - } - // opposite directions less than - if (cmp(this.semver, '<', comp.semver, options) && - this.operator.startsWith('>') && comp.operator.startsWith('<')) { - return true - } - // opposite directions greater than - if (cmp(this.semver, '>', comp.semver, options) && - this.operator.startsWith('<') && comp.operator.startsWith('>')) { - return true - } - return false - } -} - -module.exports = Comparator - -const parseOptions = __nccwpck_require__(356) -const { safeRe: re, t } = __nccwpck_require__(5471) -const cmp = __nccwpck_require__(8646) -const debug = __nccwpck_require__(1159) -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) - - -/***/ }), - -/***/ 6782: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SPACE_CHARACTERS = /\s+/g - -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - options = parseOptions(options) - - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.formatted = undefined - return this - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First reduce all whitespace as much as possible so we do not have to rely - // on potentially slow regexes like \s*. This is then stored and used for - // future error messages as well. - this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') - - // First, split on || - this.set = this.raw - .split('||') - // map the range to a 2d array of comparators - .map(r => this.parseRange(r.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0] - this.set = this.set.filter(c => !isNullSet(c[0])) - if (this.set.length === 0) { - this.set = [first] - } else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c] - break - } - } - } - } - - this.formatted = undefined - } - - get range () { - if (this.formatted === undefined) { - this.formatted = '' - for (let i = 0; i < this.set.length; i++) { - if (i > 0) { - this.formatted += '||' - } - const comps = this.set[i] - for (let k = 0; k < comps.length; k++) { - if (k > 0) { - this.formatted += ' ' - } - this.formatted += comps[k].toString().trim() - } - } - } - return this.formatted - } - - format () { - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = - (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | - (this.options.loose && FLAG_LOOSE) - const memoKey = memoOpts + ':' + range - const cached = cache.get(memoKey) - if (cached) { - return cached - } - - const loose = this.options.loose - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) - debug('hyphen replace', range) - - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - debug('tilde trim', range) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - debug('caret trim', range) - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - let rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - - if (loose) { - // in loose mode, throw out any that are not valid comparators - rangeList = rangeList.filter(comp => { - debug('loose invalid filter', comp, this.options) - return !!comp.match(re[t.COMPARATORLOOSE]) - }) - } - debug('range list', rangeList) - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - const rangeMap = new Map() - const comparators = rangeList.map(comp => new Comparator(comp, this.options)) - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp] - } - rangeMap.set(comp.value, comp) - } - if (rangeMap.size > 1 && rangeMap.has('')) { - rangeMap.delete('') - } - - const result = [...rangeMap.values()] - cache.set(memoKey, result) - return result - } - - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } -} - -module.exports = Range - -const LRU = __nccwpck_require__(1383) -const cache = new LRU() - -const parseOptions = __nccwpck_require__(356) -const Comparator = __nccwpck_require__(9379) -const debug = __nccwpck_require__(1159) -const SemVer = __nccwpck_require__(7163) -const { - safeRe: re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace, -} = __nccwpck_require__(5471) -const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101) - -const isNullSet = c => c.value === '<0.0.0-0' -const isAny = c => c.value === '' - -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) - - testComparator = remainingComparators.pop() - } - - return result -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - comp = comp.replace(re[t.BUILD], '') - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 -// ~0.0.1 --> >=0.0.1 <0.1.0-0 -const replaceTildes = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceTilde(c, options)) - .join(' ') -} - -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0` - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 -// ^1.2.3 --> >=1.2.3 <2.0.0-0 -// ^1.2.0 --> >=1.2.0 <2.0.0-0 -// ^0.0.1 --> >=0.0.1 <0.0.2-0 -// ^0.1.0 --> >=0.1.0 <0.2.0-0 -const replaceCarets = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceCaret(c, options)) - .join(' ') -} - -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - const z = options.includePrerelease ? '-0' : '' - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0` - } - } - - debug('caret return', ret) - return ret - }) -} - -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp - .split(/\s+/) - .map((c) => replaceXRange(c, options)) - .join(' ') -} - -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - if (gtlt === '<') { - pr = '-0' - } - - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0` - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp - .trim() - .replace(re[t.STAR], '') -} - -const replaceGTE0 = (comp, options) => { - debug('replaceGTE0', comp, options) - return comp - .trim() - .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') -} - -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 -// TODO build? -const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` - } else if (fpr) { - from = `>=${from}` - } else { - from = `>=${from}${incPr ? '-0' : ''}` - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0` - } else { - to = `<=${to}` - } - - return `${from} ${to}`.trim() -} - -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - - -/***/ }), - -/***/ 7163: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const debug = __nccwpck_require__(1159) -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101) -const { safeRe: re, t } = __nccwpck_require__(5471) - -const parseOptions = __nccwpck_require__(356) -const { compareIdentifiers } = __nccwpck_require__(3348) -class SemVer { - constructor (version, options) { - options = parseOptions(options) - - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease - - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer(other, this.options) - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - if (this.major < other.major) { - return -1 - } - if (this.major > other.major) { - return 1 - } - if (this.minor < other.minor) { - return -1 - } - if (this.minor > other.minor) { - return 1 - } - if (this.patch < other.patch) { - return -1 - } - if (this.patch > other.patch) { - return 1 - } - return 0 - } - - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('build compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier, identifierBase) { - if (release.startsWith('pre')) { - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } - // Avoid an invalid semver results - if (identifier) { - const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) - if (!match || match[1] !== identifier) { - throw new Error(`invalid identifier: ${identifier}`) - } - } - } - - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier, identifierBase) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier, identifierBase) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier, identifierBase) - this.inc('pre', identifier, identifierBase) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier, identifierBase) - } - this.inc('pre', identifier, identifierBase) - break - case 'release': - if (this.prerelease.length === 0) { - throw new Error(`version ${this.raw} is not a prerelease`) - } - this.prerelease.length = 0 - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': { - const base = Number(identifierBase) ? 1 : 0 - - if (this.prerelease.length === 0) { - this.prerelease = [base] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - if (identifier === this.prerelease.join('.') && identifierBase === false) { - throw new Error('invalid increment argument: identifier already exists') - } - this.prerelease.push(base) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - let prerelease = [identifier, base] - if (identifierBase === false) { - prerelease = [identifier] - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease - } - } else { - this.prerelease = prerelease - } - } - break - } - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.raw = this.format() - if (this.build.length) { - this.raw += `+${this.build.join('.')}` - } - return this - } -} - -module.exports = SemVer - - -/***/ }), - -/***/ 1799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(6353) -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean - - -/***/ }), - -/***/ 8646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const eq = __nccwpck_require__(5082) -const neq = __nccwpck_require__(4974) -const gt = __nccwpck_require__(6599) -const gte = __nccwpck_require__(1236) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(6717) - -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a === b - - case '!==': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } -} -module.exports = cmp - - -/***/ }), - -/***/ 5385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const parse = __nccwpck_require__(6353) -const { safeRe: re, t } = __nccwpck_require__(5471) - -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } - - if (typeof version === 'number') { - version = String(version) - } - - if (typeof version !== 'string') { - return null - } - - options = options || {} - - let match = null - if (!options.rtl) { - match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] - let next - while ((next = coerceRtlRegex.exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - coerceRtlRegex.lastIndex = -1 - } - - if (match === null) { - return null - } - - const major = match[2] - const minor = match[3] || '0' - const patch = match[4] || '0' - const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' - const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' - - return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) -} -module.exports = coerce - - -/***/ }), - -/***/ 7648: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -module.exports = compareBuild - - -/***/ }), - -/***/ 6874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose - - -/***/ }), - -/***/ 8469: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) - -module.exports = compare - - -/***/ }), - -/***/ 711: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(6353) - -const diff = (version1, version2) => { - const v1 = parse(version1, null, true) - const v2 = parse(version2, null, true) - const comparison = v1.compare(v2) - - if (comparison === 0) { - return null - } - - const v1Higher = comparison > 0 - const highVersion = v1Higher ? v1 : v2 - const lowVersion = v1Higher ? v2 : v1 - const highHasPre = !!highVersion.prerelease.length - const lowHasPre = !!lowVersion.prerelease.length - - if (lowHasPre && !highHasPre) { - // Going from prerelease -> no prerelease requires some special casing - - // If the low version has only a major, then it will always be a major - // Some examples: - // 1.0.0-1 -> 1.0.0 - // 1.0.0-1 -> 1.1.1 - // 1.0.0-1 -> 2.0.0 - if (!lowVersion.patch && !lowVersion.minor) { - return 'major' - } - - // If the main part has no difference - if (lowVersion.compareMain(highVersion) === 0) { - if (lowVersion.minor && !lowVersion.patch) { - return 'minor' - } - return 'patch' - } - } - - // add the `pre` prefix if we are going to a prerelease version - const prefix = highHasPre ? 'pre' : '' - - if (v1.major !== v2.major) { - return prefix + 'major' - } - - if (v1.minor !== v2.minor) { - return prefix + 'minor' - } - - if (v1.patch !== v2.patch) { - return prefix + 'patch' - } - - // high and low are preleases - return 'prerelease' -} - -module.exports = diff - - -/***/ }), - -/***/ 5082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq - - -/***/ }), - -/***/ 6599: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt - - -/***/ }), - -/***/ 1236: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte - - -/***/ }), - -/***/ 2338: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) - -const inc = (version, release, options, identifier, identifierBase) => { - if (typeof (options) === 'string') { - identifierBase = identifier - identifier = options - options = undefined - } - - try { - return new SemVer( - version instanceof SemVer ? version.version : version, - options - ).inc(release, identifier, identifierBase).version - } catch (er) { - return null - } -} -module.exports = inc - - -/***/ }), - -/***/ 3872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt - - -/***/ }), - -/***/ 6717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte - - -/***/ }), - -/***/ 8511: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major - - -/***/ }), - -/***/ 2603: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor - - -/***/ }), - -/***/ 4974: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq - - -/***/ }), - -/***/ 6353: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const parse = (version, options, throwErrors = false) => { - if (version instanceof SemVer) { - return version - } - try { - return new SemVer(version, options) - } catch (er) { - if (!throwErrors) { - return null - } - throw er - } -} - -module.exports = parse - - -/***/ }), - -/***/ 8756: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch - - -/***/ }), - -/***/ 5714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(6353) -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -module.exports = prerelease - - -/***/ }), - -/***/ 2173: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare - - -/***/ }), - -/***/ 7192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compareBuild = __nccwpck_require__(7648) -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort - - -/***/ }), - -/***/ 8011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(6782) -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} -module.exports = satisfies - - -/***/ }), - -/***/ 9872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compareBuild = __nccwpck_require__(7648) -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort - - -/***/ }), - -/***/ 8780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(6353) -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null -} -module.exports = valid - - -/***/ }), - -/***/ 2088: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// just pre-load all the stuff that index.js lazily exports -const internalRe = __nccwpck_require__(5471) -const constants = __nccwpck_require__(5101) -const SemVer = __nccwpck_require__(7163) -const identifiers = __nccwpck_require__(3348) -const parse = __nccwpck_require__(6353) -const valid = __nccwpck_require__(8780) -const clean = __nccwpck_require__(1799) -const inc = __nccwpck_require__(2338) -const diff = __nccwpck_require__(711) -const major = __nccwpck_require__(8511) -const minor = __nccwpck_require__(2603) -const patch = __nccwpck_require__(8756) -const prerelease = __nccwpck_require__(5714) -const compare = __nccwpck_require__(8469) -const rcompare = __nccwpck_require__(2173) -const compareLoose = __nccwpck_require__(6874) -const compareBuild = __nccwpck_require__(7648) -const sort = __nccwpck_require__(9872) -const rsort = __nccwpck_require__(7192) -const gt = __nccwpck_require__(6599) -const lt = __nccwpck_require__(3872) -const eq = __nccwpck_require__(5082) -const neq = __nccwpck_require__(4974) -const gte = __nccwpck_require__(1236) -const lte = __nccwpck_require__(6717) -const cmp = __nccwpck_require__(8646) -const coerce = __nccwpck_require__(5385) -const Comparator = __nccwpck_require__(9379) -const Range = __nccwpck_require__(6782) -const satisfies = __nccwpck_require__(8011) -const toComparators = __nccwpck_require__(4750) -const maxSatisfying = __nccwpck_require__(5574) -const minSatisfying = __nccwpck_require__(8595) -const minVersion = __nccwpck_require__(1866) -const validRange = __nccwpck_require__(4737) -const outside = __nccwpck_require__(280) -const gtr = __nccwpck_require__(2276) -const ltr = __nccwpck_require__(5213) -const intersects = __nccwpck_require__(3465) -const simplifyRange = __nccwpck_require__(2028) -const subset = __nccwpck_require__(1489) -module.exports = { - parse, - valid, - clean, - inc, - diff, - major, - minor, - patch, - prerelease, - compare, - rcompare, - compareLoose, - compareBuild, - sort, - rsort, - gt, - lt, - eq, - neq, - gte, - lte, - cmp, - coerce, - Comparator, - Range, - satisfies, - toComparators, - maxSatisfying, - minSatisfying, - minVersion, - validRange, - outside, - gtr, - ltr, - intersects, - simplifyRange, - subset, - SemVer, - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - RELEASE_TYPES: constants.RELEASE_TYPES, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, -} - - -/***/ }), - -/***/ 5101: -/***/ ((module) => { - - - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -const SEMVER_SPEC_VERSION = '2.0.0' - -const MAX_LENGTH = 256 -const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || -/* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -const MAX_SAFE_COMPONENT_LENGTH = 16 - -// Max safe length for a build identifier. The max length minus 6 characters for -// the shortest version with a build 0.0.0+BUILD. -const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 - -const RELEASE_TYPES = [ - 'major', - 'premajor', - 'minor', - 'preminor', - 'patch', - 'prepatch', - 'prerelease', -] - -module.exports = { - MAX_LENGTH, - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_SAFE_INTEGER, - RELEASE_TYPES, - SEMVER_SPEC_VERSION, - FLAG_INCLUDE_PRERELEASE: 0b001, - FLAG_LOOSE: 0b010, -} - - -/***/ }), - -/***/ 1159: -/***/ ((module) => { - - - -const debug = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) -) ? (...args) => console.error('SEMVER', ...args) - : () => {} - -module.exports = debug - - -/***/ }), - -/***/ 3348: -/***/ ((module) => { - - - -const numeric = /^[0-9]+$/ -const compareIdentifiers = (a, b) => { - if (typeof a === 'number' && typeof b === 'number') { - return a === b ? 0 : a < b ? -1 : 1 - } - - const anum = numeric.test(a) - const bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) - -module.exports = { - compareIdentifiers, - rcompareIdentifiers, -} - - -/***/ }), - -/***/ 1383: -/***/ ((module) => { - - - -class LRUCache { - constructor () { - this.max = 1000 - this.map = new Map() - } - - get (key) { - const value = this.map.get(key) - if (value === undefined) { - return undefined - } else { - // Remove the key from the map and add it to the end - this.map.delete(key) - this.map.set(key, value) - return value - } - } - - delete (key) { - return this.map.delete(key) - } - - set (key, value) { - const deleted = this.delete(key) - - if (!deleted && value !== undefined) { - // If cache is full, delete the least recently used item - if (this.map.size >= this.max) { - const firstKey = this.map.keys().next().value - this.delete(firstKey) - } - - this.map.set(key, value) - } - - return this - } -} - -module.exports = LRUCache - - -/***/ }), - -/***/ 356: -/***/ ((module) => { - - - -// parse out just the options we care about -const looseOption = Object.freeze({ loose: true }) -const emptyOpts = Object.freeze({ }) -const parseOptions = options => { - if (!options) { - return emptyOpts - } - - if (typeof options !== 'object') { - return looseOption - } - - return options -} -module.exports = parseOptions - - -/***/ }), - -/***/ 5471: -/***/ ((module, exports, __nccwpck_require__) => { - - - -const { - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_LENGTH, -} = __nccwpck_require__(5101) -const debug = __nccwpck_require__(1159) -exports = module.exports = {} - -// The actual regexps go on exports.re -const re = exports.re = [] -const safeRe = exports.safeRe = [] -const src = exports.src = [] -const safeSrc = exports.safeSrc = [] -const t = exports.t = {} -let R = 0 - -const LETTERDASHNUMBER = '[a-zA-Z0-9-]' - -// Replace some greedy regex tokens to prevent regex dos issues. These regex are -// used internally via the safeRe object since all inputs in this library get -// normalized first to trim and collapse all extra whitespace. The original -// regexes are exported for userland consumption and lower level usage. A -// future breaking change could export the safer regex only with a note that -// all input should have extra whitespace removed. -const safeRegexReplacements = [ - ['\\s', 1], - ['\\d', MAX_LENGTH], - [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], -] - -const makeSafeRegex = (value) => { - for (const [token, max] of safeRegexReplacements) { - value = value - .split(`${token}*`).join(`${token}{0,${max}}`) - .split(`${token}+`).join(`${token}{1,${max}}`) - } - return value -} - -const createToken = (name, value, isGlobal) => { - const safe = makeSafeRegex(value) - const index = R++ - debug(name, index, value) - t[name] = index - src[index] = value - safeSrc[index] = safe - re[index] = new RegExp(value, isGlobal ? 'g' : undefined) - safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) -} - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') -createToken('NUMERICIDENTIFIERLOOSE', '\\d+') - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) - -// ## Main Version -// Three dot-separated numeric identifiers. - -createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`) - -createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`) - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. -// Non-numberic identifiers include numberic identifiers but can be longer. -// Therefore non-numberic identifiers must go first. - -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] -}|${src[t.NUMERICIDENTIFIER]})`) - -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] -}|${src[t.NUMERICIDENTIFIERLOOSE]})`) - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) - -createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`) - -createToken('FULL', `^${src[t.FULLPLAIN]}$`) - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`) - -createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) - -createToken('GTLT', '((?:<|>)?=?)') - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) -createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) - -createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`) - -createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`) - -createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) -createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -createToken('COERCEPLAIN', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) -createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) -createToken('COERCEFULL', src[t.COERCEPLAIN] + - `(?:${src[t.PRERELEASE]})?` + - `(?:${src[t.BUILD]})?` + - `(?:$|[^\\d])`) -createToken('COERCERTL', src[t.COERCE], true) -createToken('COERCERTLFULL', src[t.COERCEFULL], true) - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -createToken('LONETILDE', '(?:~>?)') - -createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) -exports.tildeTrimReplace = '$1~' - -createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) -createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -createToken('LONECARET', '(?:\\^)') - -createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) -exports.caretTrimReplace = '$1^' - -createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) -createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) -createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) -exports.comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`) - -createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`) - -// Star ranges basically just allow anything at all. -createToken('STAR', '(<|>)?=?\\s*\\*') -// >=0.0.0 is like a star -createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') -createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') - - -/***/ }), - -/***/ 2276: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// Determine if version is greater than all the versions possible in the range. -const outside = __nccwpck_require__(280) -const gtr = (version, range, options) => outside(version, range, '>', options) -module.exports = gtr - - -/***/ }), - -/***/ 3465: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(6782) -const intersects = (r1, r2, options) => { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2, options) -} -module.exports = intersects - - -/***/ }), - -/***/ 5213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const outside = __nccwpck_require__(280) -// Determine if version is less than all the versions possible in the range -const ltr = (version, range, options) => outside(version, range, '<', options) -module.exports = ltr - - -/***/ }), - -/***/ 5574: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) - -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} -module.exports = maxSatisfying - - -/***/ }), - -/***/ 8595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) -const minSatisfying = (versions, range, options) => { - let min = null - let minSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} -module.exports = minSatisfying - - -/***/ }), - -/***/ 1866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) -const gt = __nccwpck_require__(6599) - -const minVersion = (range, loose) => { - range = new Range(range, loose) - - let minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - let setMin = null - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt(compver, setMin)) { - setMin = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }) - if (setMin && (!minver || gt(minver, setMin))) { - minver = setMin - } - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} -module.exports = minVersion - - -/***/ }), - -/***/ 280: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(7163) -const Comparator = __nccwpck_require__(9379) -const { ANY } = Comparator -const Range = __nccwpck_require__(6782) -const satisfies = __nccwpck_require__(8011) -const gt = __nccwpck_require__(6599) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(6717) -const gte = __nccwpck_require__(1236) - -const outside = (version, range, hilo, options) => { - version = new SemVer(version, options) - range = new Range(range, options) - - let gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - let high = null - let low = null - - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -module.exports = outside - - -/***/ }), - -/***/ 2028: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// given a set of versions and a range, create a "simplified" range -// that includes the same versions that the original range does -// If the original range is shorter than the simplified one, return that. -const satisfies = __nccwpck_require__(8011) -const compare = __nccwpck_require__(8469) -module.exports = (versions, range, options) => { - const set = [] - let first = null - let prev = null - const v = versions.sort((a, b) => compare(a, b, options)) - for (const version of v) { - const included = satisfies(version, range, options) - if (included) { - prev = version - if (!first) { - first = version - } - } else { - if (prev) { - set.push([first, prev]) - } - prev = null - first = null - } - } - if (first) { - set.push([first, null]) - } - - const ranges = [] - for (const [min, max] of set) { - if (min === max) { - ranges.push(min) - } else if (!max && min === v[0]) { - ranges.push('*') - } else if (!max) { - ranges.push(`>=${min}`) - } else if (min === v[0]) { - ranges.push(`<=${max}`) - } else { - ranges.push(`${min} - ${max}`) - } - } - const simplified = ranges.join(' || ') - const original = typeof range.raw === 'string' ? range.raw : String(range) - return simplified.length < original.length ? simplified : range -} - - -/***/ }), - -/***/ 1489: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(6782) -const Comparator = __nccwpck_require__(9379) -const { ANY } = Comparator -const satisfies = __nccwpck_require__(8011) -const compare = __nccwpck_require__(8469) - -// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: -// - Every simple range `r1, r2, ...` is a null set, OR -// - Every simple range `r1, r2, ...` which is not a null set is a subset of -// some `R1, R2, ...` -// -// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: -// - If c is only the ANY comparator -// - If C is only the ANY comparator, return true -// - Else if in prerelease mode, return false -// - else replace c with `[>=0.0.0]` -// - If C is only the ANY comparator -// - if in prerelease mode, return true -// - else replace C with `[>=0.0.0]` -// - Let EQ be the set of = comparators in c -// - If EQ is more than one, return true (null set) -// - Let GT be the highest > or >= comparator in c -// - Let LT be the lowest < or <= comparator in c -// - If GT and LT, and GT.semver > LT.semver, return true (null set) -// - If any C is a = range, and GT or LT are set, return false -// - If EQ -// - If GT, and EQ does not satisfy GT, return true (null set) -// - If LT, and EQ does not satisfy LT, return true (null set) -// - If EQ satisfies every C, return true -// - Else return false -// - If GT -// - If GT.semver is lower than any > or >= comp in C, return false -// - If GT is >=, and GT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the GT.semver tuple, return false -// - If LT -// - If LT.semver is greater than any < or <= comp in C, return false -// - If LT is <=, and LT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the LT.semver tuple, return false -// - Else return true - -const subset = (sub, dom, options = {}) => { - if (sub === dom) { - return true - } - - sub = new Range(sub, options) - dom = new Range(dom, options) - let sawNonNull = false - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options) - sawNonNull = sawNonNull || isSub !== null - if (isSub) { - continue OUTER - } - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) { - return false - } - } - return true -} - -const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] -const minimumVersion = [new Comparator('>=0.0.0')] - -const simpleSubset = (sub, dom, options) => { - if (sub === dom) { - return true - } - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) { - return true - } else if (options.includePrerelease) { - sub = minimumVersionWithPreRelease - } else { - sub = minimumVersion - } - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) { - return true - } else { - dom = minimumVersion - } - } - - const eqSet = new Set() - let gt, lt - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') { - gt = higherGT(gt, c, options) - } else if (c.operator === '<' || c.operator === '<=') { - lt = lowerLT(lt, c, options) - } else { - eqSet.add(c.semver) - } - } - - if (eqSet.size > 1) { - return null - } - - let gtltComp - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options) - if (gtltComp > 0) { - return null - } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { - return null - } - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) { - return null - } - - if (lt && !satisfies(eq, String(lt), options)) { - return null - } - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) { - return false - } - } - - return true - } - - let higher, lower - let hasDomLT, hasDomGT - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options) - if (higher === c && higher !== gt) { - return false - } - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { - return false - } - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options) - if (lower === c && lower !== lt) { - return false - } - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { - return false - } - } - if (!c.operator && (lt || gt) && gtltComp !== 0) { - return false - } - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) { - return false - } - - if (lt && hasDomGT && !gt && gtltComp !== 0) { - return false - } - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) { - return false - } - - return true -} - -// >=1.2.3 is lower than >1.2.3 -const higherGT = (a, b, options) => { - if (!a) { - return b - } - const comp = compare(a.semver, b.semver, options) - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a -} - -// <=1.2.3 is higher than <1.2.3 -const lowerLT = (a, b, options) => { - if (!a) { - return b - } - const comp = compare(a.semver, b.semver, options) - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a -} - -module.exports = subset - - -/***/ }), - -/***/ 4750: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(6782) - -// Mostly just for testing and legacy API reasons -const toComparators = (range, options) => - new Range(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) - -module.exports = toComparators - - -/***/ }), - -/***/ 4737: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(6782) -const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -module.exports = validRange - - -/***/ }), - -/***/ 770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(218); - - -/***/ }), - -/***/ 218: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -var net = __nccwpck_require__(9278); -var tls = __nccwpck_require__(4756); -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var events = __nccwpck_require__(4434); -var assert = __nccwpck_require__(2613); -var util = __nccwpck_require__(9023); - - -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - - -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; - - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); - -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } - - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); - - function onFree() { - self.emit('free', socket, options); - } - - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); - } - }); -}; - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port - } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); - } - - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } - - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); - - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - - function onError(cause) { - connectReq.removeAllListeners(); - - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } -}; - -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); - - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; - -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); - - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} - - -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} - -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} - - -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); - } -} else { - debug = function() {}; -} -exports.debug = debug; // for test - - -/***/ }), - -/***/ 6752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Client = __nccwpck_require__(6197) -const Dispatcher = __nccwpck_require__(992) -const errors = __nccwpck_require__(8707) -const Pool = __nccwpck_require__(5076) -const BalancedPool = __nccwpck_require__(1093) -const Agent = __nccwpck_require__(9965) -const util = __nccwpck_require__(3440) -const { InvalidArgumentError } = errors -const api = __nccwpck_require__(6615) -const buildConnector = __nccwpck_require__(9136) -const MockClient = __nccwpck_require__(7365) -const MockAgent = __nccwpck_require__(7501) -const MockPool = __nccwpck_require__(4004) -const mockErrors = __nccwpck_require__(2429) -const ProxyAgent = __nccwpck_require__(2720) -const RetryHandler = __nccwpck_require__(3573) -const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) -const DecoratorHandler = __nccwpck_require__(8840) -const RedirectHandler = __nccwpck_require__(8299) -const createRedirectInterceptor = __nccwpck_require__(4415) - -let hasCrypto -try { - __nccwpck_require__(6982) - hasCrypto = true -} catch { - hasCrypto = false -} - -Object.assign(Dispatcher.prototype, api) - -module.exports.Dispatcher = Dispatcher -module.exports.Client = Client -module.exports.Pool = Pool -module.exports.BalancedPool = BalancedPool -module.exports.Agent = Agent -module.exports.ProxyAgent = ProxyAgent -module.exports.RetryHandler = RetryHandler - -module.exports.DecoratorHandler = DecoratorHandler -module.exports.RedirectHandler = RedirectHandler -module.exports.createRedirectInterceptor = createRedirectInterceptor - -module.exports.buildConnector = buildConnector -module.exports.errors = errors - -function makeDispatcher (fn) { - return (url, opts, handler) => { - if (typeof opts === 'function') { - handler = opts - opts = null - } - - if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { - throw new InvalidArgumentError('invalid url') - } - - if (opts != null && typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (opts && opts.path != null) { - if (typeof opts.path !== 'string') { - throw new InvalidArgumentError('invalid opts.path') - } - - let path = opts.path - if (!opts.path.startsWith('/')) { - path = `/${path}` - } - - url = new URL(util.parseOrigin(url).origin + path) - } else { - if (!opts) { - opts = typeof url === 'object' ? url : {} - } - - url = util.parseURL(url) - } - - const { agent, dispatcher = getGlobalDispatcher() } = opts - - if (agent) { - throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') - } - - return fn.call(dispatcher, { - ...opts, - origin: url.origin, - path: url.search ? `${url.pathname}${url.search}` : url.pathname, - method: opts.method || (opts.body ? 'PUT' : 'GET') - }, handler) - } -} - -module.exports.setGlobalDispatcher = setGlobalDispatcher -module.exports.getGlobalDispatcher = getGlobalDispatcher - -if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { - let fetchImpl = null - module.exports.fetch = async function fetch (resource) { - if (!fetchImpl) { - fetchImpl = (__nccwpck_require__(2315).fetch) - } - - try { - return await fetchImpl(...arguments) - } catch (err) { - if (typeof err === 'object') { - Error.captureStackTrace(err, this) - } - - throw err - } - } - module.exports.Headers = __nccwpck_require__(6349).Headers - module.exports.Response = __nccwpck_require__(8676).Response - module.exports.Request = __nccwpck_require__(5194).Request - module.exports.FormData = __nccwpck_require__(3073).FormData - module.exports.File = __nccwpck_require__(3041).File - module.exports.FileReader = __nccwpck_require__(2160).FileReader - - const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628) - - module.exports.setGlobalOrigin = setGlobalOrigin - module.exports.getGlobalOrigin = getGlobalOrigin - - const { CacheStorage } = __nccwpck_require__(4738) - const { kConstruct } = __nccwpck_require__(296) - - // Cache & CacheStorage are tightly coupled with fetch. Even if it may run - // in an older version of Node, it doesn't have any use without fetch. - module.exports.caches = new CacheStorage(kConstruct) -} - -if (util.nodeMajor >= 16) { - const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168) - - module.exports.deleteCookie = deleteCookie - module.exports.getCookies = getCookies - module.exports.getSetCookies = getSetCookies - module.exports.setCookie = setCookie - - const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) - - module.exports.parseMIMEType = parseMIMEType - module.exports.serializeAMimeType = serializeAMimeType -} - -if (util.nodeMajor >= 18 && hasCrypto) { - const { WebSocket } = __nccwpck_require__(5171) - - module.exports.WebSocket = WebSocket -} - -module.exports.request = makeDispatcher(api.request) -module.exports.stream = makeDispatcher(api.stream) -module.exports.pipeline = makeDispatcher(api.pipeline) -module.exports.connect = makeDispatcher(api.connect) -module.exports.upgrade = makeDispatcher(api.upgrade) - -module.exports.MockClient = MockClient -module.exports.MockPool = MockPool -module.exports.MockAgent = MockAgent -module.exports.mockErrors = mockErrors - - -/***/ }), - -/***/ 9965: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) -const DispatcherBase = __nccwpck_require__(1) -const Pool = __nccwpck_require__(5076) -const Client = __nccwpck_require__(6197) -const util = __nccwpck_require__(3440) -const createRedirectInterceptor = __nccwpck_require__(4415) -const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)() - -const kOnConnect = Symbol('onConnect') -const kOnDisconnect = Symbol('onDisconnect') -const kOnConnectionError = Symbol('onConnectionError') -const kMaxRedirections = Symbol('maxRedirections') -const kOnDrain = Symbol('onDrain') -const kFactory = Symbol('factory') -const kFinalizer = Symbol('finalizer') -const kOptions = Symbol('options') - -function defaultFactory (origin, opts) { - return opts && opts.connections === 1 - ? new Client(origin, opts) - : new Pool(origin, opts) -} - -class Agent extends DispatcherBase { - constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { - super() - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } - - if (connect && typeof connect !== 'function') { - connect = { ...connect } - } - - this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) - ? options.interceptors.Agent - : [createRedirectInterceptor({ maxRedirections })] - - this[kOptions] = { ...util.deepClone(options), connect } - this[kOptions].interceptors = options.interceptors - ? { ...options.interceptors } - : undefined - this[kMaxRedirections] = maxRedirections - this[kFactory] = factory - this[kClients] = new Map() - this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { - const ref = this[kClients].get(key) - if (ref !== undefined && ref.deref() === undefined) { - this[kClients].delete(key) - } - }) - - const agent = this - - this[kOnDrain] = (origin, targets) => { - agent.emit('drain', origin, [agent, ...targets]) - } - - this[kOnConnect] = (origin, targets) => { - agent.emit('connect', origin, [agent, ...targets]) - } - - this[kOnDisconnect] = (origin, targets, err) => { - agent.emit('disconnect', origin, [agent, ...targets], err) - } - - this[kOnConnectionError] = (origin, targets, err) => { - agent.emit('connectionError', origin, [agent, ...targets], err) - } - } - - get [kRunning] () { - let ret = 0 - for (const ref of this[kClients].values()) { - const client = ref.deref() - /* istanbul ignore next: gc is undeterministic */ - if (client) { - ret += client[kRunning] - } - } - return ret - } - - [kDispatch] (opts, handler) { - let key - if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { - key = String(opts.origin) - } else { - throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') - } - - const ref = this[kClients].get(key) - - let dispatcher = ref ? ref.deref() : null - if (!dispatcher) { - dispatcher = this[kFactory](opts.origin, this[kOptions]) - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) - - this[kClients].set(key, new WeakRef(dispatcher)) - this[kFinalizer].register(dispatcher, key) - } - - return dispatcher.dispatch(opts, handler) - } - - async [kClose] () { - const closePromises = [] - for (const ref of this[kClients].values()) { - const client = ref.deref() - /* istanbul ignore else: gc is undeterministic */ - if (client) { - closePromises.push(client.close()) - } - } - - await Promise.all(closePromises) - } - - async [kDestroy] (err) { - const destroyPromises = [] - for (const ref of this[kClients].values()) { - const client = ref.deref() - /* istanbul ignore else: gc is undeterministic */ - if (client) { - destroyPromises.push(client.destroy(err)) - } - } - - await Promise.all(destroyPromises) - } -} - -module.exports = Agent - - -/***/ }), - -/***/ 158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { addAbortListener } = __nccwpck_require__(3440) -const { RequestAbortedError } = __nccwpck_require__(8707) - -const kListener = Symbol('kListener') -const kSignal = Symbol('kSignal') - -function abort (self) { - if (self.abort) { - self.abort() - } else { - self.onError(new RequestAbortedError()) - } -} - -function addSignal (self, signal) { - self[kSignal] = null - self[kListener] = null - - if (!signal) { - return - } - - if (signal.aborted) { - abort(self) - return - } - - self[kSignal] = signal - self[kListener] = () => { - abort(self) - } - - addAbortListener(self[kSignal], self[kListener]) -} - -function removeSignal (self) { - if (!self[kSignal]) { - return - } - - if ('removeEventListener' in self[kSignal]) { - self[kSignal].removeEventListener('abort', self[kListener]) - } else { - self[kSignal].removeListener('abort', self[kListener]) - } - - self[kSignal] = null - self[kListener] = null -} - -module.exports = { - addSignal, - removeSignal -} - - -/***/ }), - -/***/ 4660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { AsyncResource } = __nccwpck_require__(290) -const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class ConnectHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - const { signal, opaque, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - super('UNDICI_CONNECT') - - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.callback = callback - this.abort = null - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders () { - throw new SocketError('bad connect', null) - } - - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this - - removeSignal(this) - - this.callback = null - - let headers = rawHeaders - // Indicates is an HTTP2Session - if (headers != null) { - headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - } - - this.runInAsyncScope(callback, null, null, { - statusCode, - headers, - socket, - opaque, - context - }) - } - - onError (err) { - const { callback, opaque } = this - - removeSignal(this) - - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - } -} - -function connect (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - connect.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - const connectHandler = new ConnectHandler(opts, callback) - this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = connect - - -/***/ }), - -/***/ 6862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - Readable, - Duplex, - PassThrough -} = __nccwpck_require__(2203) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) -const assert = __nccwpck_require__(2613) - -const kResume = Symbol('resume') - -class PipelineRequest extends Readable { - constructor () { - super({ autoDestroy: true }) - - this[kResume] = null - } - - _read () { - const { [kResume]: resume } = this - - if (resume) { - this[kResume] = null - resume() - } - } - - _destroy (err, callback) { - this._read() - - callback(err) - } -} - -class PipelineResponse extends Readable { - constructor (resume) { - super({ autoDestroy: true }) - this[kResume] = resume - } - - _read () { - this[kResume]() - } - - _destroy (err, callback) { - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } - - callback(err) - } -} - -class PipelineHandler extends AsyncResource { - constructor (opts, handler) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (typeof handler !== 'function') { - throw new InvalidArgumentError('invalid handler') - } - - const { signal, method, opaque, onInfo, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - - super('UNDICI_PIPELINE') - - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.handler = handler - this.abort = null - this.context = null - this.onInfo = onInfo || null - - this.req = new PipelineRequest().on('error', util.nop) - - this.ret = new Duplex({ - readableObjectMode: opts.objectMode, - autoDestroy: true, - read: () => { - const { body } = this - - if (body && body.resume) { - body.resume() - } - }, - write: (chunk, encoding, callback) => { - const { req } = this - - if (req.push(chunk, encoding) || req._readableState.destroyed) { - callback() - } else { - req[kResume] = callback - } - }, - destroy: (err, callback) => { - const { body, req, res, ret, abort } = this - - if (!err && !ret._readableState.endEmitted) { - err = new RequestAbortedError() - } - - if (abort && err) { - abort() - } - - util.destroy(body, err) - util.destroy(req, err) - util.destroy(res, err) - - removeSignal(this) - - callback(err) - } - }).on('prefinish', () => { - const { req } = this - - // Node < 15 does not call _final in same tick. - req.push(null) - }) - - this.res = null - - addSignal(this, signal) - } - - onConnect (abort, context) { - const { ret, res } = this - - assert(!res, 'pipeline cannot be retried') - - if (ret.destroyed) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders (statusCode, rawHeaders, resume) { - const { opaque, handler, context } = this - - if (statusCode < 200) { - if (this.onInfo) { - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.onInfo({ statusCode, headers }) - } - return - } - - this.res = new PipelineResponse(resume) - - let body - try { - this.handler = null - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - body = this.runInAsyncScope(handler, null, { - statusCode, - headers, - opaque, - body: this.res, - context - }) - } catch (err) { - this.res.on('error', util.nop) - throw err - } - - if (!body || typeof body.on !== 'function') { - throw new InvalidReturnValueError('expected Readable') - } - - body - .on('data', (chunk) => { - const { ret, body } = this - - if (!ret.push(chunk) && body.pause) { - body.pause() - } - }) - .on('error', (err) => { - const { ret } = this - - util.destroy(ret, err) - }) - .on('end', () => { - const { ret } = this - - ret.push(null) - }) - .on('close', () => { - const { ret } = this - - if (!ret._readableState.ended) { - util.destroy(ret, new RequestAbortedError()) - } - }) - - this.body = body - } - - onData (chunk) { - const { res } = this - return res.push(chunk) - } - - onComplete (trailers) { - const { res } = this - res.push(null) - } - - onError (err) { - const { ret } = this - this.handler = null - util.destroy(ret, err) - } -} - -function pipeline (opts, handler) { - try { - const pipelineHandler = new PipelineHandler(opts, handler) - this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) - return pipelineHandler.ret - } catch (err) { - return new PassThrough().destroy(err) - } -} - -module.exports = pipeline - - -/***/ }), - -/***/ 4043: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Readable = __nccwpck_require__(9927) -const { - InvalidArgumentError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class RequestHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { - throw new InvalidArgumentError('invalid highWaterMark') - } - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - - super('UNDICI_REQUEST') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.res = null - this.abort = null - this.body = body - this.trailers = {} - this.context = null - this.onInfo = onInfo || null - this.throwOnError = throwOnError - this.highWaterMark = highWaterMark - - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) - } - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return - } - - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - const body = new Readable({ resume, abort, contentType, highWaterMark }) - - this.callback = null - this.res = body - if (callback !== null) { - if (this.throwOnError && statusCode >= 400) { - this.runInAsyncScope(getResolveErrorBodyCallback, null, - { callback, body, contentType, statusCode, statusMessage, headers } - ) - } else { - this.runInAsyncScope(callback, null, null, { - statusCode, - headers, - trailers: this.trailers, - opaque, - body, - context - }) - } - } - } - - onData (chunk) { - const { res } = this - return res.push(chunk) - } - - onComplete (trailers) { - const { res } = this - - removeSignal(this) - - util.parseHeaders(trailers, this.trailers) - - res.push(null) - } - - onError (err) { - const { res, callback, body, opaque } = this - - removeSignal(this) - - if (callback) { - // TODO: Does this need queueMicrotask? - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - - if (res) { - this.res = null - // Ensure all queued handlers are invoked before destroying res. - queueMicrotask(() => { - util.destroy(res, err) - }) - } - - if (body) { - this.body = null - util.destroy(body, err) - } - } -} - -function request (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - request.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - this.dispatch(opts, new RequestHandler(opts, callback)) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = request -module.exports.RequestHandler = RequestHandler - - -/***/ }), - -/***/ 3560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { finished, PassThrough } = __nccwpck_require__(2203) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class StreamHandler extends AsyncResource { - constructor (opts, factory, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts - - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('invalid factory') - } - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - - super('UNDICI_STREAM') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.factory = factory - this.callback = callback - this.res = null - this.abort = null - this.context = null - this.trailers = null - this.body = body - this.onInfo = onInfo || null - this.throwOnError = throwOnError || false - - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) - } - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { factory, opaque, context, callback, responseHeaders } = this - - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return - } - - this.factory = null - - let res - - if (this.throwOnError && statusCode >= 400) { - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - res = new PassThrough() - - this.callback = null - this.runInAsyncScope(getResolveErrorBodyCallback, null, - { callback, body: res, contentType, statusCode, statusMessage, headers } - ) - } else { - if (factory === null) { - return - } - - res = this.runInAsyncScope(factory, null, { - statusCode, - headers, - opaque, - context - }) - - if ( - !res || - typeof res.write !== 'function' || - typeof res.end !== 'function' || - typeof res.on !== 'function' - ) { - throw new InvalidReturnValueError('expected Writable') - } - - // TODO: Avoid finished. It registers an unnecessary amount of listeners. - finished(res, { readable: false }, (err) => { - const { callback, res, opaque, trailers, abort } = this - - this.res = null - if (err || !res.readable) { - util.destroy(res, err) - } - - this.callback = null - this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) - - if (err) { - abort() - } - }) - } - - res.on('drain', resume) - - this.res = res - - const needDrain = res.writableNeedDrain !== undefined - ? res.writableNeedDrain - : res._writableState && res._writableState.needDrain - - return needDrain !== true - } - - onData (chunk) { - const { res } = this - - return res ? res.write(chunk) : true - } - - onComplete (trailers) { - const { res } = this - - removeSignal(this) - - if (!res) { - return - } - - this.trailers = util.parseHeaders(trailers) - - res.end() - } - - onError (err) { - const { res, callback, opaque, body } = this - - removeSignal(this) - - this.factory = null - - if (res) { - this.res = null - util.destroy(res, err) - } else if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - - if (body) { - this.body = null - util.destroy(body, err) - } - } -} - -function stream (opts, factory, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - stream.call(this, opts, factory, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - this.dispatch(opts, new StreamHandler(opts, factory, callback)) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = stream - - -/***/ }), - -/***/ 1882: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) -const { AsyncResource } = __nccwpck_require__(290) -const util = __nccwpck_require__(3440) -const { addSignal, removeSignal } = __nccwpck_require__(158) -const assert = __nccwpck_require__(2613) - -class UpgradeHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - const { signal, opaque, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - super('UNDICI_UPGRADE') - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.abort = null - this.context = null - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = null - } - - onHeaders () { - throw new SocketError('bad upgrade', null) - } - - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this - - assert.strictEqual(statusCode, 101) - - removeSignal(this) - - this.callback = null - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.runInAsyncScope(callback, null, null, { - headers, - socket, - opaque, - context - }) - } - - onError (err) { - const { callback, opaque } = this - - removeSignal(this) - - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - } -} - -function upgrade (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - upgrade.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - const upgradeHandler = new UpgradeHandler(opts, callback) - this.dispatch({ - ...opts, - method: opts.method || 'GET', - upgrade: opts.protocol || 'Websocket' - }, upgradeHandler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = upgrade - - -/***/ }), - -/***/ 6615: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -module.exports.request = __nccwpck_require__(4043) -module.exports.stream = __nccwpck_require__(3560) -module.exports.pipeline = __nccwpck_require__(6862) -module.exports.upgrade = __nccwpck_require__(1882) -module.exports.connect = __nccwpck_require__(4660) - - -/***/ }), - -/***/ 9927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Ported from https://github.com/nodejs/undici/pull/907 - - - -const assert = __nccwpck_require__(2613) -const { Readable } = __nccwpck_require__(2203) -const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440) - -let Blob - -const kConsume = Symbol('kConsume') -const kReading = Symbol('kReading') -const kBody = Symbol('kBody') -const kAbort = Symbol('abort') -const kContentType = Symbol('kContentType') - -const noop = () => {} - -module.exports = class BodyReadable extends Readable { - constructor ({ - resume, - abort, - contentType = '', - highWaterMark = 64 * 1024 // Same as nodejs fs streams. - }) { - super({ - autoDestroy: true, - read: resume, - highWaterMark - }) - - this._readableState.dataEmitted = false - - this[kAbort] = abort - this[kConsume] = null - this[kBody] = null - this[kContentType] = contentType - - // Is stream being consumed through Readable API? - // This is an optimization so that we avoid checking - // for 'data' and 'readable' listeners in the hot path - // inside push(). - this[kReading] = false - } - - destroy (err) { - if (this.destroyed) { - // Node < 16 - return this - } - - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } - - if (err) { - this[kAbort]() - } - - return super.destroy(err) - } - - emit (ev, ...args) { - if (ev === 'data') { - // Node < 16.7 - this._readableState.dataEmitted = true - } else if (ev === 'error') { - // Node < 16 - this._readableState.errorEmitted = true - } - return super.emit(ev, ...args) - } - - on (ev, ...args) { - if (ev === 'data' || ev === 'readable') { - this[kReading] = true - } - return super.on(ev, ...args) - } - - addListener (ev, ...args) { - return this.on(ev, ...args) - } - - off (ev, ...args) { - const ret = super.off(ev, ...args) - if (ev === 'data' || ev === 'readable') { - this[kReading] = ( - this.listenerCount('data') > 0 || - this.listenerCount('readable') > 0 - ) - } - return ret - } - - removeListener (ev, ...args) { - return this.off(ev, ...args) - } - - push (chunk) { - if (this[kConsume] && chunk !== null && this.readableLength === 0) { - consumePush(this[kConsume], chunk) - return this[kReading] ? super.push(chunk) : true - } - return super.push(chunk) - } - - // https://fetch.spec.whatwg.org/#dom-body-text - async text () { - return consume(this, 'text') - } - - // https://fetch.spec.whatwg.org/#dom-body-json - async json () { - return consume(this, 'json') - } - - // https://fetch.spec.whatwg.org/#dom-body-blob - async blob () { - return consume(this, 'blob') - } - - // https://fetch.spec.whatwg.org/#dom-body-arraybuffer - async arrayBuffer () { - return consume(this, 'arrayBuffer') - } - - // https://fetch.spec.whatwg.org/#dom-body-formdata - async formData () { - // TODO: Implement. - throw new NotSupportedError() - } - - // https://fetch.spec.whatwg.org/#dom-body-bodyused - get bodyUsed () { - return util.isDisturbed(this) - } - - // https://fetch.spec.whatwg.org/#dom-body-body - get body () { - if (!this[kBody]) { - this[kBody] = ReadableStreamFrom(this) - if (this[kConsume]) { - // TODO: Is this the best way to force a lock? - this[kBody].getReader() // Ensure stream is locked. - assert(this[kBody].locked) - } - } - return this[kBody] - } - - dump (opts) { - let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 - const signal = opts && opts.signal - - if (signal) { - try { - if (typeof signal !== 'object' || !('aborted' in signal)) { - throw new InvalidArgumentError('signal must be an AbortSignal') - } - util.throwIfAborted(signal) - } catch (err) { - return Promise.reject(err) - } - } - - if (this.closed) { - return Promise.resolve(null) - } - - return new Promise((resolve, reject) => { - const signalListenerCleanup = signal - ? util.addAbortListener(signal, () => { - this.destroy() - }) - : noop - - this - .on('close', function () { - signalListenerCleanup() - if (signal && signal.aborted) { - reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) - } else { - resolve(null) - } - }) - .on('error', noop) - .on('data', function (chunk) { - limit -= chunk.length - if (limit <= 0) { - this.destroy() - } - }) - .resume() - }) - } -} - -// https://streams.spec.whatwg.org/#readablestream-locked -function isLocked (self) { - // Consume is an implicit lock. - return (self[kBody] && self[kBody].locked === true) || self[kConsume] -} - -// https://fetch.spec.whatwg.org/#body-unusable -function isUnusable (self) { - return util.isDisturbed(self) || isLocked(self) -} - -async function consume (stream, type) { - if (isUnusable(stream)) { - throw new TypeError('unusable') - } - - assert(!stream[kConsume]) - - return new Promise((resolve, reject) => { - stream[kConsume] = { - type, - stream, - resolve, - reject, - length: 0, - body: [] - } - - stream - .on('error', function (err) { - consumeFinish(this[kConsume], err) - }) - .on('close', function () { - if (this[kConsume].body !== null) { - consumeFinish(this[kConsume], new RequestAbortedError()) - } - }) - - process.nextTick(consumeStart, stream[kConsume]) - }) -} - -function consumeStart (consume) { - if (consume.body === null) { - return - } - - const { _readableState: state } = consume.stream - - for (const chunk of state.buffer) { - consumePush(consume, chunk) - } - - if (state.endEmitted) { - consumeEnd(this[kConsume]) - } else { - consume.stream.on('end', function () { - consumeEnd(this[kConsume]) - }) - } - - consume.stream.resume() - - while (consume.stream.read() != null) { - // Loop - } -} - -function consumeEnd (consume) { - const { type, body, resolve, stream, length } = consume - - try { - if (type === 'text') { - resolve(toUSVString(Buffer.concat(body))) - } else if (type === 'json') { - resolve(JSON.parse(Buffer.concat(body))) - } else if (type === 'arrayBuffer') { - const dst = new Uint8Array(length) - - let pos = 0 - for (const buf of body) { - dst.set(buf, pos) - pos += buf.byteLength - } - - resolve(dst.buffer) - } else if (type === 'blob') { - if (!Blob) { - Blob = (__nccwpck_require__(181).Blob) - } - resolve(new Blob(body, { type: stream[kContentType] })) - } - - consumeFinish(consume) - } catch (err) { - stream.destroy(err) - } -} - -function consumePush (consume, chunk) { - consume.length += chunk.length - consume.body.push(chunk) -} - -function consumeFinish (consume, err) { - if (consume.body === null) { - return - } - - if (err) { - consume.reject(err) - } else { - consume.resolve() - } - - consume.type = null - consume.stream = null - consume.resolve = null - consume.reject = null - consume.length = 0 - consume.body = null -} - - -/***/ }), - -/***/ 7655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(2613) -const { - ResponseStatusCodeError -} = __nccwpck_require__(8707) -const { toUSVString } = __nccwpck_require__(3440) - -async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { - assert(body) - - let chunks = [] - let limit = 0 - - for await (const chunk of body) { - chunks.push(chunk) - limit += chunk.length - if (limit > 128 * 1024) { - chunks = null - break - } - } - - if (statusCode === 204 || !contentType || !chunks) { - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) - return - } - - try { - if (contentType.startsWith('application/json')) { - const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) - return - } - - if (contentType.startsWith('text/')) { - const payload = toUSVString(Buffer.concat(chunks)) - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) - return - } - } catch (err) { - // Process in a fallback if error - } - - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) -} - -module.exports = { getResolveErrorBodyCallback } - - -/***/ }), - -/***/ 1093: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - BalancedPoolMissingUpstreamError, - InvalidArgumentError -} = __nccwpck_require__(8707) -const { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} = __nccwpck_require__(8640) -const Pool = __nccwpck_require__(5076) -const { kUrl, kInterceptors } = __nccwpck_require__(6443) -const { parseOrigin } = __nccwpck_require__(3440) -const kFactory = Symbol('factory') - -const kOptions = Symbol('options') -const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') -const kCurrentWeight = Symbol('kCurrentWeight') -const kIndex = Symbol('kIndex') -const kWeight = Symbol('kWeight') -const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') -const kErrorPenalty = Symbol('kErrorPenalty') - -function getGreatestCommonDivisor (a, b) { - if (b === 0) return a - return getGreatestCommonDivisor(b, a % b) -} - -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} - -class BalancedPool extends PoolBase { - constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { - super() - - this[kOptions] = opts - this[kIndex] = -1 - this[kCurrentWeight] = 0 - - this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 - this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - - if (!Array.isArray(upstreams)) { - upstreams = [upstreams] - } - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) - ? opts.interceptors.BalancedPool - : [] - this[kFactory] = factory - - for (const upstream of upstreams) { - this.addUpstream(upstream) - } - this._updateBalancedPoolStats() - } - - addUpstream (upstream) { - const upstreamOrigin = parseOrigin(upstream).origin - - if (this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - ))) { - return this - } - const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) - - this[kAddClient](pool) - pool.on('connect', () => { - pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) - }) - - pool.on('connectionError', () => { - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - }) - - pool.on('disconnect', (...args) => { - const err = args[2] - if (err && err.code === 'UND_ERR_SOCKET') { - // decrease the weight of the pool. - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - } - }) - - for (const client of this[kClients]) { - client[kWeight] = this[kMaxWeightPerServer] - } - - this._updateBalancedPoolStats() - - return this - } - - _updateBalancedPoolStats () { - this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) - } - - removeUpstream (upstream) { - const upstreamOrigin = parseOrigin(upstream).origin - - const pool = this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - )) - - if (pool) { - this[kRemoveClient](pool) - } - - return this - } - - get upstreams () { - return this[kClients] - .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) - .map((p) => p[kUrl].origin) - } - - [kGetDispatcher] () { - // We validate that pools is greater than 0, - // otherwise we would have to wait until an upstream - // is added, which might never happen. - if (this[kClients].length === 0) { - throw new BalancedPoolMissingUpstreamError() - } - - const dispatcher = this[kClients].find(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - - if (!dispatcher) { - return - } - - const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - - if (allClientsBusy) { - return - } - - let counter = 0 - - let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - - while (counter++ < this[kClients].length) { - this[kIndex] = (this[kIndex] + 1) % this[kClients].length - const pool = this[kClients][this[kIndex]] - - // find pool index with the largest weight - if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { - maxWeightIndex = this[kIndex] - } - - // decrease the current weight every `this[kClients].length`. - if (this[kIndex] === 0) { - // Set the current weight to the next lower weight. - this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] - - if (this[kCurrentWeight] <= 0) { - this[kCurrentWeight] = this[kMaxWeightPerServer] - } - } - if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { - return pool - } - } - - this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] - this[kIndex] = maxWeightIndex - return this[kClients][maxWeightIndex] - } -} - -module.exports = BalancedPool - - -/***/ }), - -/***/ 479: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kConstruct } = __nccwpck_require__(296) -const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993) -const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) -const { kHeadersList } = __nccwpck_require__(6443) -const { webidl } = __nccwpck_require__(4222) -const { Response, cloneResponse } = __nccwpck_require__(8676) -const { Request } = __nccwpck_require__(5194) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const { fetching } = __nccwpck_require__(2315) -const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523) -const assert = __nccwpck_require__(2613) -const { getGlobalDispatcher } = __nccwpck_require__(2581) - -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation - * @typedef {Object} CacheBatchOperation - * @property {'delete' | 'put'} type - * @property {any} request - * @property {any} response - * @property {import('../../types/cache').CacheQueryOptions} options - */ - -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list - * @typedef {[any, any][]} requestResponseList - */ - -class Cache { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list - * @type {requestResponseList} - */ - #relevantRequestResponseList - - constructor () { - if (arguments[0] !== kConstruct) { - webidl.illegalConstructor() - } - - this.#relevantRequestResponseList = arguments[1] - } - - async match (request, options = {}) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) - - request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - const p = await this.matchAll(request, options) - - if (p.length === 0) { - return - } - - return p[0] - } - - async matchAll (request = undefined, options = {}) { - webidl.brandCheck(this, Cache) - - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - // 1. - let r = null - - // 2. - if (request !== undefined) { - if (request instanceof Request) { - // 2.1.1 - r = request[kState] - - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { - // 2.2.1 - r = new Request(request)[kState] - } - } - - // 5. - // 5.1 - const responses = [] - - // 5.2 - if (request === undefined) { - // 5.2.1 - for (const requestResponse of this.#relevantRequestResponseList) { - responses.push(requestResponse[1]) - } - } else { // 5.3 - // 5.3.1 - const requestResponses = this.#queryCache(r, options) - - // 5.3.2 - for (const requestResponse of requestResponses) { - responses.push(requestResponse[1]) - } - } - - // 5.4 - // We don't implement CORs so we don't need to loop over the responses, yay! - - // 5.5.1 - const responseList = [] - - // 5.5.2 - for (const response of responses) { - // 5.5.2.1 - const responseObject = new Response(response.body?.source ?? null) - const body = responseObject[kState].body - responseObject[kState] = response - responseObject[kState].body = body - responseObject[kHeaders][kHeadersList] = response.headersList - responseObject[kHeaders][kGuard] = 'immutable' - - responseList.push(responseObject) - } - - // 6. - return Object.freeze(responseList) - } - - async add (request) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) - - request = webidl.converters.RequestInfo(request) - - // 1. - const requests = [request] - - // 2. - const responseArrayPromise = this.addAll(requests) - - // 3. - return await responseArrayPromise - } - - async addAll (requests) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - - requests = webidl.converters['sequence'](requests) - - // 1. - const responsePromises = [] - - // 2. - const requestList = [] - - // 3. - for (const request of requests) { - if (typeof request === 'string') { - continue - } - - // 3.1 - const r = request[kState] - - // 3.2 - if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Expected http/s scheme when method is not GET.' - }) - } - } - - // 4. - /** @type {ReturnType[]} */ - const fetchControllers = [] - - // 5. - for (const request of requests) { - // 5.1 - const r = new Request(request)[kState] - - // 5.2 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Expected http/s scheme.' - }) - } - - // 5.4 - r.initiator = 'fetch' - r.destination = 'subresource' - - // 5.5 - requestList.push(r) - - // 5.6 - const responsePromise = createDeferredPromise() - - // 5.7 - fetchControllers.push(fetching({ - request: r, - dispatcher: getGlobalDispatcher(), - processResponse (response) { - // 1. - if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { - responsePromise.reject(webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Received an invalid status code or the request failed.' - })) - } else if (response.headersList.contains('vary')) { // 2. - // 2.1 - const fieldValues = getFieldValues(response.headersList.get('vary')) - - // 2.2 - for (const fieldValue of fieldValues) { - // 2.2.1 - if (fieldValue === '*') { - responsePromise.reject(webidl.errors.exception({ - header: 'Cache.addAll', - message: 'invalid vary field value' - })) - - for (const controller of fetchControllers) { - controller.abort() - } - - return - } - } - } - }, - processResponseEndOfBody (response) { - // 1. - if (response.aborted) { - responsePromise.reject(new DOMException('aborted', 'AbortError')) - return - } - - // 2. - responsePromise.resolve(response) - } - })) - - // 5.8 - responsePromises.push(responsePromise.promise) - } - - // 6. - const p = Promise.all(responsePromises) - - // 7. - const responses = await p - - // 7.1 - const operations = [] - - // 7.2 - let index = 0 - - // 7.3 - for (const response of responses) { - // 7.3.1 - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 7.3.2 - request: requestList[index], // 7.3.3 - response // 7.3.4 - } - - operations.push(operation) // 7.3.5 - - index++ // 7.3.6 - } - - // 7.5 - const cacheJobPromise = createDeferredPromise() - - // 7.6.1 - let errorData = null - - // 7.6.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } - - // 7.6.3 - queueMicrotask(() => { - // 7.6.3.1 - if (errorData === null) { - cacheJobPromise.resolve(undefined) - } else { - // 7.6.3.2 - cacheJobPromise.reject(errorData) - } - }) - - // 7.7 - return cacheJobPromise.promise - } - - async put (request, response) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) - - request = webidl.converters.RequestInfo(request) - response = webidl.converters.Response(response) - - // 1. - let innerRequest = null - - // 2. - if (request instanceof Request) { - innerRequest = request[kState] - } else { // 3. - innerRequest = new Request(request)[kState] - } - - // 4. - if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Expected an http/s scheme when method is not GET' - }) - } - - // 5. - const innerResponse = response[kState] - - // 6. - if (innerResponse.status === 206) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got 206 status' - }) - } - - // 7. - if (innerResponse.headersList.contains('vary')) { - // 7.1. - const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) - - // 7.2. - for (const fieldValue of fieldValues) { - // 7.2.1 - if (fieldValue === '*') { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got * vary field value' - }) - } - } - } - - // 8. - if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Response body is locked or disturbed' - }) - } - - // 9. - const clonedResponse = cloneResponse(innerResponse) - - // 10. - const bodyReadPromise = createDeferredPromise() - - // 11. - if (innerResponse.body != null) { - // 11.1 - const stream = innerResponse.body.stream - - // 11.2 - const reader = stream.getReader() - - // 11.3 - readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) - } else { - bodyReadPromise.resolve(undefined) - } - - // 12. - /** @type {CacheBatchOperation[]} */ - const operations = [] - - // 13. - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 14. - request: innerRequest, // 15. - response: clonedResponse // 16. - } - - // 17. - operations.push(operation) - - // 19. - const bytes = await bodyReadPromise.promise - - if (clonedResponse.body != null) { - clonedResponse.body.source = bytes - } - - // 19.1 - const cacheJobPromise = createDeferredPromise() - - // 19.2.1 - let errorData = null - - // 19.2.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } - - // 19.2.3 - queueMicrotask(() => { - // 19.2.3.1 - if (errorData === null) { - cacheJobPromise.resolve() - } else { // 19.2.3.2 - cacheJobPromise.reject(errorData) - } - }) - - return cacheJobPromise.promise - } - - async delete (request, options = {}) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - - request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - /** - * @type {Request} - */ - let r = null - - if (request instanceof Request) { - r = request[kState] - - if (r.method !== 'GET' && !options.ignoreMethod) { - return false - } - } else { - assert(typeof request === 'string') - - r = new Request(request)[kState] - } - - /** @type {CacheBatchOperation[]} */ - const operations = [] - - /** @type {CacheBatchOperation} */ - const operation = { - type: 'delete', - request: r, - options - } - - operations.push(operation) - - const cacheJobPromise = createDeferredPromise() - - let errorData = null - let requestResponses - - try { - requestResponses = this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } - - queueMicrotask(() => { - if (errorData === null) { - cacheJobPromise.resolve(!!requestResponses?.length) - } else { - cacheJobPromise.reject(errorData) - } - }) - - return cacheJobPromise.promise - } - - /** - * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys - * @param {any} request - * @param {import('../../types/cache').CacheQueryOptions} options - * @returns {readonly Request[]} - */ - async keys (request = undefined, options = {}) { - webidl.brandCheck(this, Cache) - - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - // 1. - let r = null - - // 2. - if (request !== undefined) { - // 2.1 - if (request instanceof Request) { - // 2.1.1 - r = request[kState] - - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { // 2.2 - r = new Request(request)[kState] - } - } - - // 4. - const promise = createDeferredPromise() - - // 5. - // 5.1 - const requests = [] - - // 5.2 - if (request === undefined) { - // 5.2.1 - for (const requestResponse of this.#relevantRequestResponseList) { - // 5.2.1.1 - requests.push(requestResponse[0]) - } - } else { // 5.3 - // 5.3.1 - const requestResponses = this.#queryCache(r, options) - - // 5.3.2 - for (const requestResponse of requestResponses) { - // 5.3.2.1 - requests.push(requestResponse[0]) - } - } - - // 5.4 - queueMicrotask(() => { - // 5.4.1 - const requestList = [] - - // 5.4.2 - for (const request of requests) { - const requestObject = new Request('https://a') - requestObject[kState] = request - requestObject[kHeaders][kHeadersList] = request.headersList - requestObject[kHeaders][kGuard] = 'immutable' - requestObject[kRealm] = request.client - - // 5.4.2.1 - requestList.push(requestObject) - } - - // 5.4.3 - promise.resolve(Object.freeze(requestList)) - }) - - return promise.promise - } - - /** - * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm - * @param {CacheBatchOperation[]} operations - * @returns {requestResponseList} - */ - #batchCacheOperations (operations) { - // 1. - const cache = this.#relevantRequestResponseList - - // 2. - const backupCache = [...cache] - - // 3. - const addedItems = [] - - // 4.1 - const resultList = [] - - try { - // 4.2 - for (const operation of operations) { - // 4.2.1 - if (operation.type !== 'delete' && operation.type !== 'put') { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'operation type does not match "delete" or "put"' - }) - } - - // 4.2.2 - if (operation.type === 'delete' && operation.response != null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'delete operation should not have an associated response' - }) - } - - // 4.2.3 - if (this.#queryCache(operation.request, operation.options, addedItems).length) { - throw new DOMException('???', 'InvalidStateError') - } - - // 4.2.4 - let requestResponses - - // 4.2.5 - if (operation.type === 'delete') { - // 4.2.5.1 - requestResponses = this.#queryCache(operation.request, operation.options) - - // TODO: the spec is wrong, this is needed to pass WPTs - if (requestResponses.length === 0) { - return [] - } - - // 4.2.5.2 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) - - // 4.2.5.2.1 - cache.splice(idx, 1) - } - } else if (operation.type === 'put') { // 4.2.6 - // 4.2.6.1 - if (operation.response == null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'put operation should have an associated response' - }) - } - - // 4.2.6.2 - const r = operation.request - - // 4.2.6.3 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'expected http or https scheme' - }) - } - - // 4.2.6.4 - if (r.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'not get method' - }) - } - - // 4.2.6.5 - if (operation.options != null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'options must not be defined' - }) - } - - // 4.2.6.6 - requestResponses = this.#queryCache(operation.request) - - // 4.2.6.7 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) - - // 4.2.6.7.1 - cache.splice(idx, 1) - } - - // 4.2.6.8 - cache.push([operation.request, operation.response]) - - // 4.2.6.10 - addedItems.push([operation.request, operation.response]) - } - - // 4.2.7 - resultList.push([operation.request, operation.response]) - } - - // 4.3 - return resultList - } catch (e) { // 5. - // 5.1 - this.#relevantRequestResponseList.length = 0 - - // 5.2 - this.#relevantRequestResponseList = backupCache - - // 5.3 - throw e - } - } - - /** - * @see https://w3c.github.io/ServiceWorker/#query-cache - * @param {any} requestQuery - * @param {import('../../types/cache').CacheQueryOptions} options - * @param {requestResponseList} targetStorage - * @returns {requestResponseList} - */ - #queryCache (requestQuery, options, targetStorage) { - /** @type {requestResponseList} */ - const resultList = [] - - const storage = targetStorage ?? this.#relevantRequestResponseList - - for (const requestResponse of storage) { - const [cachedRequest, cachedResponse] = requestResponse - if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { - resultList.push(requestResponse) - } - } - - return resultList - } - - /** - * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm - * @param {any} requestQuery - * @param {any} request - * @param {any | null} response - * @param {import('../../types/cache').CacheQueryOptions | undefined} options - * @returns {boolean} - */ - #requestMatchesCachedItem (requestQuery, request, response = null, options) { - // if (options?.ignoreMethod === false && request.method === 'GET') { - // return false - // } - - const queryURL = new URL(requestQuery.url) - - const cachedURL = new URL(request.url) - - if (options?.ignoreSearch) { - cachedURL.search = '' - - queryURL.search = '' - } - - if (!urlEquals(queryURL, cachedURL, true)) { - return false - } - - if ( - response == null || - options?.ignoreVary || - !response.headersList.contains('vary') - ) { - return true - } - - const fieldValues = getFieldValues(response.headersList.get('vary')) - - for (const fieldValue of fieldValues) { - if (fieldValue === '*') { - return false - } - - const requestValue = request.headersList.get(fieldValue) - const queryValue = requestQuery.headersList.get(fieldValue) - - // If one has the header and the other doesn't, or one has - // a different value than the other, return false - if (requestValue !== queryValue) { - return false - } - } - - return true - } -} - -Object.defineProperties(Cache.prototype, { - [Symbol.toStringTag]: { - value: 'Cache', - configurable: true - }, - match: kEnumerableProperty, - matchAll: kEnumerableProperty, - add: kEnumerableProperty, - addAll: kEnumerableProperty, - put: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty -}) - -const cacheQueryOptionConverters = [ - { - key: 'ignoreSearch', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'ignoreMethod', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'ignoreVary', - converter: webidl.converters.boolean, - defaultValue: false - } -] - -webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) - -webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ - ...cacheQueryOptionConverters, - { - key: 'cacheName', - converter: webidl.converters.DOMString - } -]) - -webidl.converters.Response = webidl.interfaceConverter(Response) - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.RequestInfo -) - -module.exports = { - Cache -} - - -/***/ }), - -/***/ 4738: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kConstruct } = __nccwpck_require__(296) -const { Cache } = __nccwpck_require__(479) -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) - -class CacheStorage { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map - * @type {Map} - */ - async has (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) - - cacheName = webidl.converters.DOMString(cacheName) - - // 2.1.1 - // 2.2 - return this.#caches.has(cacheName) - } - - /** - * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open - * @param {string} cacheName - * @returns {Promise} - */ - async open (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) - - cacheName = webidl.converters.DOMString(cacheName) - - // 2.1 - if (this.#caches.has(cacheName)) { - // await caches.open('v1') !== await caches.open('v1') - - // 2.1.1 - const cache = this.#caches.get(cacheName) - - // 2.1.1.1 - return new Cache(kConstruct, cache) - } - - // 2.2 - const cache = [] - - // 2.3 - this.#caches.set(cacheName, cache) - - // 2.4 - return new Cache(kConstruct, cache) - } - - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete - * @param {string} cacheName - * @returns {Promise} - */ - async delete (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) - - cacheName = webidl.converters.DOMString(cacheName) - - return this.#caches.delete(cacheName) - } - - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys - * @returns {string[]} - */ - async keys () { - webidl.brandCheck(this, CacheStorage) - - // 2.1 - const keys = this.#caches.keys() - - // 2.2 - return [...keys] - } -} - -Object.defineProperties(CacheStorage.prototype, { - [Symbol.toStringTag]: { - value: 'CacheStorage', - configurable: true - }, - match: kEnumerableProperty, - has: kEnumerableProperty, - open: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty -}) - -module.exports = { - CacheStorage -} - - -/***/ }), - -/***/ 296: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -module.exports = { - kConstruct: (__nccwpck_require__(6443).kConstruct) -} - - -/***/ }), - -/***/ 3993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const assert = __nccwpck_require__(2613) -const { URLSerializer } = __nccwpck_require__(4322) -const { isValidHeaderName } = __nccwpck_require__(5523) - -/** - * @see https://url.spec.whatwg.org/#concept-url-equals - * @param {URL} A - * @param {URL} B - * @param {boolean | undefined} excludeFragment - * @returns {boolean} - */ -function urlEquals (A, B, excludeFragment = false) { - const serializedA = URLSerializer(A, excludeFragment) - - const serializedB = URLSerializer(B, excludeFragment) - - return serializedA === serializedB -} - -/** - * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 - * @param {string} header - */ -function fieldValues (header) { - assert(header !== null) - - const values = [] - - for (let value of header.split(',')) { - value = value.trim() - - if (!value.length) { - continue - } else if (!isValidHeaderName(value)) { - continue - } - - values.push(value) - } - - return values -} - -module.exports = { - urlEquals, - fieldValues -} - - -/***/ }), - -/***/ 6197: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// @ts-check - - - -/* global WebAssembly */ - -const assert = __nccwpck_require__(2613) -const net = __nccwpck_require__(9278) -const http = __nccwpck_require__(8611) -const { pipeline } = __nccwpck_require__(2203) -const util = __nccwpck_require__(3440) -const timers = __nccwpck_require__(8804) -const Request = __nccwpck_require__(4655) -const DispatcherBase = __nccwpck_require__(1) -const { - RequestContentLengthMismatchError, - ResponseContentLengthMismatchError, - InvalidArgumentError, - RequestAbortedError, - HeadersTimeoutError, - HeadersOverflowError, - SocketError, - InformationalError, - BodyTimeoutError, - HTTPParserError, - ResponseExceededMaxSizeError, - ClientDestroyedError -} = __nccwpck_require__(8707) -const buildConnector = __nccwpck_require__(9136) -const { - kUrl, - kReset, - kServerName, - kClient, - kBusy, - kParser, - kConnect, - kBlocking, - kResuming, - kRunning, - kPending, - kSize, - kWriting, - kQueue, - kConnected, - kConnecting, - kNeedDrain, - kNoRef, - kKeepAliveDefaultTimeout, - kHostHeader, - kPendingIdx, - kRunningIdx, - kError, - kPipelining, - kSocket, - kKeepAliveTimeoutValue, - kMaxHeadersSize, - kKeepAliveMaxTimeout, - kKeepAliveTimeoutThreshold, - kHeadersTimeout, - kBodyTimeout, - kStrictContentLength, - kConnector, - kMaxRedirections, - kMaxRequests, - kCounter, - kClose, - kDestroy, - kDispatch, - kInterceptors, - kLocalAddress, - kMaxResponseSize, - kHTTPConnVersion, - // HTTP2 - kHost, - kHTTP2Session, - kHTTP2SessionState, - kHTTP2BuildRequest, - kHTTP2CopyHeaders, - kHTTP1BuildRequest -} = __nccwpck_require__(6443) - -/** @type {import('http2')} */ -let http2 -try { - http2 = __nccwpck_require__(5675) -} catch { - // @ts-ignore - http2 = { constants: {} } -} - -const { - constants: { - HTTP2_HEADER_AUTHORITY, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_SCHEME, - HTTP2_HEADER_CONTENT_LENGTH, - HTTP2_HEADER_EXPECT, - HTTP2_HEADER_STATUS - } -} = http2 - -// Experimental -let h2ExperimentalWarned = false - -const FastBuffer = Buffer[Symbol.species] - -const kClosedResolve = Symbol('kClosedResolve') - -const channels = {} - -try { - const diagnosticsChannel = __nccwpck_require__(1637) - channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') - channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') - channels.connectError = diagnosticsChannel.channel('undici:client:connectError') - channels.connected = diagnosticsChannel.channel('undici:client:connected') -} catch { - channels.sendHeaders = { hasSubscribers: false } - channels.beforeConnect = { hasSubscribers: false } - channels.connectError = { hasSubscribers: false } - channels.connected = { hasSubscribers: false } -} - -/** - * @type {import('../types/client').default} - */ -class Client extends DispatcherBase { - /** - * - * @param {string|URL} url - * @param {import('../types/client').Client.Options} options - */ - constructor (url, { - interceptors, - maxHeaderSize, - headersTimeout, - socketTimeout, - requestTimeout, - connectTimeout, - bodyTimeout, - idleTimeout, - keepAlive, - keepAliveTimeout, - maxKeepAliveTimeout, - keepAliveMaxTimeout, - keepAliveTimeoutThreshold, - socketPath, - pipelining, - tls, - strictContentLength, - maxCachedSessions, - maxRedirections, - connect, - maxRequestsPerClient, - localAddress, - maxResponseSize, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - // h2 - allowH2, - maxConcurrentStreams - } = {}) { - super() - - if (keepAlive !== undefined) { - throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') - } - - if (socketTimeout !== undefined) { - throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') - } - - if (requestTimeout !== undefined) { - throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') - } - - if (idleTimeout !== undefined) { - throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') - } - - if (maxKeepAliveTimeout !== undefined) { - throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') - } - - if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { - throw new InvalidArgumentError('invalid maxHeaderSize') - } - - if (socketPath != null && typeof socketPath !== 'string') { - throw new InvalidArgumentError('invalid socketPath') - } - - if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { - throw new InvalidArgumentError('invalid connectTimeout') - } - - if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveTimeout') - } - - if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveMaxTimeout') - } - - if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { - throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') - } - - if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') - } - - if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } - - if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { - throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') - } - - if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { - throw new InvalidArgumentError('localAddress must be valid string IP address') - } - - if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { - throw new InvalidArgumentError('maxResponseSize must be a positive number') - } - - if ( - autoSelectFamilyAttemptTimeout != null && - (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) - ) { - throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') - } - - // h2 - if (allowH2 != null && typeof allowH2 !== 'boolean') { - throw new InvalidArgumentError('allowH2 must be a valid boolean value') - } - - if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { - throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') - } - - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } - - this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) - ? interceptors.Client - : [createRedirectInterceptor({ maxRedirections })] - this[kUrl] = util.parseOrigin(url) - this[kConnector] = connect - this[kSocket] = null - this[kPipelining] = pipelining != null ? pipelining : 1 - this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize - this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout - this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout - this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold - this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] - this[kServerName] = null - this[kLocalAddress] = localAddress != null ? localAddress : null - this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming - this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming - this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` - this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 - this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 - this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength - this[kMaxRedirections] = maxRedirections - this[kMaxRequests] = maxRequestsPerClient - this[kClosedResolve] = null - this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 - this[kHTTPConnVersion] = 'h1' - - // HTTP/2 - this[kHTTP2Session] = null - this[kHTTP2SessionState] = !allowH2 - ? null - : { - // streams: null, // Fixed queue of streams - For future support of `push` - openStreams: 0, // Keep track of them to decide wether or not unref the session - maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server - } - this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` - - // kQueue is built up of 3 sections separated by - // the kRunningIdx and kPendingIdx indices. - // | complete | running | pending | - // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length - // kRunningIdx points to the first running element. - // kPendingIdx points to the first pending element. - // This implements a fast queue with an amortized - // time of O(1). - - this[kQueue] = [] - this[kRunningIdx] = 0 - this[kPendingIdx] = 0 - } - - get pipelining () { - return this[kPipelining] - } - - set pipelining (value) { - this[kPipelining] = value - resume(this, true) - } - - get [kPending] () { - return this[kQueue].length - this[kPendingIdx] - } - - get [kRunning] () { - return this[kPendingIdx] - this[kRunningIdx] - } - - get [kSize] () { - return this[kQueue].length - this[kRunningIdx] - } - - get [kConnected] () { - return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed - } - - get [kBusy] () { - const socket = this[kSocket] - return ( - (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || - (this[kSize] >= (this[kPipelining] || 1)) || - this[kPending] > 0 - ) - } - - /* istanbul ignore: only used for test */ - [kConnect] (cb) { - connect(this) - this.once('connect', cb) - } - - [kDispatch] (opts, handler) { - const origin = opts.origin || this[kUrl].origin - - const request = this[kHTTPConnVersion] === 'h2' - ? Request[kHTTP2BuildRequest](origin, opts, handler) - : Request[kHTTP1BuildRequest](origin, opts, handler) - - this[kQueue].push(request) - if (this[kResuming]) { - // Do nothing. - } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { - // Wait a tick in case stream/iterator is ended in the same tick. - this[kResuming] = 1 - process.nextTick(resume, this) - } else { - resume(this, true) - } - - if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { - this[kNeedDrain] = 2 - } - - return this[kNeedDrain] < 2 - } - - async [kClose] () { - // TODO: for H2 we need to gracefully flush the remaining enqueued - // request and close each stream. - return new Promise((resolve) => { - if (!this[kSize]) { - resolve(null) - } else { - this[kClosedResolve] = resolve - } - }) - } - - async [kDestroy] (err) { - return new Promise((resolve) => { - const requests = this[kQueue].splice(this[kPendingIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(this, request, err) - } - - const callback = () => { - if (this[kClosedResolve]) { - // TODO (fix): Should we error here with ClientDestroyedError? - this[kClosedResolve]() - this[kClosedResolve] = null - } - resolve() - } - - if (this[kHTTP2Session] != null) { - util.destroy(this[kHTTP2Session], err) - this[kHTTP2Session] = null - this[kHTTP2SessionState] = null - } - - if (!this[kSocket]) { - queueMicrotask(callback) - } else { - util.destroy(this[kSocket].on('close', callback), err) - } - - resume(this) - }) - } -} - -function onHttp2SessionError (err) { - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - - this[kSocket][kError] = err - - onError(this[kClient], err) -} - -function onHttp2FrameError (type, code, id) { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - - if (id === 0) { - this[kSocket][kError] = err - onError(this[kClient], err) - } -} - -function onHttp2SessionEnd () { - util.destroy(this, new SocketError('other side closed')) - util.destroy(this[kSocket], new SocketError('other side closed')) -} - -function onHTTP2GoAway (code) { - const client = this[kClient] - const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) - client[kSocket] = null - client[kHTTP2Session] = null - - if (client.destroyed) { - assert(this[kPending] === 0) - - // Fail entire queue. - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(this, request, err) - } - } else if (client[kRunning] > 0) { - // Fail head of pipeline. - const request = client[kQueue][client[kRunningIdx]] - client[kQueue][client[kRunningIdx]++] = null - - errorRequest(client, request, err) - } - - client[kPendingIdx] = client[kRunningIdx] - - assert(client[kRunning] === 0) - - client.emit('disconnect', - client[kUrl], - [client], - err - ) - - resume(client) -} - -const constants = __nccwpck_require__(2824) -const createRedirectInterceptor = __nccwpck_require__(4415) -const EMPTY_BUF = Buffer.alloc(0) - -async function lazyllhttp () { - const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined - - let mod - try { - mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64')) - } catch (e) { - /* istanbul ignore next */ - - // We could check if the error was caused by the simd option not - // being enabled, but the occurring of this other error - // * https://github.com/emscripten-core/emscripten/issues/11495 - // got me to remove that check to avoid breaking Node 12. - mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64')) - } - - return await WebAssembly.instantiate(mod, { - env: { - /* eslint-disable camelcase */ - - wasm_on_url: (p, at, len) => { - /* istanbul ignore next */ - return 0 - }, - wasm_on_status: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_message_begin: (p) => { - assert.strictEqual(currentParser.ptr, p) - return currentParser.onMessageBegin() || 0 - }, - wasm_on_header_field: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_header_value: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { - assert.strictEqual(currentParser.ptr, p) - return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 - }, - wasm_on_body: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_message_complete: (p) => { - assert.strictEqual(currentParser.ptr, p) - return currentParser.onMessageComplete() || 0 - } - - /* eslint-enable camelcase */ - } - }) -} - -let llhttpInstance = null -let llhttpPromise = lazyllhttp() -llhttpPromise.catch() - -let currentParser = null -let currentBufferRef = null -let currentBufferSize = 0 -let currentBufferPtr = null - -const TIMEOUT_HEADERS = 1 -const TIMEOUT_BODY = 2 -const TIMEOUT_IDLE = 3 - -class Parser { - constructor (client, socket, { exports }) { - assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) - - this.llhttp = exports - this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) - this.client = client - this.socket = socket - this.timeout = null - this.timeoutValue = null - this.timeoutType = null - this.statusCode = null - this.statusText = '' - this.upgrade = false - this.headers = [] - this.headersSize = 0 - this.headersMaxSize = client[kMaxHeadersSize] - this.shouldKeepAlive = false - this.paused = false - this.resume = this.resume.bind(this) - - this.bytesRead = 0 - - this.keepAlive = '' - this.contentLength = '' - this.connection = '' - this.maxResponseSize = client[kMaxResponseSize] - } - - setTimeout (value, type) { - this.timeoutType = type - if (value !== this.timeoutValue) { - timers.clearTimeout(this.timeout) - if (value) { - this.timeout = timers.setTimeout(onParserTimeout, value, this) - // istanbul ignore else: only for jest - if (this.timeout.unref) { - this.timeout.unref() - } - } else { - this.timeout = null - } - this.timeoutValue = value - } else if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - } - - resume () { - if (this.socket.destroyed || !this.paused) { - return - } - - assert(this.ptr != null) - assert(currentParser == null) - - this.llhttp.llhttp_resume(this.ptr) - - assert(this.timeoutType === TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - - this.paused = false - this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. - this.readMore() - } - - readMore () { - while (!this.paused && this.ptr) { - const chunk = this.socket.read() - if (chunk === null) { - break - } - this.execute(chunk) - } - } - - execute (data) { - assert(this.ptr != null) - assert(currentParser == null) - assert(!this.paused) - - const { socket, llhttp } = this - - if (data.length > currentBufferSize) { - if (currentBufferPtr) { - llhttp.free(currentBufferPtr) - } - currentBufferSize = Math.ceil(data.length / 4096) * 4096 - currentBufferPtr = llhttp.malloc(currentBufferSize) - } - - new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - - // Call `execute` on the wasm parser. - // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, - // and finally the length of bytes to parse. - // The return value is an error code or `constants.ERROR.OK`. - try { - let ret - - try { - currentBufferRef = data - currentParser = this - ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) - /* eslint-disable-next-line no-useless-catch */ - } catch (err) { - /* istanbul ignore next: difficult to make a test case for */ - throw err - } finally { - currentParser = null - currentBufferRef = null - } - - const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr - - if (ret === constants.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(data.slice(offset)) - } else if (ret === constants.ERROR.PAUSED) { - this.paused = true - socket.unshift(data.slice(offset)) - } else if (ret !== constants.ERROR.OK) { - const ptr = llhttp.llhttp_get_error_reason(this.ptr) - let message = '' - /* istanbul ignore else: difficult to make a test case for */ - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) - message = - 'Response does not match the HTTP/1.1 protocol (' + - Buffer.from(llhttp.memory.buffer, ptr, len).toString() + - ')' - } - throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) - } - } catch (err) { - util.destroy(socket, err) - } - } - - destroy () { - assert(this.ptr != null) - assert(currentParser == null) - - this.llhttp.llhttp_free(this.ptr) - this.ptr = null - - timers.clearTimeout(this.timeout) - this.timeout = null - this.timeoutValue = null - this.timeoutType = null - - this.paused = false - } - - onStatus (buf) { - this.statusText = buf.toString() - } - - onMessageBegin () { - const { socket, client } = this - - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } - - const request = client[kQueue][client[kRunningIdx]] - if (!request) { - return -1 - } - } - - onHeaderField (buf) { - const len = this.headers.length - - if ((len & 1) === 0) { - this.headers.push(buf) - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } - - this.trackHeader(buf.length) - } - - onHeaderValue (buf) { - let len = this.headers.length - - if ((len & 1) === 1) { - this.headers.push(buf) - len += 1 - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } - - const key = this.headers[len - 2] - if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { - this.keepAlive += buf.toString() - } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { - this.connection += buf.toString() - } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { - this.contentLength += buf.toString() - } - - this.trackHeader(buf.length) - } - - trackHeader (len) { - this.headersSize += len - if (this.headersSize >= this.headersMaxSize) { - util.destroy(this.socket, new HeadersOverflowError()) - } - } - - onUpgrade (head) { - const { upgrade, client, socket, headers, statusCode } = this - - assert(upgrade) - - const request = client[kQueue][client[kRunningIdx]] - assert(request) - - assert(!socket.destroyed) - assert(socket === client[kSocket]) - assert(!this.paused) - assert(request.upgrade || request.method === 'CONNECT') - - this.statusCode = null - this.statusText = '' - this.shouldKeepAlive = null - - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 - - socket.unshift(head) - - socket[kParser].destroy() - socket[kParser] = null - - socket[kClient] = null - socket[kError] = null - socket - .removeListener('error', onSocketError) - .removeListener('readable', onSocketReadable) - .removeListener('end', onSocketEnd) - .removeListener('close', onSocketClose) - - client[kSocket] = null - client[kQueue][client[kRunningIdx]++] = null - client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) - - try { - request.onUpgrade(statusCode, headers, socket) - } catch (err) { - util.destroy(socket, err) - } - - resume(client) - } - - onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { - const { client, socket, headers, statusText } = this - - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } - - const request = client[kQueue][client[kRunningIdx]] - - /* istanbul ignore next: difficult to make a test case for */ - if (!request) { - return -1 - } - - assert(!this.upgrade) - assert(this.statusCode < 200) - - if (statusCode === 100) { - util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) - return -1 - } - - /* this can only happen if server is misbehaving */ - if (upgrade && !request.upgrade) { - util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) - return -1 - } - - assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) - - this.statusCode = statusCode - this.shouldKeepAlive = ( - shouldKeepAlive || - // Override llhttp value which does not allow keepAlive for HEAD. - (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') - ) - - if (this.statusCode >= 200) { - const bodyTimeout = request.bodyTimeout != null - ? request.bodyTimeout - : client[kBodyTimeout] - this.setTimeout(bodyTimeout, TIMEOUT_BODY) - } else if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - - if (request.method === 'CONNECT') { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } - - if (upgrade) { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } - - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 - - if (this.shouldKeepAlive && client[kPipelining]) { - const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null - - if (keepAliveTimeout != null) { - const timeout = Math.min( - keepAliveTimeout - client[kKeepAliveTimeoutThreshold], - client[kKeepAliveMaxTimeout] - ) - if (timeout <= 0) { - socket[kReset] = true - } else { - client[kKeepAliveTimeoutValue] = timeout - } - } else { - client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] - } - } else { - // Stop more requests from being dispatched. - socket[kReset] = true - } - - const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - - if (request.aborted) { - return -1 - } - - if (request.method === 'HEAD') { - return 1 - } - - if (statusCode < 200) { - return 1 - } - - if (socket[kBlocking]) { - socket[kBlocking] = false - resume(client) - } - - return pause ? constants.ERROR.PAUSED : 0 - } - - onBody (buf) { - const { client, socket, statusCode, maxResponseSize } = this - - if (socket.destroyed) { - return -1 - } - - const request = client[kQueue][client[kRunningIdx]] - assert(request) - - assert.strictEqual(this.timeoutType, TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - - assert(statusCode >= 200) - - if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { - util.destroy(socket, new ResponseExceededMaxSizeError()) - return -1 - } - - this.bytesRead += buf.length - - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED - } - } - - onMessageComplete () { - const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this - - if (socket.destroyed && (!statusCode || shouldKeepAlive)) { - return -1 - } - - if (upgrade) { - return - } - - const request = client[kQueue][client[kRunningIdx]] - assert(request) - - assert(statusCode >= 100) - - this.statusCode = null - this.statusText = '' - this.bytesRead = 0 - this.contentLength = '' - this.keepAlive = '' - this.connection = '' - - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 - - if (statusCode < 200) { - return - } - - /* istanbul ignore next: should be handled by llhttp? */ - if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { - util.destroy(socket, new ResponseContentLengthMismatchError()) - return -1 - } - - request.onComplete(headers) - - client[kQueue][client[kRunningIdx]++] = null - - if (socket[kWriting]) { - assert.strictEqual(client[kRunning], 0) - // Response completed before request. - util.destroy(socket, new InformationalError('reset')) - return constants.ERROR.PAUSED - } else if (!shouldKeepAlive) { - util.destroy(socket, new InformationalError('reset')) - return constants.ERROR.PAUSED - } else if (socket[kReset] && client[kRunning] === 0) { - // Destroy socket once all requests have completed. - // The request at the tail of the pipeline is the one - // that requested reset and no further requests should - // have been queued since then. - util.destroy(socket, new InformationalError('reset')) - return constants.ERROR.PAUSED - } else if (client[kPipelining] === 1) { - // We must wait a full event loop cycle to reuse this socket to make sure - // that non-spec compliant servers are not closing the connection even if they - // said they won't. - setImmediate(resume, client) - } else { - resume(client) - } - } -} - -function onParserTimeout (parser) { - const { socket, timeoutType, client } = parser - - /* istanbul ignore else */ - if (timeoutType === TIMEOUT_HEADERS) { - if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { - assert(!parser.paused, 'cannot be paused while waiting for headers') - util.destroy(socket, new HeadersTimeoutError()) - } - } else if (timeoutType === TIMEOUT_BODY) { - if (!parser.paused) { - util.destroy(socket, new BodyTimeoutError()) - } - } else if (timeoutType === TIMEOUT_IDLE) { - assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) - util.destroy(socket, new InformationalError('socket idle timeout')) - } -} - -function onSocketReadable () { - const { [kParser]: parser } = this - if (parser) { - parser.readMore() - } -} - -function onSocketError (err) { - const { [kClient]: client, [kParser]: parser } = this - - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - - if (client[kHTTPConnVersion] !== 'h2') { - // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded - // to the user. - if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so for as a valid response. - parser.onMessageComplete() - return - } - } - - this[kError] = err - - onError(this[kClient], err) -} - -function onError (client, err) { - if ( - client[kRunning] === 0 && - err.code !== 'UND_ERR_INFO' && - err.code !== 'UND_ERR_SOCKET' - ) { - // Error is not caused by running request and not a recoverable - // socket error. - - assert(client[kPendingIdx] === client[kRunningIdx]) - - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(client, request, err) - } - assert(client[kSize] === 0) - } -} - -function onSocketEnd () { - const { [kParser]: parser, [kClient]: client } = this - - if (client[kHTTPConnVersion] !== 'h2') { - if (parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() - return - } - } - - util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) -} - -function onSocketClose () { - const { [kClient]: client, [kParser]: parser } = this - - if (client[kHTTPConnVersion] === 'h1' && parser) { - if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() - } - - this[kParser].destroy() - this[kParser] = null - } - - const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - - client[kSocket] = null - - if (client.destroyed) { - assert(client[kPending] === 0) - - // Fail entire queue. - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(client, request, err) - } - } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { - // Fail head of pipeline. - const request = client[kQueue][client[kRunningIdx]] - client[kQueue][client[kRunningIdx]++] = null - - errorRequest(client, request, err) - } - - client[kPendingIdx] = client[kRunningIdx] - - assert(client[kRunning] === 0) - - client.emit('disconnect', client[kUrl], [client], err) - - resume(client) -} - -async function connect (client) { - assert(!client[kConnecting]) - assert(!client[kSocket]) - - let { host, hostname, protocol, port } = client[kUrl] - - // Resolve ipv6 - if (hostname[0] === '[') { - const idx = hostname.indexOf(']') - - assert(idx !== -1) - const ip = hostname.substring(1, idx) - - assert(net.isIP(ip)) - hostname = ip - } - - client[kConnecting] = true - - if (channels.beforeConnect.hasSubscribers) { - channels.beforeConnect.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector] - }) - } - - try { - const socket = await new Promise((resolve, reject) => { - client[kConnector]({ - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, (err, socket) => { - if (err) { - reject(err) - } else { - resolve(socket) - } - }) - }) - - if (client.destroyed) { - util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) - return - } - - client[kConnecting] = false - - assert(socket) - - const isH2 = socket.alpnProtocol === 'h2' - if (isH2) { - if (!h2ExperimentalWarned) { - h2ExperimentalWarned = true - process.emitWarning('H2 support is experimental, expect them to change at any time.', { - code: 'UNDICI-H2' - }) - } - - const session = http2.connect(client[kUrl], { - createConnection: () => socket, - peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams - }) - - client[kHTTPConnVersion] = 'h2' - session[kClient] = client - session[kSocket] = socket - session.on('error', onHttp2SessionError) - session.on('frameError', onHttp2FrameError) - session.on('end', onHttp2SessionEnd) - session.on('goaway', onHTTP2GoAway) - session.on('close', onSocketClose) - session.unref() - - client[kHTTP2Session] = session - socket[kHTTP2Session] = session - } else { - if (!llhttpInstance) { - llhttpInstance = await llhttpPromise - llhttpPromise = null - } - - socket[kNoRef] = false - socket[kWriting] = false - socket[kReset] = false - socket[kBlocking] = false - socket[kParser] = new Parser(client, socket, llhttpInstance) - } - - socket[kCounter] = 0 - socket[kMaxRequests] = client[kMaxRequests] - socket[kClient] = client - socket[kError] = null - - socket - .on('error', onSocketError) - .on('readable', onSocketReadable) - .on('end', onSocketEnd) - .on('close', onSocketClose) - - client[kSocket] = socket - - if (channels.connected.hasSubscribers) { - channels.connected.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - socket - }) - } - client.emit('connect', client[kUrl], [client]) - } catch (err) { - if (client.destroyed) { - return - } - - client[kConnecting] = false - - if (channels.connectError.hasSubscribers) { - channels.connectError.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - error: err - }) - } - - if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { - assert(client[kRunning] === 0) - while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { - const request = client[kQueue][client[kPendingIdx]++] - errorRequest(client, request, err) - } - } else { - onError(client, err) - } - - client.emit('connectionError', client[kUrl], [client], err) - } - - resume(client) -} - -function emitDrain (client) { - client[kNeedDrain] = 0 - client.emit('drain', client[kUrl], [client]) -} - -function resume (client, sync) { - if (client[kResuming] === 2) { - return - } - - client[kResuming] = 2 - - _resume(client, sync) - client[kResuming] = 0 - - if (client[kRunningIdx] > 256) { - client[kQueue].splice(0, client[kRunningIdx]) - client[kPendingIdx] -= client[kRunningIdx] - client[kRunningIdx] = 0 - } -} - -function _resume (client, sync) { - while (true) { - if (client.destroyed) { - assert(client[kPending] === 0) - return - } - - if (client[kClosedResolve] && !client[kSize]) { - client[kClosedResolve]() - client[kClosedResolve] = null - return - } - - const socket = client[kSocket] - - if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { - if (client[kSize] === 0) { - if (!socket[kNoRef] && socket.unref) { - socket.unref() - socket[kNoRef] = true - } - } else if (socket[kNoRef] && socket.ref) { - socket.ref() - socket[kNoRef] = false - } - - if (client[kSize] === 0) { - if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { - socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) - } - } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { - if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { - const request = client[kQueue][client[kRunningIdx]] - const headersTimeout = request.headersTimeout != null - ? request.headersTimeout - : client[kHeadersTimeout] - socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) - } - } - } - - if (client[kBusy]) { - client[kNeedDrain] = 2 - } else if (client[kNeedDrain] === 2) { - if (sync) { - client[kNeedDrain] = 1 - process.nextTick(emitDrain, client) - } else { - emitDrain(client) - } - continue - } - - if (client[kPending] === 0) { - return - } - - if (client[kRunning] >= (client[kPipelining] || 1)) { - return - } - - const request = client[kQueue][client[kPendingIdx]] - - if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { - if (client[kRunning] > 0) { - return - } - - client[kServerName] = request.servername - - if (socket && socket.servername !== request.servername) { - util.destroy(socket, new InformationalError('servername changed')) - return - } - } - - if (client[kConnecting]) { - return - } - - if (!socket && !client[kHTTP2Session]) { - connect(client) - return - } - - if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { - return - } - - if (client[kRunning] > 0 && !request.idempotent) { - // Non-idempotent request cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } - - if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { - // Don't dispatch an upgrade until all preceding requests have completed. - // A misbehaving server might upgrade the connection before all pipelined - // request has completed. - return - } - - if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && - (util.isStream(request.body) || util.isAsyncIterable(request.body))) { - // Request with stream or iterator body can error while other requests - // are inflight and indirectly error those as well. - // Ensure this doesn't happen by waiting for inflight - // to complete before dispatching. - - // Request with stream or iterator body cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } - - if (!request.aborted && write(client, request)) { - client[kPendingIdx]++ - } else { - client[kQueue].splice(client[kPendingIdx], 1) - } - } -} - -// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 -function shouldSendContentLength (method) { - return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' -} - -function write (client, request) { - if (client[kHTTPConnVersion] === 'h2') { - writeH2(client, client[kHTTP2Session], request) - return - } - - const { body, method, path, host, upgrade, headers, blocking, reset } = request - - // https://tools.ietf.org/html/rfc7231#section-4.3.1 - // https://tools.ietf.org/html/rfc7231#section-4.3.2 - // https://tools.ietf.org/html/rfc7231#section-4.3.5 - - // Sending a payload body on a request that does not - // expect it can cause undefined behavior on some - // servers and corrupt connection state. Do not - // re-use the connection for further requests. - - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) - - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } - - const bodyLength = util.bodyLength(body) - - let contentLength = bodyLength - - if (contentLength === null) { - contentLength = request.contentLength - } - - if (contentLength === 0 && !expectsPayload) { - // https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD NOT send a Content-Length header field when - // the request message does not contain a payload body and the method - // semantics do not anticipate such a body. - - contentLength = null - } - - // https://github.com/nodejs/undici/issues/2046 - // A user agent may send a Content-Length header with 0 value, this should be allowed. - if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { - if (client[kStrictContentLength]) { - errorRequest(client, request, new RequestContentLengthMismatchError()) - return false - } - - process.emitWarning(new RequestContentLengthMismatchError()) - } - - const socket = client[kSocket] - - try { - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } - - errorRequest(client, request, err || new RequestAbortedError()) - - util.destroy(socket, new InformationalError('aborted')) - }) - } catch (err) { - errorRequest(client, request, err) - } - - if (request.aborted) { - return false - } - - if (method === 'HEAD') { - // https://github.com/mcollina/undici/issues/258 - // Close after a HEAD request to interop with misbehaving servers - // that may send a body in the response. - - socket[kReset] = true - } - - if (upgrade || method === 'CONNECT') { - // On CONNECT or upgrade, block pipeline from dispatching further - // requests on this connection. - - socket[kReset] = true - } - - if (reset != null) { - socket[kReset] = reset - } - - if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { - socket[kReset] = true - } - - if (blocking) { - socket[kBlocking] = true - } - - let header = `${method} ${path} HTTP/1.1\r\n` - - if (typeof host === 'string') { - header += `host: ${host}\r\n` - } else { - header += client[kHostHeader] - } - - if (upgrade) { - header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` - } else if (client[kPipelining] && !socket[kReset]) { - header += 'connection: keep-alive\r\n' - } else { - header += 'connection: close\r\n' - } - - if (headers) { - header += headers - } - - if (channels.sendHeaders.hasSubscribers) { - channels.sendHeaders.publish({ request, headers: header, socket }) - } - - /* istanbul ignore else: assertion */ - if (!body || bodyLength === 0) { - if (contentLength === 0) { - socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') - } else { - assert(contentLength === null, 'no body must not have content length') - socket.write(`${header}\r\n`, 'latin1') - } - request.onRequestSent() - } else if (util.isBuffer(body)) { - assert(contentLength === body.byteLength, 'buffer body must have content length') - - socket.cork() - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - socket.write(body) - socket.uncork() - request.onBodySent(body) - request.onRequestSent() - if (!expectsPayload) { - socket[kReset] = true - } - } else if (util.isBlobLike(body)) { - if (typeof body.stream === 'function') { - writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) - } else { - writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) - } - } else if (util.isStream(body)) { - writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) - } else if (util.isIterable(body)) { - writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) - } else { - assert(false) - } - - return true -} - -function writeH2 (client, session, request) { - const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - - let headers - if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) - else headers = reqHeaders - - if (upgrade) { - errorRequest(client, request, new Error('Upgrade not supported for H2')) - return false - } - - try { - // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } - - errorRequest(client, request, err || new RequestAbortedError()) - }) - } catch (err) { - errorRequest(client, request, err) - } - - if (request.aborted) { - return false - } - - /** @type {import('node:http2').ClientHttp2Stream} */ - let stream - const h2State = client[kHTTP2SessionState] - - headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] - headers[HTTP2_HEADER_METHOD] = method - - if (method === 'CONNECT') { - session.ref() - // we are already connected, streams are pending, first request - // will create a new stream. We trigger a request to create the stream and wait until - // `ready` event is triggered - // We disabled endStream to allow the user to write to the stream - stream = session.request(headers, { endStream: false, signal }) - - if (stream.id && !stream.pending) { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - } else { - stream.once('ready', () => { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - }) - } - - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) session.unref() - }) - - return true - } - - // https://tools.ietf.org/html/rfc7540#section-8.3 - // :path and :scheme headers must be omited when sending CONNECT - - headers[HTTP2_HEADER_PATH] = path - headers[HTTP2_HEADER_SCHEME] = 'https' - - // https://tools.ietf.org/html/rfc7231#section-4.3.1 - // https://tools.ietf.org/html/rfc7231#section-4.3.2 - // https://tools.ietf.org/html/rfc7231#section-4.3.5 - - // Sending a payload body on a request that does not - // expect it can cause undefined behavior on some - // servers and corrupt connection state. Do not - // re-use the connection for further requests. - - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) - - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } - - let contentLength = util.bodyLength(body) - - if (contentLength == null) { - contentLength = request.contentLength - } - - if (contentLength === 0 || !expectsPayload) { - // https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD NOT send a Content-Length header field when - // the request message does not contain a payload body and the method - // semantics do not anticipate such a body. - - contentLength = null - } - - // https://github.com/nodejs/undici/issues/2046 - // A user agent may send a Content-Length header with 0 value, this should be allowed. - if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { - if (client[kStrictContentLength]) { - errorRequest(client, request, new RequestContentLengthMismatchError()) - return false - } - - process.emitWarning(new RequestContentLengthMismatchError()) - } - - if (contentLength != null) { - assert(body, 'no body must not have content length') - headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` - } - - session.ref() - - const shouldEndStream = method === 'GET' || method === 'HEAD' - if (expectContinue) { - headers[HTTP2_HEADER_EXPECT] = '100-continue' - stream = session.request(headers, { endStream: shouldEndStream, signal }) - - stream.once('continue', writeBodyH2) - } else { - stream = session.request(headers, { - endStream: shouldEndStream, - signal - }) - writeBodyH2() - } - - // Increment counter as we have new several streams open - ++h2State.openStreams - - stream.once('response', headers => { - const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers - - if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { - stream.pause() - } - }) - - stream.once('end', () => { - request.onComplete([]) - }) - - stream.on('data', (chunk) => { - if (request.onData(chunk) === false) { - stream.pause() - } - }) - - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) { - session.unref() - } - }) - - stream.once('error', function (err) { - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) - - stream.once('frameError', (type, code) => { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - errorRequest(client, request, err) - - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) - - // stream.on('aborted', () => { - // // TODO(HTTP/2): Support aborted - // }) - - // stream.on('timeout', () => { - // // TODO(HTTP/2): Support timeout - // }) - - // stream.on('push', headers => { - // // TODO(HTTP/2): Suppor push - // }) - - // stream.on('trailers', headers => { - // // TODO(HTTP/2): Support trailers - // }) - - return true - - function writeBodyH2 () { - /* istanbul ignore else: assertion */ - if (!body) { - request.onRequestSent() - } else if (util.isBuffer(body)) { - assert(contentLength === body.byteLength, 'buffer body must have content length') - stream.cork() - stream.write(body) - stream.uncork() - stream.end() - request.onBodySent(body) - request.onRequestSent() - } else if (util.isBlobLike(body)) { - if (typeof body.stream === 'function') { - writeIterable({ - client, - request, - contentLength, - h2stream: stream, - expectsPayload, - body: body.stream(), - socket: client[kSocket], - header: '' - }) - } else { - writeBlob({ - body, - client, - request, - contentLength, - expectsPayload, - h2stream: stream, - header: '', - socket: client[kSocket] - }) - } - } else if (util.isStream(body)) { - writeStream({ - body, - client, - request, - contentLength, - expectsPayload, - socket: client[kSocket], - h2stream: stream, - header: '' - }) - } else if (util.isIterable(body)) { - writeIterable({ - body, - client, - request, - contentLength, - expectsPayload, - header: '', - h2stream: stream, - socket: client[kSocket] - }) - } else { - assert(false) - } - } -} - -function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - - if (client[kHTTPConnVersion] === 'h2') { - // For HTTP/2, is enough to pipe the stream - const pipe = pipeline( - body, - h2stream, - (err) => { - if (err) { - util.destroy(body, err) - util.destroy(h2stream, err) - } else { - request.onRequestSent() - } - } - ) - - pipe.on('data', onPipeData) - pipe.once('end', () => { - pipe.removeListener('data', onPipeData) - util.destroy(pipe) - }) - - function onPipeData (chunk) { - request.onBodySent(chunk) - } - - return - } - - let finished = false - - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - - const onData = function (chunk) { - if (finished) { - return - } - - try { - if (!writer.write(chunk) && this.pause) { - this.pause() - } - } catch (err) { - util.destroy(this, err) - } - } - const onDrain = function () { - if (finished) { - return - } - - if (body.resume) { - body.resume() - } - } - const onAbort = function () { - if (finished) { - return - } - const err = new RequestAbortedError() - queueMicrotask(() => onFinished(err)) - } - const onFinished = function (err) { - if (finished) { - return - } - - finished = true - - assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) - - socket - .off('drain', onDrain) - .off('error', onFinished) - - body - .removeListener('data', onData) - .removeListener('end', onFinished) - .removeListener('error', onFinished) - .removeListener('close', onAbort) - - if (!err) { - try { - writer.end() - } catch (er) { - err = er - } - } - - writer.destroy(err) - - if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { - util.destroy(body, err) - } else { - util.destroy(body) - } - } - - body - .on('data', onData) - .on('end', onFinished) - .on('error', onFinished) - .on('close', onAbort) - - if (body.resume) { - body.resume() - } - - socket - .on('drain', onDrain) - .on('error', onFinished) -} - -async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength === body.size, 'blob body must have content length') - - const isH2 = client[kHTTPConnVersion] === 'h2' - try { - if (contentLength != null && contentLength !== body.size) { - throw new RequestContentLengthMismatchError() - } - - const buffer = Buffer.from(await body.arrayBuffer()) - - if (isH2) { - h2stream.cork() - h2stream.write(buffer) - h2stream.uncork() - } else { - socket.cork() - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - socket.write(buffer) - socket.uncork() - } - - request.onBodySent(buffer) - request.onRequestSent() - - if (!expectsPayload) { - socket[kReset] = true - } - - resume(client) - } catch (err) { - util.destroy(isH2 ? h2stream : socket, err) - } -} - -async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - - let callback = null - function onDrain () { - if (callback) { - const cb = callback - callback = null - cb() - } - } - - const waitForDrain = () => new Promise((resolve, reject) => { - assert(callback === null) - - if (socket[kError]) { - reject(socket[kError]) - } else { - callback = resolve - } - }) - - if (client[kHTTPConnVersion] === 'h2') { - h2stream - .on('close', onDrain) - .on('drain', onDrain) - - try { - // It's up to the user to somehow abort the async iterable. - for await (const chunk of body) { - if (socket[kError]) { - throw socket[kError] - } - - const res = h2stream.write(chunk) - request.onBodySent(chunk) - if (!res) { - await waitForDrain() - } - } - } catch (err) { - h2stream.destroy(err) - } finally { - request.onRequestSent() - h2stream.end() - h2stream - .off('close', onDrain) - .off('drain', onDrain) - } - - return - } - - socket - .on('close', onDrain) - .on('drain', onDrain) - - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - try { - // It's up to the user to somehow abort the async iterable. - for await (const chunk of body) { - if (socket[kError]) { - throw socket[kError] - } - - if (!writer.write(chunk)) { - await waitForDrain() - } - } - - writer.end() - } catch (err) { - writer.destroy(err) - } finally { - socket - .off('close', onDrain) - .off('drain', onDrain) - } -} - -class AsyncWriter { - constructor ({ socket, request, contentLength, client, expectsPayload, header }) { - this.socket = socket - this.request = request - this.contentLength = contentLength - this.client = client - this.bytesWritten = 0 - this.expectsPayload = expectsPayload - this.header = header - - socket[kWriting] = true - } - - write (chunk) { - const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this - - if (socket[kError]) { - throw socket[kError] - } - - if (socket.destroyed) { - return false - } - - const len = Buffer.byteLength(chunk) - if (!len) { - return true - } - - // We should defer writing chunks. - if (contentLength !== null && bytesWritten + len > contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } - - process.emitWarning(new RequestContentLengthMismatchError()) - } - - socket.cork() - - if (bytesWritten === 0) { - if (!expectsPayload) { - socket[kReset] = true - } - - if (contentLength === null) { - socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') - } else { - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - } - } - - if (contentLength === null) { - socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') - } - - this.bytesWritten += len - - const ret = socket.write(chunk) - - socket.uncork() - - request.onBodySent(chunk) - - if (!ret) { - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() - } - } - } - - return ret - } - - end () { - const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this - request.onRequestSent() - - socket[kWriting] = false - - if (socket[kError]) { - throw socket[kError] - } - - if (socket.destroyed) { - return - } - - if (bytesWritten === 0) { - if (expectsPayload) { - // https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD send a Content-Length in a request message when - // no Transfer-Encoding is sent and the request method defines a meaning - // for an enclosed payload body. - - socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') - } else { - socket.write(`${header}\r\n`, 'latin1') - } - } else if (contentLength === null) { - socket.write('\r\n0\r\n\r\n', 'latin1') - } - - if (contentLength !== null && bytesWritten !== contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } else { - process.emitWarning(new RequestContentLengthMismatchError()) - } - } - - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() - } - } - - resume(client) - } - - destroy (err) { - const { socket, client } = this - - socket[kWriting] = false - - if (err) { - assert(client[kRunning] <= 1, 'pipeline should only contain this request') - util.destroy(socket, err) - } - } -} - -function errorRequest (client, request, err) { - try { - request.onError(err) - assert(request.aborted) - } catch (err) { - client.emit('error', err) - } -} - -module.exports = Client - - -/***/ }), - -/***/ 3194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -/* istanbul ignore file: only for Node 12 */ - -const { kConnected, kSize } = __nccwpck_require__(6443) - -class CompatWeakRef { - constructor (value) { - this.value = value - } - - deref () { - return this.value[kConnected] === 0 && this.value[kSize] === 0 - ? undefined - : this.value - } -} - -class CompatFinalizer { - constructor (finalizer) { - this.finalizer = finalizer - } - - register (dispatcher, key) { - if (dispatcher.on) { - dispatcher.on('disconnect', () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key) - } - }) - } - } -} - -module.exports = function () { - // FIXME: remove workaround when the Node bug is fixed - // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 - if (process.env.NODE_V8_COVERAGE) { - return { - WeakRef: CompatWeakRef, - FinalizationRegistry: CompatFinalizer - } - } - return { - WeakRef: global.WeakRef || CompatWeakRef, - FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer - } -} - - -/***/ }), - -/***/ 9237: -/***/ ((module) => { - - - -// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size -const maxAttributeValueSize = 1024 - -// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size -const maxNameValuePairSize = 4096 - -module.exports = { - maxAttributeValueSize, - maxNameValuePairSize -} - - -/***/ }), - -/***/ 3168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { parseSetCookie } = __nccwpck_require__(8915) -const { stringify } = __nccwpck_require__(3834) -const { webidl } = __nccwpck_require__(4222) -const { Headers } = __nccwpck_require__(6349) - -/** - * @typedef {Object} Cookie - * @property {string} name - * @property {string} value - * @property {Date|number|undefined} expires - * @property {number|undefined} maxAge - * @property {string|undefined} domain - * @property {string|undefined} path - * @property {boolean|undefined} secure - * @property {boolean|undefined} httpOnly - * @property {'Strict'|'Lax'|'None'} sameSite - * @property {string[]} unparsed - */ - -/** - * @param {Headers} headers - * @returns {Record} - */ -function getCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - const cookie = headers.get('cookie') - const out = {} - - if (!cookie) { - return out - } - - for (const piece of cookie.split(';')) { - const [name, ...value] = piece.split('=') - - out[name.trim()] = value.join('=') - } - - return out -} - -/** - * @param {Headers} headers - * @param {string} name - * @param {{ path?: string, domain?: string }|undefined} attributes - * @returns {void} - */ -function deleteCookie (headers, name, attributes) { - webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - name = webidl.converters.DOMString(name) - attributes = webidl.converters.DeleteCookieAttributes(attributes) - - // Matches behavior of - // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 - setCookie(headers, { - name, - value: '', - expires: new Date(0), - ...attributes - }) -} - -/** - * @param {Headers} headers - * @returns {Cookie[]} - */ -function getSetCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - const cookies = headers.getSetCookie() - - if (!cookies) { - return [] - } - - return cookies.map((pair) => parseSetCookie(pair)) -} - -/** - * @param {Headers} headers - * @param {Cookie} cookie - * @returns {void} - */ -function setCookie (headers, cookie) { - webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - cookie = webidl.converters.Cookie(cookie) - - const str = stringify(cookie) - - if (str) { - headers.append('Set-Cookie', stringify(cookie)) - } -} - -webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'path', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'domain', - defaultValue: null - } -]) - -webidl.converters.Cookie = webidl.dictionaryConverter([ - { - converter: webidl.converters.DOMString, - key: 'name' - }, - { - converter: webidl.converters.DOMString, - key: 'value' - }, - { - converter: webidl.nullableConverter((value) => { - if (typeof value === 'number') { - return webidl.converters['unsigned long long'](value) - } - - return new Date(value) - }), - key: 'expires', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters['long long']), - key: 'maxAge', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'domain', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'path', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.boolean), - key: 'secure', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.boolean), - key: 'httpOnly', - defaultValue: null - }, - { - converter: webidl.converters.USVString, - key: 'sameSite', - allowedValues: ['Strict', 'Lax', 'None'] - }, - { - converter: webidl.sequenceConverter(webidl.converters.DOMString), - key: 'unparsed', - defaultValue: [] - } -]) - -module.exports = { - getCookies, - deleteCookie, - getSetCookies, - setCookie -} - - -/***/ }), - -/***/ 8915: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237) -const { isCTLExcludingHtab } = __nccwpck_require__(3834) -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322) -const assert = __nccwpck_require__(2613) - -/** - * @description Parses the field-value attributes of a set-cookie header string. - * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 - * @param {string} header - * @returns if the header is invalid, null will be returned - */ -function parseSetCookie (header) { - // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F - // character (CTL characters excluding HTAB): Abort these steps and - // ignore the set-cookie-string entirely. - if (isCTLExcludingHtab(header)) { - return null - } - - let nameValuePair = '' - let unparsedAttributes = '' - let name = '' - let value = '' - - // 2. If the set-cookie-string contains a %x3B (";") character: - if (header.includes(';')) { - // 1. The name-value-pair string consists of the characters up to, - // but not including, the first %x3B (";"), and the unparsed- - // attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question). - const position = { position: 0 } - - nameValuePair = collectASequenceOfCodePointsFast(';', header, position) - unparsedAttributes = header.slice(position.position) - } else { - // Otherwise: - - // 1. The name-value-pair string consists of all the characters - // contained in the set-cookie-string, and the unparsed- - // attributes is the empty string. - nameValuePair = header - } - - // 3. If the name-value-pair string lacks a %x3D ("=") character, then - // the name string is empty, and the value string is the value of - // name-value-pair. - if (!nameValuePair.includes('=')) { - value = nameValuePair - } else { - // Otherwise, the name string consists of the characters up to, but - // not including, the first %x3D ("=") character, and the (possibly - // empty) value string consists of the characters after the first - // %x3D ("=") character. - const position = { position: 0 } - name = collectASequenceOfCodePointsFast( - '=', - nameValuePair, - position - ) - value = nameValuePair.slice(position.position + 1) - } - - // 4. Remove any leading or trailing WSP characters from the name - // string and the value string. - name = name.trim() - value = value.trim() - - // 5. If the sum of the lengths of the name string and the value string - // is more than 4096 octets, abort these steps and ignore the set- - // cookie-string entirely. - if (name.length + value.length > maxNameValuePairSize) { - return null - } - - // 6. The cookie-name is the name string, and the cookie-value is the - // value string. - return { - name, value, ...parseUnparsedAttributes(unparsedAttributes) - } -} - -/** - * Parses the remaining attributes of a set-cookie header - * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 - * @param {string} unparsedAttributes - * @param {[Object.]={}} cookieAttributeList - */ -function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { - // 1. If the unparsed-attributes string is empty, skip the rest of - // these steps. - if (unparsedAttributes.length === 0) { - return cookieAttributeList - } - - // 2. Discard the first character of the unparsed-attributes (which - // will be a %x3B (";") character). - assert(unparsedAttributes[0] === ';') - unparsedAttributes = unparsedAttributes.slice(1) - - let cookieAv = '' - - // 3. If the remaining unparsed-attributes contains a %x3B (";") - // character: - if (unparsedAttributes.includes(';')) { - // 1. Consume the characters of the unparsed-attributes up to, but - // not including, the first %x3B (";") character. - cookieAv = collectASequenceOfCodePointsFast( - ';', - unparsedAttributes, - { position: 0 } - ) - unparsedAttributes = unparsedAttributes.slice(cookieAv.length) - } else { - // Otherwise: - - // 1. Consume the remainder of the unparsed-attributes. - cookieAv = unparsedAttributes - unparsedAttributes = '' - } - - // Let the cookie-av string be the characters consumed in this step. - - let attributeName = '' - let attributeValue = '' - - // 4. If the cookie-av string contains a %x3D ("=") character: - if (cookieAv.includes('=')) { - // 1. The (possibly empty) attribute-name string consists of the - // characters up to, but not including, the first %x3D ("=") - // character, and the (possibly empty) attribute-value string - // consists of the characters after the first %x3D ("=") - // character. - const position = { position: 0 } - - attributeName = collectASequenceOfCodePointsFast( - '=', - cookieAv, - position - ) - attributeValue = cookieAv.slice(position.position + 1) - } else { - // Otherwise: - - // 1. The attribute-name string consists of the entire cookie-av - // string, and the attribute-value string is empty. - attributeName = cookieAv - } - - // 5. Remove any leading or trailing WSP characters from the attribute- - // name string and the attribute-value string. - attributeName = attributeName.trim() - attributeValue = attributeValue.trim() - - // 6. If the attribute-value is longer than 1024 octets, ignore the - // cookie-av string and return to Step 1 of this algorithm. - if (attributeValue.length > maxAttributeValueSize) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } - - // 7. Process the attribute-name and attribute-value according to the - // requirements in the following subsections. (Notice that - // attributes with unrecognized attribute-names are ignored.) - const attributeNameLowercase = attributeName.toLowerCase() - - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 - // If the attribute-name case-insensitively matches the string - // "Expires", the user agent MUST process the cookie-av as follows. - if (attributeNameLowercase === 'expires') { - // 1. Let the expiry-time be the result of parsing the attribute-value - // as cookie-date (see Section 5.1.1). - const expiryTime = new Date(attributeValue) - - // 2. If the attribute-value failed to parse as a cookie date, ignore - // the cookie-av. - - cookieAttributeList.expires = expiryTime - } else if (attributeNameLowercase === 'max-age') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 - // If the attribute-name case-insensitively matches the string "Max- - // Age", the user agent MUST process the cookie-av as follows. - - // 1. If the first character of the attribute-value is not a DIGIT or a - // "-" character, ignore the cookie-av. - const charCode = attributeValue.charCodeAt(0) - - if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } - - // 2. If the remainder of attribute-value contains a non-DIGIT - // character, ignore the cookie-av. - if (!/^\d+$/.test(attributeValue)) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } - - // 3. Let delta-seconds be the attribute-value converted to an integer. - const deltaSeconds = Number(attributeValue) - - // 4. Let cookie-age-limit be the maximum age of the cookie (which - // SHOULD be 400 days or less, see Section 4.1.2.2). - - // 5. Set delta-seconds to the smaller of its present value and cookie- - // age-limit. - // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) - - // 6. If delta-seconds is less than or equal to zero (0), let expiry- - // time be the earliest representable date and time. Otherwise, let - // the expiry-time be the current date and time plus delta-seconds - // seconds. - // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds - - // 7. Append an attribute to the cookie-attribute-list with an - // attribute-name of Max-Age and an attribute-value of expiry-time. - cookieAttributeList.maxAge = deltaSeconds - } else if (attributeNameLowercase === 'domain') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 - // If the attribute-name case-insensitively matches the string "Domain", - // the user agent MUST process the cookie-av as follows. - - // 1. Let cookie-domain be the attribute-value. - let cookieDomain = attributeValue - - // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be - // cookie-domain without its leading %x2E ("."). - if (cookieDomain[0] === '.') { - cookieDomain = cookieDomain.slice(1) - } - - // 3. Convert the cookie-domain to lower case. - cookieDomain = cookieDomain.toLowerCase() - - // 4. Append an attribute to the cookie-attribute-list with an - // attribute-name of Domain and an attribute-value of cookie-domain. - cookieAttributeList.domain = cookieDomain - } else if (attributeNameLowercase === 'path') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 - // If the attribute-name case-insensitively matches the string "Path", - // the user agent MUST process the cookie-av as follows. - - // 1. If the attribute-value is empty or if the first character of the - // attribute-value is not %x2F ("/"): - let cookiePath = '' - if (attributeValue.length === 0 || attributeValue[0] !== '/') { - // 1. Let cookie-path be the default-path. - cookiePath = '/' - } else { - // Otherwise: - - // 1. Let cookie-path be the attribute-value. - cookiePath = attributeValue - } - - // 2. Append an attribute to the cookie-attribute-list with an - // attribute-name of Path and an attribute-value of cookie-path. - cookieAttributeList.path = cookiePath - } else if (attributeNameLowercase === 'secure') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 - // If the attribute-name case-insensitively matches the string "Secure", - // the user agent MUST append an attribute to the cookie-attribute-list - // with an attribute-name of Secure and an empty attribute-value. - - cookieAttributeList.secure = true - } else if (attributeNameLowercase === 'httponly') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 - // If the attribute-name case-insensitively matches the string - // "HttpOnly", the user agent MUST append an attribute to the cookie- - // attribute-list with an attribute-name of HttpOnly and an empty - // attribute-value. - - cookieAttributeList.httpOnly = true - } else if (attributeNameLowercase === 'samesite') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 - // If the attribute-name case-insensitively matches the string - // "SameSite", the user agent MUST process the cookie-av as follows: - - // 1. Let enforcement be "Default". - let enforcement = 'Default' - - const attributeValueLowercase = attributeValue.toLowerCase() - // 2. If cookie-av's attribute-value is a case-insensitive match for - // "None", set enforcement to "None". - if (attributeValueLowercase.includes('none')) { - enforcement = 'None' - } - - // 3. If cookie-av's attribute-value is a case-insensitive match for - // "Strict", set enforcement to "Strict". - if (attributeValueLowercase.includes('strict')) { - enforcement = 'Strict' - } - - // 4. If cookie-av's attribute-value is a case-insensitive match for - // "Lax", set enforcement to "Lax". - if (attributeValueLowercase.includes('lax')) { - enforcement = 'Lax' - } - - // 5. Append an attribute to the cookie-attribute-list with an - // attribute-name of "SameSite" and an attribute-value of - // enforcement. - cookieAttributeList.sameSite = enforcement - } else { - cookieAttributeList.unparsed ??= [] - - cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) - } - - // 8. Return to Step 1 of this algorithm. - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) -} - -module.exports = { - parseSetCookie, - parseUnparsedAttributes -} - - -/***/ }), - -/***/ 3834: -/***/ ((module) => { - - - -/** - * @param {string} value - * @returns {boolean} - */ -function isCTLExcludingHtab (value) { - if (value.length === 0) { - return false - } - - for (const char of value) { - const code = char.charCodeAt(0) - - if ( - (code >= 0x00 || code <= 0x08) || - (code >= 0x0A || code <= 0x1F) || - code === 0x7F - ) { - return false - } - } -} - -/** - CHAR = - token = 1* - separators = "(" | ")" | "<" | ">" | "@" - | "," | ";" | ":" | "\" | <"> - | "/" | "[" | "]" | "?" | "=" - | "{" | "}" | SP | HT - * @param {string} name - */ -function validateCookieName (name) { - for (const char of name) { - const code = char.charCodeAt(0) - - if ( - (code <= 0x20 || code > 0x7F) || - char === '(' || - char === ')' || - char === '>' || - char === '<' || - char === '@' || - char === ',' || - char === ';' || - char === ':' || - char === '\\' || - char === '"' || - char === '/' || - char === '[' || - char === ']' || - char === '?' || - char === '=' || - char === '{' || - char === '}' - ) { - throw new Error('Invalid cookie name') - } - } -} - -/** - cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) - cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E - ; US-ASCII characters excluding CTLs, - ; whitespace DQUOTE, comma, semicolon, - ; and backslash - * @param {string} value - */ -function validateCookieValue (value) { - for (const char of value) { - const code = char.charCodeAt(0) - - if ( - code < 0x21 || // exclude CTLs (0-31) - code === 0x22 || - code === 0x2C || - code === 0x3B || - code === 0x5C || - code > 0x7E // non-ascii - ) { - throw new Error('Invalid header value') - } - } -} - -/** - * path-value = - * @param {string} path - */ -function validateCookiePath (path) { - for (const char of path) { - const code = char.charCodeAt(0) - - if (code < 0x21 || char === ';') { - throw new Error('Invalid cookie path') - } - } -} - -/** - * I have no idea why these values aren't allowed to be honest, - * but Deno tests these. - Khafra - * @param {string} domain - */ -function validateCookieDomain (domain) { - if ( - domain.startsWith('-') || - domain.endsWith('.') || - domain.endsWith('-') - ) { - throw new Error('Invalid cookie domain') - } -} - -/** - * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 - * @param {number|Date} date - IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT - ; fixed length/zone/capitalization subset of the format - ; see Section 3.3 of [RFC5322] - - day-name = %x4D.6F.6E ; "Mon", case-sensitive - / %x54.75.65 ; "Tue", case-sensitive - / %x57.65.64 ; "Wed", case-sensitive - / %x54.68.75 ; "Thu", case-sensitive - / %x46.72.69 ; "Fri", case-sensitive - / %x53.61.74 ; "Sat", case-sensitive - / %x53.75.6E ; "Sun", case-sensitive - date1 = day SP month SP year - ; e.g., 02 Jun 1982 - - day = 2DIGIT - month = %x4A.61.6E ; "Jan", case-sensitive - / %x46.65.62 ; "Feb", case-sensitive - / %x4D.61.72 ; "Mar", case-sensitive - / %x41.70.72 ; "Apr", case-sensitive - / %x4D.61.79 ; "May", case-sensitive - / %x4A.75.6E ; "Jun", case-sensitive - / %x4A.75.6C ; "Jul", case-sensitive - / %x41.75.67 ; "Aug", case-sensitive - / %x53.65.70 ; "Sep", case-sensitive - / %x4F.63.74 ; "Oct", case-sensitive - / %x4E.6F.76 ; "Nov", case-sensitive - / %x44.65.63 ; "Dec", case-sensitive - year = 4DIGIT - - GMT = %x47.4D.54 ; "GMT", case-sensitive - - time-of-day = hour ":" minute ":" second - ; 00:00:00 - 23:59:60 (leap second) - - hour = 2DIGIT - minute = 2DIGIT - second = 2DIGIT - */ -function toIMFDate (date) { - if (typeof date === 'number') { - date = new Date(date) - } - - const days = [ - 'Sun', 'Mon', 'Tue', 'Wed', - 'Thu', 'Fri', 'Sat' - ] - - const months = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' - ] - - const dayName = days[date.getUTCDay()] - const day = date.getUTCDate().toString().padStart(2, '0') - const month = months[date.getUTCMonth()] - const year = date.getUTCFullYear() - const hour = date.getUTCHours().toString().padStart(2, '0') - const minute = date.getUTCMinutes().toString().padStart(2, '0') - const second = date.getUTCSeconds().toString().padStart(2, '0') - - return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` -} - -/** - max-age-av = "Max-Age=" non-zero-digit *DIGIT - ; In practice, both expires-av and max-age-av - ; are limited to dates representable by the - ; user agent. - * @param {number} maxAge - */ -function validateCookieMaxAge (maxAge) { - if (maxAge < 0) { - throw new Error('Invalid cookie max-age') - } -} - -/** - * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 - * @param {import('./index').Cookie} cookie - */ -function stringify (cookie) { - if (cookie.name.length === 0) { - return null - } - - validateCookieName(cookie.name) - validateCookieValue(cookie.value) - - const out = [`${cookie.name}=${cookie.value}`] - - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 - if (cookie.name.startsWith('__Secure-')) { - cookie.secure = true - } - - if (cookie.name.startsWith('__Host-')) { - cookie.secure = true - cookie.domain = null - cookie.path = '/' - } - - if (cookie.secure) { - out.push('Secure') - } - - if (cookie.httpOnly) { - out.push('HttpOnly') - } - - if (typeof cookie.maxAge === 'number') { - validateCookieMaxAge(cookie.maxAge) - out.push(`Max-Age=${cookie.maxAge}`) - } - - if (cookie.domain) { - validateCookieDomain(cookie.domain) - out.push(`Domain=${cookie.domain}`) - } - - if (cookie.path) { - validateCookiePath(cookie.path) - out.push(`Path=${cookie.path}`) - } - - if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { - out.push(`Expires=${toIMFDate(cookie.expires)}`) - } - - if (cookie.sameSite) { - out.push(`SameSite=${cookie.sameSite}`) - } - - for (const part of cookie.unparsed) { - if (!part.includes('=')) { - throw new Error('Invalid unparsed') - } - - const [key, ...value] = part.split('=') - - out.push(`${key.trim()}=${value.join('=')}`) - } - - return out.join('; ') -} - -module.exports = { - isCTLExcludingHtab, - validateCookieName, - validateCookiePath, - validateCookieValue, - toIMFDate, - stringify -} - - -/***/ }), - -/***/ 9136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const net = __nccwpck_require__(9278) -const assert = __nccwpck_require__(2613) -const util = __nccwpck_require__(3440) -const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) - -let tls // include tls conditionally since it is not always available - -// TODO: session re-use does not wait for the first -// connection to resolve the session and might therefore -// resolve the same servername multiple times even when -// re-use is enabled. - -let SessionCache -// FIXME: remove workaround when the Node bug is fixed -// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 -if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { - SessionCache = class WeakSessionCache { - constructor (maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions - this._sessionCache = new Map() - this._sessionRegistry = new global.FinalizationRegistry((key) => { - if (this._sessionCache.size < this._maxCachedSessions) { - return - } - - const ref = this._sessionCache.get(key) - if (ref !== undefined && ref.deref() === undefined) { - this._sessionCache.delete(key) - } - }) - } - - get (sessionKey) { - const ref = this._sessionCache.get(sessionKey) - return ref ? ref.deref() : null - } - - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } - - this._sessionCache.set(sessionKey, new WeakRef(session)) - this._sessionRegistry.register(session, sessionKey) - } - } -} else { - SessionCache = class SimpleSessionCache { - constructor (maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions - this._sessionCache = new Map() - } - - get (sessionKey) { - return this._sessionCache.get(sessionKey) - } - - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } - - if (this._sessionCache.size >= this._maxCachedSessions) { - // remove the oldest session - const { value: oldestKey } = this._sessionCache.keys().next() - this._sessionCache.delete(oldestKey) - } - - this._sessionCache.set(sessionKey, session) - } - } -} - -function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { - if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { - throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') - } - - const options = { path: socketPath, ...opts } - const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) - timeout = timeout == null ? 10e3 : timeout - allowH2 = allowH2 != null ? allowH2 : false - return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { - let socket - if (protocol === 'https:') { - if (!tls) { - tls = __nccwpck_require__(4756) - } - servername = servername || options.servername || util.getServerName(host) || null - - const sessionKey = servername || hostname - const session = sessionCache.get(sessionKey) || null - - assert(sessionKey) - - socket = tls.connect({ - highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... - ...options, - servername, - session, - localAddress, - // TODO(HTTP/2): Add support for h2c - ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], - socket: httpSocket, // upgrade socket connection - port: port || 443, - host: hostname - }) - - socket - .on('session', function (session) { - // TODO (fix): Can a session become invalid once established? Don't think so? - sessionCache.set(sessionKey, session) - }) - } else { - assert(!httpSocket, 'httpSocket can only be sent on TLS update') - socket = net.connect({ - highWaterMark: 64 * 1024, // Same as nodejs fs streams. - ...options, - localAddress, - port: port || 80, - host: hostname - }) - } - - // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket - if (options.keepAlive == null || options.keepAlive) { - const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay - socket.setKeepAlive(true, keepAliveInitialDelay) - } - - const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) - - socket - .setNoDelay(true) - .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { - cancelTimeout() - - if (callback) { - const cb = callback - callback = null - cb(null, this) - } - }) - .on('error', function (err) { - cancelTimeout() - - if (callback) { - const cb = callback - callback = null - cb(err) - } - }) - - return socket - } -} - -function setupTimeout (onConnectTimeout, timeout) { - if (!timeout) { - return () => {} - } - - let s1 = null - let s2 = null - const timeoutId = setTimeout(() => { - // setImmediate is added to make sure that we priotorise socket error events over timeouts - s1 = setImmediate(() => { - if (process.platform === 'win32') { - // Windows needs an extra setImmediate probably due to implementation differences in the socket logic - s2 = setImmediate(() => onConnectTimeout()) - } else { - onConnectTimeout() - } - }) - }, timeout) - return () => { - clearTimeout(timeoutId) - clearImmediate(s1) - clearImmediate(s2) - } -} - -function onConnectTimeout (socket) { - util.destroy(socket, new ConnectTimeoutError()) -} - -module.exports = buildConnector - - -/***/ }), - -/***/ 735: -/***/ ((module) => { - - - -/** @type {Record} */ -const headerNameLowerCasedRecord = {} - -// https://developer.mozilla.org/docs/Web/HTTP/Headers -const wellknownHeaderNames = [ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -] - -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey -} - -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) - -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord -} - - -/***/ }), - -/***/ 8707: -/***/ ((module) => { - - - -class UndiciError extends Error { - constructor (message) { - super(message) - this.name = 'UndiciError' - this.code = 'UND_ERR' - } -} - -class ConnectTimeoutError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ConnectTimeoutError) - this.name = 'ConnectTimeoutError' - this.message = message || 'Connect Timeout Error' - this.code = 'UND_ERR_CONNECT_TIMEOUT' - } -} - -class HeadersTimeoutError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, HeadersTimeoutError) - this.name = 'HeadersTimeoutError' - this.message = message || 'Headers Timeout Error' - this.code = 'UND_ERR_HEADERS_TIMEOUT' - } -} - -class HeadersOverflowError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, HeadersOverflowError) - this.name = 'HeadersOverflowError' - this.message = message || 'Headers Overflow Error' - this.code = 'UND_ERR_HEADERS_OVERFLOW' - } -} - -class BodyTimeoutError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, BodyTimeoutError) - this.name = 'BodyTimeoutError' - this.message = message || 'Body Timeout Error' - this.code = 'UND_ERR_BODY_TIMEOUT' - } -} - -class ResponseStatusCodeError extends UndiciError { - constructor (message, statusCode, headers, body) { - super(message) - Error.captureStackTrace(this, ResponseStatusCodeError) - this.name = 'ResponseStatusCodeError' - this.message = message || 'Response Status Code Error' - this.code = 'UND_ERR_RESPONSE_STATUS_CODE' - this.body = body - this.status = statusCode - this.statusCode = statusCode - this.headers = headers - } -} - -class InvalidArgumentError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, InvalidArgumentError) - this.name = 'InvalidArgumentError' - this.message = message || 'Invalid Argument Error' - this.code = 'UND_ERR_INVALID_ARG' - } -} - -class InvalidReturnValueError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, InvalidReturnValueError) - this.name = 'InvalidReturnValueError' - this.message = message || 'Invalid Return Value Error' - this.code = 'UND_ERR_INVALID_RETURN_VALUE' - } -} - -class RequestAbortedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, RequestAbortedError) - this.name = 'AbortError' - this.message = message || 'Request aborted' - this.code = 'UND_ERR_ABORTED' - } -} - -class InformationalError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, InformationalError) - this.name = 'InformationalError' - this.message = message || 'Request information' - this.code = 'UND_ERR_INFO' - } -} - -class RequestContentLengthMismatchError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, RequestContentLengthMismatchError) - this.name = 'RequestContentLengthMismatchError' - this.message = message || 'Request body length does not match content-length header' - this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' - } -} - -class ResponseContentLengthMismatchError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ResponseContentLengthMismatchError) - this.name = 'ResponseContentLengthMismatchError' - this.message = message || 'Response body length does not match content-length header' - this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' - } -} - -class ClientDestroyedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ClientDestroyedError) - this.name = 'ClientDestroyedError' - this.message = message || 'The client is destroyed' - this.code = 'UND_ERR_DESTROYED' - } -} - -class ClientClosedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ClientClosedError) - this.name = 'ClientClosedError' - this.message = message || 'The client is closed' - this.code = 'UND_ERR_CLOSED' - } -} - -class SocketError extends UndiciError { - constructor (message, socket) { - super(message) - Error.captureStackTrace(this, SocketError) - this.name = 'SocketError' - this.message = message || 'Socket error' - this.code = 'UND_ERR_SOCKET' - this.socket = socket - } -} - -class NotSupportedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, NotSupportedError) - this.name = 'NotSupportedError' - this.message = message || 'Not supported error' - this.code = 'UND_ERR_NOT_SUPPORTED' - } -} - -class BalancedPoolMissingUpstreamError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, NotSupportedError) - this.name = 'MissingUpstreamError' - this.message = message || 'No upstream has been added to the BalancedPool' - this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' - } -} - -class HTTPParserError extends Error { - constructor (message, code, data) { - super(message) - Error.captureStackTrace(this, HTTPParserError) - this.name = 'HTTPParserError' - this.code = code ? `HPE_${code}` : undefined - this.data = data ? data.toString() : undefined - } -} - -class ResponseExceededMaxSizeError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ResponseExceededMaxSizeError) - this.name = 'ResponseExceededMaxSizeError' - this.message = message || 'Response content exceeded max size' - this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' - } -} - -class RequestRetryError extends UndiciError { - constructor (message, code, { headers, data }) { - super(message) - Error.captureStackTrace(this, RequestRetryError) - this.name = 'RequestRetryError' - this.message = message || 'Request retry error' - this.code = 'UND_ERR_REQ_RETRY' - this.statusCode = code - this.data = data - this.headers = headers - } -} - -module.exports = { - HTTPParserError, - UndiciError, - HeadersTimeoutError, - HeadersOverflowError, - BodyTimeoutError, - RequestContentLengthMismatchError, - ConnectTimeoutError, - ResponseStatusCodeError, - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError, - ClientDestroyedError, - ClientClosedError, - InformationalError, - SocketError, - NotSupportedError, - ResponseContentLengthMismatchError, - BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError -} - - -/***/ }), - -/***/ 4655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - InvalidArgumentError, - NotSupportedError -} = __nccwpck_require__(8707) -const assert = __nccwpck_require__(2613) -const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443) -const util = __nccwpck_require__(3440) - -// tokenRegExp and headerCharRegex have been lifted from -// https://github.com/nodejs/node/blob/main/lib/_http_common.js - -/** - * Verifies that the given val is a valid HTTP token - * per the rules defined in RFC 7230 - * See https://tools.ietf.org/html/rfc7230#section-3.2.6 - */ -const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ - -/** - * Matches if val contains an invalid field-vchar - * field-value = *( field-content / obs-fold ) - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - */ -const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ - -// Verifies that a given path is valid does not contain control chars \x00 to \x20 -const invalidPathRegex = /[^\u0021-\u00ff]/ - -const kHandler = Symbol('handler') - -const channels = {} - -let extractBody - -try { - const diagnosticsChannel = __nccwpck_require__(1637) - channels.create = diagnosticsChannel.channel('undici:request:create') - channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') - channels.headers = diagnosticsChannel.channel('undici:request:headers') - channels.trailers = diagnosticsChannel.channel('undici:request:trailers') - channels.error = diagnosticsChannel.channel('undici:request:error') -} catch { - channels.create = { hasSubscribers: false } - channels.bodySent = { hasSubscribers: false } - channels.headers = { hasSubscribers: false } - channels.trailers = { hasSubscribers: false } - channels.error = { hasSubscribers: false } -} - -class Request { - constructor (origin, { - path, - method, - body, - headers, - query, - idempotent, - blocking, - upgrade, - headersTimeout, - bodyTimeout, - reset, - throwOnError, - expectContinue - }, handler) { - if (typeof path !== 'string') { - throw new InvalidArgumentError('path must be a string') - } else if ( - path[0] !== '/' && - !(path.startsWith('http://') || path.startsWith('https://')) && - method !== 'CONNECT' - ) { - throw new InvalidArgumentError('path must be an absolute URL or start with a slash') - } else if (invalidPathRegex.exec(path) !== null) { - throw new InvalidArgumentError('invalid request path') - } - - if (typeof method !== 'string') { - throw new InvalidArgumentError('method must be a string') - } else if (tokenRegExp.exec(method) === null) { - throw new InvalidArgumentError('invalid request method') - } - - if (upgrade && typeof upgrade !== 'string') { - throw new InvalidArgumentError('upgrade must be a string') - } - - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('invalid headersTimeout') - } - - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('invalid bodyTimeout') - } - - if (reset != null && typeof reset !== 'boolean') { - throw new InvalidArgumentError('invalid reset') - } - - if (expectContinue != null && typeof expectContinue !== 'boolean') { - throw new InvalidArgumentError('invalid expectContinue') - } - - this.headersTimeout = headersTimeout - - this.bodyTimeout = bodyTimeout - - this.throwOnError = throwOnError === true - - this.method = method - - this.abort = null - - if (body == null) { - this.body = null - } else if (util.isStream(body)) { - this.body = body - - const rState = this.body._readableState - if (!rState || !rState.autoDestroy) { - this.endHandler = function autoDestroy () { - util.destroy(this) - } - this.body.on('end', this.endHandler) - } - - this.errorHandler = err => { - if (this.abort) { - this.abort(err) - } else { - this.error = err - } - } - this.body.on('error', this.errorHandler) - } else if (util.isBuffer(body)) { - this.body = body.byteLength ? body : null - } else if (ArrayBuffer.isView(body)) { - this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null - } else if (body instanceof ArrayBuffer) { - this.body = body.byteLength ? Buffer.from(body) : null - } else if (typeof body === 'string') { - this.body = body.length ? Buffer.from(body) : null - } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { - this.body = body - } else { - throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') - } - - this.completed = false - - this.aborted = false - - this.upgrade = upgrade || null - - this.path = query ? util.buildURL(path, query) : path - - this.origin = origin - - this.idempotent = idempotent == null - ? method === 'HEAD' || method === 'GET' - : idempotent - - this.blocking = blocking == null ? false : blocking - - this.reset = reset == null ? null : reset - - this.host = null - - this.contentLength = null - - this.contentType = null - - this.headers = '' - - // Only for H2 - this.expectContinue = expectContinue != null ? expectContinue : false - - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError('headers array must be even') - } - for (let i = 0; i < headers.length; i += 2) { - processHeader(this, headers[i], headers[i + 1]) - } - } else if (headers && typeof headers === 'object') { - const keys = Object.keys(headers) - for (let i = 0; i < keys.length; i++) { - const key = keys[i] - processHeader(this, key, headers[key]) - } - } else if (headers != null) { - throw new InvalidArgumentError('headers must be an object or an array') - } - - if (util.isFormDataLike(this.body)) { - if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { - throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') - } - - if (!extractBody) { - extractBody = (__nccwpck_require__(8923).extractBody) - } - - const [bodyStream, contentType] = extractBody(body) - if (this.contentType == null) { - this.contentType = contentType - this.headers += `content-type: ${contentType}\r\n` - } - this.body = bodyStream.stream - this.contentLength = bodyStream.length - } else if (util.isBlobLike(body) && this.contentType == null && body.type) { - this.contentType = body.type - this.headers += `content-type: ${body.type}\r\n` - } - - util.validateHandler(handler, method, upgrade) - - this.servername = util.getServerName(this.host) - - this[kHandler] = handler - - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }) - } - } - - onBodySent (chunk) { - if (this[kHandler].onBodySent) { - try { - return this[kHandler].onBodySent(chunk) - } catch (err) { - this.abort(err) - } - } - } - - onRequestSent () { - if (channels.bodySent.hasSubscribers) { - channels.bodySent.publish({ request: this }) - } - - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent() - } catch (err) { - this.abort(err) - } - } - } - - onConnect (abort) { - assert(!this.aborted) - assert(!this.completed) - - if (this.error) { - abort(this.error) - } else { - this.abort = abort - return this[kHandler].onConnect(abort) - } - } - - onHeaders (statusCode, headers, resume, statusText) { - assert(!this.aborted) - assert(!this.completed) - - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) - } - - try { - return this[kHandler].onHeaders(statusCode, headers, resume, statusText) - } catch (err) { - this.abort(err) - } - } - - onData (chunk) { - assert(!this.aborted) - assert(!this.completed) - - try { - return this[kHandler].onData(chunk) - } catch (err) { - this.abort(err) - return false - } - } - - onUpgrade (statusCode, headers, socket) { - assert(!this.aborted) - assert(!this.completed) - - return this[kHandler].onUpgrade(statusCode, headers, socket) - } - - onComplete (trailers) { - this.onFinally() - - assert(!this.aborted) - - this.completed = true - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers }) - } - - try { - return this[kHandler].onComplete(trailers) - } catch (err) { - // TODO (fix): This might be a bad idea? - this.onError(err) - } - } - - onError (error) { - this.onFinally() - - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }) - } - - if (this.aborted) { - return - } - this.aborted = true - - return this[kHandler].onError(error) - } - - onFinally () { - if (this.errorHandler) { - this.body.off('error', this.errorHandler) - this.errorHandler = null - } - - if (this.endHandler) { - this.body.off('end', this.endHandler) - this.endHandler = null - } - } - - // TODO: adjust to support H2 - addHeader (key, value) { - processHeader(this, key, value) - return this - } - - static [kHTTP1BuildRequest] (origin, opts, handler) { - // TODO: Migrate header parsing here, to make Requests - // HTTP agnostic - return new Request(origin, opts, handler) - } - - static [kHTTP2BuildRequest] (origin, opts, handler) { - const headers = opts.headers - opts = { ...opts, headers: null } - - const request = new Request(origin, opts, handler) - - request.headers = {} - - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError('headers array must be even') - } - for (let i = 0; i < headers.length; i += 2) { - processHeader(request, headers[i], headers[i + 1], true) - } - } else if (headers && typeof headers === 'object') { - const keys = Object.keys(headers) - for (let i = 0; i < keys.length; i++) { - const key = keys[i] - processHeader(request, key, headers[key], true) - } - } else if (headers != null) { - throw new InvalidArgumentError('headers must be an object or an array') - } - - return request - } - - static [kHTTP2CopyHeaders] (raw) { - const rawHeaders = raw.split('\r\n') - const headers = {} - - for (const header of rawHeaders) { - const [key, value] = header.split(': ') - - if (value == null || value.length === 0) continue - - if (headers[key]) headers[key] += `,${value}` - else headers[key] = value - } - - return headers - } -} - -function processHeaderValue (key, val, skipAppend) { - if (val && typeof val === 'object') { - throw new InvalidArgumentError(`invalid ${key} header`) - } - - val = val != null ? `${val}` : '' - - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - - return skipAppend ? val : `${key}: ${val}\r\n` -} - -function processHeader (request, key, val, skipAppend = false) { - if (val && (typeof val === 'object' && !Array.isArray(val))) { - throw new InvalidArgumentError(`invalid ${key} header`) - } else if (val === undefined) { - return - } - - if ( - request.host === null && - key.length === 4 && - key.toLowerCase() === 'host' - ) { - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - // Consumed by Client - request.host = val - } else if ( - request.contentLength === null && - key.length === 14 && - key.toLowerCase() === 'content-length' - ) { - request.contentLength = parseInt(val, 10) - if (!Number.isFinite(request.contentLength)) { - throw new InvalidArgumentError('invalid content-length header') - } - } else if ( - request.contentType === null && - key.length === 12 && - key.toLowerCase() === 'content-type' - ) { - request.contentType = val - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) - else request.headers += processHeaderValue(key, val) - } else if ( - key.length === 17 && - key.toLowerCase() === 'transfer-encoding' - ) { - throw new InvalidArgumentError('invalid transfer-encoding header') - } else if ( - key.length === 10 && - key.toLowerCase() === 'connection' - ) { - const value = typeof val === 'string' ? val.toLowerCase() : null - if (value !== 'close' && value !== 'keep-alive') { - throw new InvalidArgumentError('invalid connection header') - } else if (value === 'close') { - request.reset = true - } - } else if ( - key.length === 10 && - key.toLowerCase() === 'keep-alive' - ) { - throw new InvalidArgumentError('invalid keep-alive header') - } else if ( - key.length === 7 && - key.toLowerCase() === 'upgrade' - ) { - throw new InvalidArgumentError('invalid upgrade header') - } else if ( - key.length === 6 && - key.toLowerCase() === 'expect' - ) { - throw new NotSupportedError('expect header not supported') - } else if (tokenRegExp.exec(key) === null) { - throw new InvalidArgumentError('invalid header key') - } else { - if (Array.isArray(val)) { - for (let i = 0; i < val.length; i++) { - if (skipAppend) { - if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` - else request.headers[key] = processHeaderValue(key, val[i], skipAppend) - } else { - request.headers += processHeaderValue(key, val[i]) - } - } - } else { - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) - else request.headers += processHeaderValue(key, val) - } - } -} - -module.exports = Request - - -/***/ }), - -/***/ 6443: -/***/ ((module) => { - -module.exports = { - kClose: Symbol('close'), - kDestroy: Symbol('destroy'), - kDispatch: Symbol('dispatch'), - kUrl: Symbol('url'), - kWriting: Symbol('writing'), - kResuming: Symbol('resuming'), - kQueue: Symbol('queue'), - kConnect: Symbol('connect'), - kConnecting: Symbol('connecting'), - kHeadersList: Symbol('headers list'), - kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), - kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), - kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), - kKeepAliveTimeoutValue: Symbol('keep alive timeout'), - kKeepAlive: Symbol('keep alive'), - kHeadersTimeout: Symbol('headers timeout'), - kBodyTimeout: Symbol('body timeout'), - kServerName: Symbol('server name'), - kLocalAddress: Symbol('local address'), - kHost: Symbol('host'), - kNoRef: Symbol('no ref'), - kBodyUsed: Symbol('used'), - kRunning: Symbol('running'), - kBlocking: Symbol('blocking'), - kPending: Symbol('pending'), - kSize: Symbol('size'), - kBusy: Symbol('busy'), - kQueued: Symbol('queued'), - kFree: Symbol('free'), - kConnected: Symbol('connected'), - kClosed: Symbol('closed'), - kNeedDrain: Symbol('need drain'), - kReset: Symbol('reset'), - kDestroyed: Symbol.for('nodejs.stream.destroyed'), - kMaxHeadersSize: Symbol('max headers size'), - kRunningIdx: Symbol('running index'), - kPendingIdx: Symbol('pending index'), - kError: Symbol('error'), - kClients: Symbol('clients'), - kClient: Symbol('client'), - kParser: Symbol('parser'), - kOnDestroyed: Symbol('destroy callbacks'), - kPipelining: Symbol('pipelining'), - kSocket: Symbol('socket'), - kHostHeader: Symbol('host header'), - kConnector: Symbol('connector'), - kStrictContentLength: Symbol('strict content length'), - kMaxRedirections: Symbol('maxRedirections'), - kMaxRequests: Symbol('maxRequestsPerClient'), - kProxy: Symbol('proxy agent options'), - kCounter: Symbol('socket request counter'), - kInterceptors: Symbol('dispatch interceptors'), - kMaxResponseSize: Symbol('max response size'), - kHTTP2Session: Symbol('http2Session'), - kHTTP2SessionState: Symbol('http2Session state'), - kHTTP2BuildRequest: Symbol('http2 build request'), - kHTTP1BuildRequest: Symbol('http1 build request'), - kHTTP2CopyHeaders: Symbol('http2 copy headers'), - kHTTPConnVersion: Symbol('http connection version'), - kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), - kConstruct: Symbol('constructable') -} - - -/***/ }), - -/***/ 3440: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const assert = __nccwpck_require__(2613) -const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443) -const { IncomingMessage } = __nccwpck_require__(8611) -const stream = __nccwpck_require__(2203) -const net = __nccwpck_require__(9278) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { Blob } = __nccwpck_require__(181) -const nodeUtil = __nccwpck_require__(9023) -const { stringify } = __nccwpck_require__(3480) -const { headerNameLowerCasedRecord } = __nccwpck_require__(735) - -const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) - -function nop () {} - -function isStream (obj) { - return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' -} - -// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) -function isBlobLike (object) { - return (Blob && object instanceof Blob) || ( - object && - typeof object === 'object' && - (typeof object.stream === 'function' || - typeof object.arrayBuffer === 'function') && - /^(Blob|File)$/.test(object[Symbol.toStringTag]) - ) -} - -function buildURL (url, queryParams) { - if (url.includes('?') || url.includes('#')) { - throw new Error('Query params cannot be passed when url already contains "?" or "#".') - } - - const stringified = stringify(queryParams) - - if (stringified) { - url += '?' + stringified - } - - return url -} - -function parseURL (url) { - if (typeof url === 'string') { - url = new URL(url) - - if (!/^https?:/.test(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } - - return url - } - - if (!url || typeof url !== 'object') { - throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') - } - - if (!/^https?:/.test(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } - - if (!(url instanceof URL)) { - if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { - throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') - } - - if (url.path != null && typeof url.path !== 'string') { - throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') - } - - if (url.pathname != null && typeof url.pathname !== 'string') { - throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') - } - - if (url.hostname != null && typeof url.hostname !== 'string') { - throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') - } - - if (url.origin != null && typeof url.origin !== 'string') { - throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') - } - - const port = url.port != null - ? url.port - : (url.protocol === 'https:' ? 443 : 80) - let origin = url.origin != null - ? url.origin - : `${url.protocol}//${url.hostname}:${port}` - let path = url.path != null - ? url.path - : `${url.pathname || ''}${url.search || ''}` - - if (origin.endsWith('/')) { - origin = origin.substring(0, origin.length - 1) - } - - if (path && !path.startsWith('/')) { - path = `/${path}` - } - // new URL(path, origin) is unsafe when `path` contains an absolute URL - // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: - // If first parameter is a relative URL, second param is required, and will be used as the base URL. - // If first parameter is an absolute URL, a given second param will be ignored. - url = new URL(origin + path) - } - - return url -} - -function parseOrigin (url) { - url = parseURL(url) - - if (url.pathname !== '/' || url.search || url.hash) { - throw new InvalidArgumentError('invalid url') - } - - return url -} - -function getHostname (host) { - if (host[0] === '[') { - const idx = host.indexOf(']') - - assert(idx !== -1) - return host.substring(1, idx) - } - - const idx = host.indexOf(':') - if (idx === -1) return host - - return host.substring(0, idx) -} - -// IP addresses are not valid server names per RFC6066 -// > Currently, the only server names supported are DNS hostnames -function getServerName (host) { - if (!host) { - return null - } - - assert.strictEqual(typeof host, 'string') - - const servername = getHostname(host) - if (net.isIP(servername)) { - return '' - } - - return servername -} - -function deepClone (obj) { - return JSON.parse(JSON.stringify(obj)) -} - -function isAsyncIterable (obj) { - return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') -} - -function isIterable (obj) { - return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) -} - -function bodyLength (body) { - if (body == null) { - return 0 - } else if (isStream(body)) { - const state = body._readableState - return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) - ? state.length - : null - } else if (isBlobLike(body)) { - return body.size != null ? body.size : null - } else if (isBuffer(body)) { - return body.byteLength - } - - return null -} - -function isDestroyed (stream) { - return !stream || !!(stream.destroyed || stream[kDestroyed]) -} - -function isReadableAborted (stream) { - const state = stream && stream._readableState - return isDestroyed(stream) && state && !state.endEmitted -} - -function destroy (stream, err) { - if (stream == null || !isStream(stream) || isDestroyed(stream)) { - return - } - - if (typeof stream.destroy === 'function') { - if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { - // See: https://github.com/nodejs/node/pull/38505/files - stream.socket = null - } - - stream.destroy(err) - } else if (err) { - process.nextTick((stream, err) => { - stream.emit('error', err) - }, stream, err) - } - - if (stream.destroyed !== true) { - stream[kDestroyed] = true - } -} - -const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ -function parseKeepAliveTimeout (val) { - const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) - return m ? parseInt(m[1], 10) * 1000 : null -} - -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return headerNameLowerCasedRecord[value] || value.toLowerCase() -} - -function parseHeaders (headers, obj = {}) { - // For H2 support - if (!Array.isArray(headers)) return headers - - for (let i = 0; i < headers.length; i += 2) { - const key = headers[i].toString().toLowerCase() - let val = obj[key] - - if (!val) { - if (Array.isArray(headers[i + 1])) { - obj[key] = headers[i + 1].map(x => x.toString('utf8')) - } else { - obj[key] = headers[i + 1].toString('utf8') - } - } else { - if (!Array.isArray(val)) { - val = [val] - obj[key] = val - } - val.push(headers[i + 1].toString('utf8')) - } - } - - // See https://github.com/nodejs/node/pull/46528 - if ('content-length' in obj && 'content-disposition' in obj) { - obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') - } - - return obj -} - -function parseRawHeaders (headers) { - const ret = [] - let hasContentLength = false - let contentDispositionIdx = -1 - - for (let n = 0; n < headers.length; n += 2) { - const key = headers[n + 0].toString() - const val = headers[n + 1].toString('utf8') - - if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { - ret.push(key, val) - hasContentLength = true - } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { - contentDispositionIdx = ret.push(key, val) - 1 - } else { - ret.push(key, val) - } - } - - // See https://github.com/nodejs/node/pull/46528 - if (hasContentLength && contentDispositionIdx !== -1) { - ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') - } - - return ret -} - -function isBuffer (buffer) { - // See, https://github.com/mcollina/undici/pull/319 - return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) -} - -function validateHandler (handler, method, upgrade) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } - - if (typeof handler.onConnect !== 'function') { - throw new InvalidArgumentError('invalid onConnect method') - } - - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } - - if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { - throw new InvalidArgumentError('invalid onBodySent method') - } - - if (upgrade || method === 'CONNECT') { - if (typeof handler.onUpgrade !== 'function') { - throw new InvalidArgumentError('invalid onUpgrade method') - } - } else { - if (typeof handler.onHeaders !== 'function') { - throw new InvalidArgumentError('invalid onHeaders method') - } - - if (typeof handler.onData !== 'function') { - throw new InvalidArgumentError('invalid onData method') - } - - if (typeof handler.onComplete !== 'function') { - throw new InvalidArgumentError('invalid onComplete method') - } - } -} - -// A body is disturbed if it has been read from and it cannot -// be re-used without losing state or data. -function isDisturbed (body) { - return !!(body && ( - stream.isDisturbed - ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? - : body[kBodyUsed] || - body.readableDidRead || - (body._readableState && body._readableState.dataEmitted) || - isReadableAborted(body) - )) -} - -function isErrored (body) { - return !!(body && ( - stream.isErrored - ? stream.isErrored(body) - : /state: 'errored'/.test(nodeUtil.inspect(body) - ))) -} - -function isReadable (body) { - return !!(body && ( - stream.isReadable - ? stream.isReadable(body) - : /state: 'readable'/.test(nodeUtil.inspect(body) - ))) -} - -function getSocketInfo (socket) { - return { - localAddress: socket.localAddress, - localPort: socket.localPort, - remoteAddress: socket.remoteAddress, - remotePort: socket.remotePort, - remoteFamily: socket.remoteFamily, - timeout: socket.timeout, - bytesWritten: socket.bytesWritten, - bytesRead: socket.bytesRead - } -} - -async function * convertIterableToBuffer (iterable) { - for await (const chunk of iterable) { - yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) - } -} - -let ReadableStream -function ReadableStreamFrom (iterable) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - if (ReadableStream.from) { - return ReadableStream.from(convertIterableToBuffer(iterable)) - } - - let iterator - return new ReadableStream( - { - async start () { - iterator = iterable[Symbol.asyncIterator]() - }, - async pull (controller) { - const { done, value } = await iterator.next() - if (done) { - queueMicrotask(() => { - controller.close() - }) - } else { - const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) - controller.enqueue(new Uint8Array(buf)) - } - return controller.desiredSize > 0 - }, - async cancel (reason) { - await iterator.return() - } - }, - 0 - ) -} - -// The chunk should be a FormData instance and contains -// all the required methods. -function isFormDataLike (object) { - return ( - object && - typeof object === 'object' && - typeof object.append === 'function' && - typeof object.delete === 'function' && - typeof object.get === 'function' && - typeof object.getAll === 'function' && - typeof object.has === 'function' && - typeof object.set === 'function' && - object[Symbol.toStringTag] === 'FormData' - ) -} - -function throwIfAborted (signal) { - if (!signal) { return } - if (typeof signal.throwIfAborted === 'function') { - signal.throwIfAborted() - } else { - if (signal.aborted) { - // DOMException not available < v17.0.0 - const err = new Error('The operation was aborted') - err.name = 'AbortError' - throw err - } - } -} - -function addAbortListener (signal, listener) { - if ('addEventListener' in signal) { - signal.addEventListener('abort', listener, { once: true }) - return () => signal.removeEventListener('abort', listener) - } - signal.addListener('abort', listener) - return () => signal.removeListener('abort', listener) -} - -const hasToWellFormed = !!String.prototype.toWellFormed - -/** - * @param {string} val - */ -function toUSVString (val) { - if (hasToWellFormed) { - return `${val}`.toWellFormed() - } else if (nodeUtil.toUSVString) { - return nodeUtil.toUSVString(val) - } - - return `${val}` -} - -// Parsed accordingly to RFC 9110 -// https://www.rfc-editor.org/rfc/rfc9110#field.content-range -function parseRangeHeader (range) { - if (range == null || range === '') return { start: 0, end: null, size: null } - - const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null - return m - ? { - start: parseInt(m[1]), - end: m[2] ? parseInt(m[2]) : null, - size: m[3] ? parseInt(m[3]) : null - } - : null -} - -const kEnumerableProperty = Object.create(null) -kEnumerableProperty.enumerable = true - -module.exports = { - kEnumerableProperty, - nop, - isDisturbed, - isErrored, - isReadable, - toUSVString, - isReadableAborted, - isBlobLike, - parseOrigin, - parseURL, - getServerName, - isStream, - isIterable, - isAsyncIterable, - isDestroyed, - headerNameToString, - parseRawHeaders, - parseHeaders, - parseKeepAliveTimeout, - destroy, - bodyLength, - deepClone, - ReadableStreamFrom, - isBuffer, - validateHandler, - getSocketInfo, - isFormDataLike, - buildURL, - throwIfAborted, - addAbortListener, - parseRangeHeader, - nodeMajor, - nodeMinor, - nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), - safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -} - - -/***/ }), - -/***/ 1: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Dispatcher = __nccwpck_require__(992) -const { - ClientDestroyedError, - ClientClosedError, - InvalidArgumentError -} = __nccwpck_require__(8707) -const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443) - -const kDestroyed = Symbol('destroyed') -const kClosed = Symbol('closed') -const kOnDestroyed = Symbol('onDestroyed') -const kOnClosed = Symbol('onClosed') -const kInterceptedDispatch = Symbol('Intercepted Dispatch') - -class DispatcherBase extends Dispatcher { - constructor () { - super() - - this[kDestroyed] = false - this[kOnDestroyed] = null - this[kClosed] = false - this[kOnClosed] = [] - } - - get destroyed () { - return this[kDestroyed] - } - - get closed () { - return this[kClosed] - } - - get interceptors () { - return this[kInterceptors] - } - - set interceptors (newInterceptors) { - if (newInterceptors) { - for (let i = newInterceptors.length - 1; i >= 0; i--) { - const interceptor = this[kInterceptors][i] - if (typeof interceptor !== 'function') { - throw new InvalidArgumentError('interceptor must be an function') - } - } - } - - this[kInterceptors] = newInterceptors - } - - close (callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - this.close((err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (this[kDestroyed]) { - queueMicrotask(() => callback(new ClientDestroyedError(), null)) - return - } - - if (this[kClosed]) { - if (this[kOnClosed]) { - this[kOnClosed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } - - this[kClosed] = true - this[kOnClosed].push(callback) - - const onClosed = () => { - const callbacks = this[kOnClosed] - this[kOnClosed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } - - // Should not error. - this[kClose]() - .then(() => this.destroy()) - .then(() => { - queueMicrotask(onClosed) - }) - } - - destroy (err, callback) { - if (typeof err === 'function') { - callback = err - err = null - } - - if (callback === undefined) { - return new Promise((resolve, reject) => { - this.destroy(err, (err, data) => { - return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) - }) - }) - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (this[kDestroyed]) { - if (this[kOnDestroyed]) { - this[kOnDestroyed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } - - if (!err) { - err = new ClientDestroyedError() - } - - this[kDestroyed] = true - this[kOnDestroyed] = this[kOnDestroyed] || [] - this[kOnDestroyed].push(callback) - - const onDestroyed = () => { - const callbacks = this[kOnDestroyed] - this[kOnDestroyed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } - - // Should not error. - this[kDestroy](err).then(() => { - queueMicrotask(onDestroyed) - }) - } - - [kInterceptedDispatch] (opts, handler) { - if (!this[kInterceptors] || this[kInterceptors].length === 0) { - this[kInterceptedDispatch] = this[kDispatch] - return this[kDispatch](opts, handler) - } - - let dispatch = this[kDispatch].bind(this) - for (let i = this[kInterceptors].length - 1; i >= 0; i--) { - dispatch = this[kInterceptors][i](dispatch) - } - this[kInterceptedDispatch] = dispatch - return dispatch(opts, handler) - } - - dispatch (opts, handler) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } - - try { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('opts must be an object.') - } - - if (this[kDestroyed] || this[kOnDestroyed]) { - throw new ClientDestroyedError() - } - - if (this[kClosed]) { - throw new ClientClosedError() - } - - return this[kInterceptedDispatch](opts, handler) - } catch (err) { - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } - - handler.onError(err) - - return false - } - } -} - -module.exports = DispatcherBase - - -/***/ }), - -/***/ 992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const EventEmitter = __nccwpck_require__(4434) - -class Dispatcher extends EventEmitter { - dispatch () { - throw new Error('not implemented') - } - - close () { - throw new Error('not implemented') - } - - destroy () { - throw new Error('not implemented') - } -} - -module.exports = Dispatcher - - -/***/ }), - -/***/ 8923: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Busboy = __nccwpck_require__(9581) -const util = __nccwpck_require__(3440) -const { - ReadableStreamFrom, - isBlobLike, - isReadableStreamLike, - readableStreamClose, - createDeferredPromise, - fullyReadBody -} = __nccwpck_require__(5523) -const { FormData } = __nccwpck_require__(3073) -const { kState } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { DOMException, structuredClone } = __nccwpck_require__(7326) -const { Blob, File: NativeFile } = __nccwpck_require__(181) -const { kBodyUsed } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { isErrored } = __nccwpck_require__(3440) -const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253) -const { File: UndiciFile } = __nccwpck_require__(3041) -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) - -let random -try { - const crypto = __nccwpck_require__(7598) - random = (max) => crypto.randomInt(0, max) -} catch { - random = (max) => Math.floor(Math.random(max)) -} - -let ReadableStream = globalThis.ReadableStream - -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile -const textEncoder = new TextEncoder() -const textDecoder = new TextDecoder() - -// https://fetch.spec.whatwg.org/#concept-bodyinit-extract -function extractBody (object, keepalive = false) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - // 1. Let stream be null. - let stream = null - - // 2. If object is a ReadableStream object, then set stream to object. - if (object instanceof ReadableStream) { - stream = object - } else if (isBlobLike(object)) { - // 3. Otherwise, if object is a Blob object, set stream to the - // result of running object’s get stream. - stream = object.stream() - } else { - // 4. Otherwise, set stream to a new ReadableStream object, and set - // up stream. - stream = new ReadableStream({ - async pull (controller) { - controller.enqueue( - typeof source === 'string' ? textEncoder.encode(source) : source - ) - queueMicrotask(() => readableStreamClose(controller)) - }, - start () {}, - type: undefined - }) - } - - // 5. Assert: stream is a ReadableStream object. - assert(isReadableStreamLike(stream)) - - // 6. Let action be null. - let action = null - - // 7. Let source be null. - let source = null - - // 8. Let length be null. - let length = null - - // 9. Let type be null. - let type = null - - // 10. Switch on object: - if (typeof object === 'string') { - // Set source to the UTF-8 encoding of object. - // Note: setting source to a Uint8Array here breaks some mocking assumptions. - source = object - - // Set type to `text/plain;charset=UTF-8`. - type = 'text/plain;charset=UTF-8' - } else if (object instanceof URLSearchParams) { - // URLSearchParams - - // spec says to run application/x-www-form-urlencoded on body.list - // this is implemented in Node.js as apart of an URLSearchParams instance toString method - // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 - // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 - - // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. - source = object.toString() - - // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. - type = 'application/x-www-form-urlencoded;charset=UTF-8' - } else if (isArrayBuffer(object)) { - // BufferSource/ArrayBuffer - - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.slice()) - } else if (ArrayBuffer.isView(object)) { - // BufferSource/ArrayBufferView - - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) - } else if (util.isFormDataLike(object)) { - const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` - const prefix = `--${boundary}\r\nContent-Disposition: form-data` - - /*! formdata-polyfill. MIT License. Jimmy Wärting */ - const escape = (str) => - str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') - const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') - - // Set action to this step: run the multipart/form-data - // encoding algorithm, with object’s entry list and UTF-8. - // - This ensures that the body is immutable and can't be changed afterwords - // - That the content-length is calculated in advance. - // - And that all parts are pre-encoded and ready to be sent. - - const blobParts = [] - const rn = new Uint8Array([13, 10]) // '\r\n' - length = 0 - let hasUnknownSizeValue = false - - for (const [name, value] of object) { - if (typeof value === 'string') { - const chunk = textEncoder.encode(prefix + - `; name="${escape(normalizeLinefeeds(name))}"` + - `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) - blobParts.push(chunk) - length += chunk.byteLength - } else { - const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + - (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + - `Content-Type: ${ - value.type || 'application/octet-stream' - }\r\n\r\n`) - blobParts.push(chunk, value, rn) - if (typeof value.size === 'number') { - length += chunk.byteLength + value.size + rn.byteLength - } else { - hasUnknownSizeValue = true - } - } - } - - const chunk = textEncoder.encode(`--${boundary}--`) - blobParts.push(chunk) - length += chunk.byteLength - if (hasUnknownSizeValue) { - length = null - } - - // Set source to object. - source = object - - action = async function * () { - for (const part of blobParts) { - if (part.stream) { - yield * part.stream() - } else { - yield part - } - } - } - - // Set type to `multipart/form-data; boundary=`, - // followed by the multipart/form-data boundary string generated - // by the multipart/form-data encoding algorithm. - type = 'multipart/form-data; boundary=' + boundary - } else if (isBlobLike(object)) { - // Blob - - // Set source to object. - source = object - - // Set length to object’s size. - length = object.size - - // If object’s type attribute is not the empty byte sequence, set - // type to its value. - if (object.type) { - type = object.type - } - } else if (typeof object[Symbol.asyncIterator] === 'function') { - // If keepalive is true, then throw a TypeError. - if (keepalive) { - throw new TypeError('keepalive') - } - - // If object is disturbed or locked, then throw a TypeError. - if (util.isDisturbed(object) || object.locked) { - throw new TypeError( - 'Response body object should not be disturbed or locked' - ) - } - - stream = - object instanceof ReadableStream ? object : ReadableStreamFrom(object) - } - - // 11. If source is a byte sequence, then set action to a - // step that returns source and length to source’s length. - if (typeof source === 'string' || util.isBuffer(source)) { - length = Buffer.byteLength(source) - } - - // 12. If action is non-null, then run these steps in in parallel: - if (action != null) { - // Run action. - let iterator - stream = new ReadableStream({ - async start () { - iterator = action(object)[Symbol.asyncIterator]() - }, - async pull (controller) { - const { value, done } = await iterator.next() - if (done) { - // When running action is done, close stream. - queueMicrotask(() => { - controller.close() - }) - } else { - // Whenever one or more bytes are available and stream is not errored, - // enqueue a Uint8Array wrapping an ArrayBuffer containing the available - // bytes into stream. - if (!isErrored(stream)) { - controller.enqueue(new Uint8Array(value)) - } - } - return controller.desiredSize > 0 - }, - async cancel (reason) { - await iterator.return() - }, - type: undefined - }) - } - - // 13. Let body be a body whose stream is stream, source is source, - // and length is length. - const body = { stream, source, length } - - // 14. Return (body, type). - return [body, type] -} - -// https://fetch.spec.whatwg.org/#bodyinit-safely-extract -function safelyExtractBody (object, keepalive = false) { - if (!ReadableStream) { - // istanbul ignore next - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - // To safely extract a body and a `Content-Type` value from - // a byte sequence or BodyInit object object, run these steps: - - // 1. If object is a ReadableStream object, then: - if (object instanceof ReadableStream) { - // Assert: object is neither disturbed nor locked. - // istanbul ignore next - assert(!util.isDisturbed(object), 'The body has already been consumed.') - // istanbul ignore next - assert(!object.locked, 'The stream is locked.') - } - - // 2. Return the results of extracting object. - return extractBody(object, keepalive) -} - -function cloneBody (body) { - // To clone a body body, run these steps: - - // https://fetch.spec.whatwg.org/#concept-body-clone - - // 1. Let « out1, out2 » be the result of teeing body’s stream. - const [out1, out2] = body.stream.tee() - const out2Clone = structuredClone(out2, { transfer: [out2] }) - // This, for whatever reasons, unrefs out2Clone which allows - // the process to exit by itself. - const [, finalClone] = out2Clone.tee() - - // 2. Set body’s stream to out1. - body.stream = out1 - - // 3. Return a body whose stream is out2 and other members are copied from body. - return { - stream: finalClone, - length: body.length, - source: body.source - } -} - -async function * consumeBody (body) { - if (body) { - if (isUint8Array(body)) { - yield body - } else { - const stream = body.stream - - if (util.isDisturbed(stream)) { - throw new TypeError('The body has already been consumed.') - } - - if (stream.locked) { - throw new TypeError('The stream is locked.') - } - - // Compat. - stream[kBodyUsed] = true - - yield * stream - } - } -} - -function throwIfAborted (state) { - if (state.aborted) { - throw new DOMException('The operation was aborted.', 'AbortError') - } -} - -function bodyMixinMethods (instance) { - const methods = { - blob () { - // The blob() method steps are to return the result of - // running consume body with this and the following step - // given a byte sequence bytes: return a Blob whose - // contents are bytes and whose type attribute is this’s - // MIME type. - return specConsumeBody(this, (bytes) => { - let mimeType = bodyMimeType(this) - - if (mimeType === 'failure') { - mimeType = '' - } else if (mimeType) { - mimeType = serializeAMimeType(mimeType) - } - - // Return a Blob whose contents are bytes and type attribute - // is mimeType. - return new Blob([bytes], { type: mimeType }) - }, instance) - }, - - arrayBuffer () { - // The arrayBuffer() method steps are to return the result - // of running consume body with this and the following step - // given a byte sequence bytes: return a new ArrayBuffer - // whose contents are bytes. - return specConsumeBody(this, (bytes) => { - return new Uint8Array(bytes).buffer - }, instance) - }, - - text () { - // The text() method steps are to return the result of running - // consume body with this and UTF-8 decode. - return specConsumeBody(this, utf8DecodeBytes, instance) - }, - - json () { - // The json() method steps are to return the result of running - // consume body with this and parse JSON from bytes. - return specConsumeBody(this, parseJSONFromBytes, instance) - }, - - async formData () { - webidl.brandCheck(this, instance) - - throwIfAborted(this[kState]) - - const contentType = this.headers.get('Content-Type') - - // If mimeType’s essence is "multipart/form-data", then: - if (/multipart\/form-data/.test(contentType)) { - const headers = {} - for (const [key, value] of this.headers) headers[key.toLowerCase()] = value - - const responseFormData = new FormData() - - let busboy - - try { - busboy = new Busboy({ - headers, - preservePath: true - }) - } catch (err) { - throw new DOMException(`${err}`, 'AbortError') - } - - busboy.on('field', (name, value) => { - responseFormData.append(name, value) - }) - busboy.on('file', (name, value, filename, encoding, mimeType) => { - const chunks = [] - - if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { - let base64chunk = '' - - value.on('data', (chunk) => { - base64chunk += chunk.toString().replace(/[\r\n]/gm, '') - - const end = base64chunk.length - base64chunk.length % 4 - chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) - - base64chunk = base64chunk.slice(end) - }) - value.on('end', () => { - chunks.push(Buffer.from(base64chunk, 'base64')) - responseFormData.append(name, new File(chunks, filename, { type: mimeType })) - }) - } else { - value.on('data', (chunk) => { - chunks.push(chunk) - }) - value.on('end', () => { - responseFormData.append(name, new File(chunks, filename, { type: mimeType })) - }) - } - }) - - const busboyResolve = new Promise((resolve, reject) => { - busboy.on('finish', resolve) - busboy.on('error', (err) => reject(new TypeError(err))) - }) - - if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) - busboy.end() - await busboyResolve - - return responseFormData - } else if (/application\/x-www-form-urlencoded/.test(contentType)) { - // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: - - // 1. Let entries be the result of parsing bytes. - let entries - try { - let text = '' - // application/x-www-form-urlencoded parser will keep the BOM. - // https://url.spec.whatwg.org/#concept-urlencoded-parser - // Note that streaming decoder is stateful and cannot be reused - const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) - - for await (const chunk of consumeBody(this[kState].body)) { - if (!isUint8Array(chunk)) { - throw new TypeError('Expected Uint8Array chunk') - } - text += streamingDecoder.decode(chunk, { stream: true }) - } - text += streamingDecoder.decode() - entries = new URLSearchParams(text) - } catch (err) { - // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. - // 2. If entries is failure, then throw a TypeError. - throw Object.assign(new TypeError(), { cause: err }) - } - - // 3. Return a new FormData object whose entries are entries. - const formData = new FormData() - for (const [name, value] of entries) { - formData.append(name, value) - } - return formData - } else { - // Wait a tick before checking if the request has been aborted. - // Otherwise, a TypeError can be thrown when an AbortError should. - await Promise.resolve() - - throwIfAborted(this[kState]) - - // Otherwise, throw a TypeError. - throw webidl.errors.exception({ - header: `${instance.name}.formData`, - message: 'Could not parse content as FormData.' - }) - } - } - } - - return methods -} - -function mixinBody (prototype) { - Object.assign(prototype.prototype, bodyMixinMethods(prototype)) -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-body-consume-body - * @param {Response|Request} object - * @param {(value: unknown) => unknown} convertBytesToJSValue - * @param {Response|Request} instance - */ -async function specConsumeBody (object, convertBytesToJSValue, instance) { - webidl.brandCheck(object, instance) - - throwIfAborted(object[kState]) - - // 1. If object is unusable, then return a promise rejected - // with a TypeError. - if (bodyUnusable(object[kState].body)) { - throw new TypeError('Body is unusable') - } - - // 2. Let promise be a new promise. - const promise = createDeferredPromise() - - // 3. Let errorSteps given error be to reject promise with error. - const errorSteps = (error) => promise.reject(error) - - // 4. Let successSteps given a byte sequence data be to resolve - // promise with the result of running convertBytesToJSValue - // with data. If that threw an exception, then run errorSteps - // with that exception. - const successSteps = (data) => { - try { - promise.resolve(convertBytesToJSValue(data)) - } catch (e) { - errorSteps(e) - } - } - - // 5. If object’s body is null, then run successSteps with an - // empty byte sequence. - if (object[kState].body == null) { - successSteps(new Uint8Array()) - return promise.promise - } - - // 6. Otherwise, fully read object’s body given successSteps, - // errorSteps, and object’s relevant global object. - await fullyReadBody(object[kState].body, successSteps, errorSteps) - - // 7. Return promise. - return promise.promise -} - -// https://fetch.spec.whatwg.org/#body-unusable -function bodyUnusable (body) { - // An object including the Body interface mixin is - // said to be unusable if its body is non-null and - // its body’s stream is disturbed or locked. - return body != null && (body.stream.locked || util.isDisturbed(body.stream)) -} - -/** - * @see https://encoding.spec.whatwg.org/#utf-8-decode - * @param {Buffer} buffer - */ -function utf8DecodeBytes (buffer) { - if (buffer.length === 0) { - return '' - } - - // 1. Let buffer be the result of peeking three bytes from - // ioQueue, converted to a byte sequence. - - // 2. If buffer is 0xEF 0xBB 0xBF, then read three - // bytes from ioQueue. (Do nothing with those bytes.) - if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { - buffer = buffer.subarray(3) - } - - // 3. Process a queue with an instance of UTF-8’s - // decoder, ioQueue, output, and "replacement". - const output = textDecoder.decode(buffer) - - // 4. Return output. - return output -} - -/** - * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value - * @param {Uint8Array} bytes - */ -function parseJSONFromBytes (bytes) { - return JSON.parse(utf8DecodeBytes(bytes)) -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-body-mime-type - * @param {import('./response').Response|import('./request').Request} object - */ -function bodyMimeType (object) { - const { headersList } = object[kState] - const contentType = headersList.get('content-type') - - if (contentType === null) { - return 'failure' - } - - return parseMIMEType(contentType) -} - -module.exports = { - extractBody, - safelyExtractBody, - cloneBody, - mixinBody -} - - -/***/ }), - -/***/ 7326: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167) - -const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] -const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) - -const nullBodyStatus = [101, 204, 205, 304] - -const redirectStatus = [301, 302, 303, 307, 308] -const redirectStatusSet = new Set(redirectStatus) - -// https://fetch.spec.whatwg.org/#block-bad-port -const badPorts = [ - '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', - '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', - '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', - '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', - '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', - '10080' -] - -const badPortsSet = new Set(badPorts) - -// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies -const referrerPolicy = [ - '', - 'no-referrer', - 'no-referrer-when-downgrade', - 'same-origin', - 'origin', - 'strict-origin', - 'origin-when-cross-origin', - 'strict-origin-when-cross-origin', - 'unsafe-url' -] -const referrerPolicySet = new Set(referrerPolicy) - -const requestRedirect = ['follow', 'manual', 'error'] - -const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -const safeMethodsSet = new Set(safeMethods) - -const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] - -const requestCredentials = ['omit', 'same-origin', 'include'] - -const requestCache = [ - 'default', - 'no-store', - 'reload', - 'no-cache', - 'force-cache', - 'only-if-cached' -] - -// https://fetch.spec.whatwg.org/#request-body-header-name -const requestBodyHeader = [ - 'content-encoding', - 'content-language', - 'content-location', - 'content-type', - // See https://github.com/nodejs/undici/issues/2021 - // 'Content-Length' is a forbidden header name, which is typically - // removed in the Headers implementation. However, undici doesn't - // filter out headers, so we add it here. - 'content-length' -] - -// https://fetch.spec.whatwg.org/#enumdef-requestduplex -const requestDuplex = [ - 'half' -] - -// http://fetch.spec.whatwg.org/#forbidden-method -const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] -const forbiddenMethodsSet = new Set(forbiddenMethods) - -const subresource = [ - 'audio', - 'audioworklet', - 'font', - 'image', - 'manifest', - 'paintworklet', - 'script', - 'style', - 'track', - 'video', - 'xslt', - '' -] -const subresourceSet = new Set(subresource) - -/** @type {globalThis['DOMException']} */ -const DOMException = globalThis.DOMException ?? (() => { - // DOMException was only made a global in Node v17.0.0, - // but fetch supports >= v16.8. - try { - atob('~') - } catch (err) { - return Object.getPrototypeOf(err).constructor - } -})() - -let channel - -/** @type {globalThis['structuredClone']} */ -const structuredClone = - globalThis.structuredClone ?? - // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js - // structuredClone was added in v17.0.0, but fetch supports v16.8 - function structuredClone (value, options = undefined) { - if (arguments.length === 0) { - throw new TypeError('missing argument') - } - - if (!channel) { - channel = new MessageChannel() - } - channel.port1.unref() - channel.port2.unref() - channel.port1.postMessage(value, options?.transfer) - return receiveMessageOnPort(channel.port2).message - } - -module.exports = { - DOMException, - structuredClone, - subresource, - forbiddenMethods, - requestBodyHeader, - referrerPolicy, - requestRedirect, - requestMode, - requestCredentials, - requestCache, - redirectStatus, - corsSafeListedMethods, - nullBodyStatus, - safeMethods, - badPorts, - requestDuplex, - subresourceSet, - badPortsSet, - redirectStatusSet, - corsSafeListedMethodsSet, - safeMethodsSet, - forbiddenMethodsSet, - referrerPolicySet -} - - -/***/ }), - -/***/ 4322: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(2613) -const { atob } = __nccwpck_require__(181) -const { isomorphicDecode } = __nccwpck_require__(5523) - -const encoder = new TextEncoder() - -/** - * @see https://mimesniff.spec.whatwg.org/#http-token-code-point - */ -const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ -const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line -/** - * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point - */ -const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line - -// https://fetch.spec.whatwg.org/#data-url-processor -/** @param {URL} dataURL */ -function dataURLProcessor (dataURL) { - // 1. Assert: dataURL’s scheme is "data". - assert(dataURL.protocol === 'data:') - - // 2. Let input be the result of running the URL - // serializer on dataURL with exclude fragment - // set to true. - let input = URLSerializer(dataURL, true) - - // 3. Remove the leading "data:" string from input. - input = input.slice(5) - - // 4. Let position point at the start of input. - const position = { position: 0 } - - // 5. Let mimeType be the result of collecting a - // sequence of code points that are not equal - // to U+002C (,), given position. - let mimeType = collectASequenceOfCodePointsFast( - ',', - input, - position - ) - - // 6. Strip leading and trailing ASCII whitespace - // from mimeType. - // Undici implementation note: we need to store the - // length because if the mimetype has spaces removed, - // the wrong amount will be sliced from the input in - // step #9 - const mimeTypeLength = mimeType.length - mimeType = removeASCIIWhitespace(mimeType, true, true) - - // 7. If position is past the end of input, then - // return failure - if (position.position >= input.length) { - return 'failure' - } - - // 8. Advance position by 1. - position.position++ - - // 9. Let encodedBody be the remainder of input. - const encodedBody = input.slice(mimeTypeLength + 1) - - // 10. Let body be the percent-decoding of encodedBody. - let body = stringPercentDecode(encodedBody) - - // 11. If mimeType ends with U+003B (;), followed by - // zero or more U+0020 SPACE, followed by an ASCII - // case-insensitive match for "base64", then: - if (/;(\u0020){0,}base64$/i.test(mimeType)) { - // 1. Let stringBody be the isomorphic decode of body. - const stringBody = isomorphicDecode(body) - - // 2. Set body to the forgiving-base64 decode of - // stringBody. - body = forgivingBase64(stringBody) - - // 3. If body is failure, then return failure. - if (body === 'failure') { - return 'failure' - } - - // 4. Remove the last 6 code points from mimeType. - mimeType = mimeType.slice(0, -6) - - // 5. Remove trailing U+0020 SPACE code points from mimeType, - // if any. - mimeType = mimeType.replace(/(\u0020)+$/, '') - - // 6. Remove the last U+003B (;) code point from mimeType. - mimeType = mimeType.slice(0, -1) - } - - // 12. If mimeType starts with U+003B (;), then prepend - // "text/plain" to mimeType. - if (mimeType.startsWith(';')) { - mimeType = 'text/plain' + mimeType - } - - // 13. Let mimeTypeRecord be the result of parsing - // mimeType. - let mimeTypeRecord = parseMIMEType(mimeType) - - // 14. If mimeTypeRecord is failure, then set - // mimeTypeRecord to text/plain;charset=US-ASCII. - if (mimeTypeRecord === 'failure') { - mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') - } - - // 15. Return a new data: URL struct whose MIME - // type is mimeTypeRecord and body is body. - // https://fetch.spec.whatwg.org/#data-url-struct - return { mimeType: mimeTypeRecord, body } -} - -// https://url.spec.whatwg.org/#concept-url-serializer -/** - * @param {URL} url - * @param {boolean} excludeFragment - */ -function URLSerializer (url, excludeFragment = false) { - if (!excludeFragment) { - return url.href - } - - const href = url.href - const hashLength = url.hash.length - - return hashLength === 0 ? href : href.substring(0, href.length - hashLength) -} - -// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points -/** - * @param {(char: string) => boolean} condition - * @param {string} input - * @param {{ position: number }} position - */ -function collectASequenceOfCodePoints (condition, input, position) { - // 1. Let result be the empty string. - let result = '' - - // 2. While position doesn’t point past the end of input and the - // code point at position within input meets the condition condition: - while (position.position < input.length && condition(input[position.position])) { - // 1. Append that code point to the end of result. - result += input[position.position] - - // 2. Advance position by 1. - position.position++ - } - - // 3. Return result. - return result -} - -/** - * A faster collectASequenceOfCodePoints that only works when comparing a single character. - * @param {string} char - * @param {string} input - * @param {{ position: number }} position - */ -function collectASequenceOfCodePointsFast (char, input, position) { - const idx = input.indexOf(char, position.position) - const start = position.position - - if (idx === -1) { - position.position = input.length - return input.slice(start) - } - - position.position = idx - return input.slice(start, position.position) -} - -// https://url.spec.whatwg.org/#string-percent-decode -/** @param {string} input */ -function stringPercentDecode (input) { - // 1. Let bytes be the UTF-8 encoding of input. - const bytes = encoder.encode(input) - - // 2. Return the percent-decoding of bytes. - return percentDecode(bytes) -} - -// https://url.spec.whatwg.org/#percent-decode -/** @param {Uint8Array} input */ -function percentDecode (input) { - // 1. Let output be an empty byte sequence. - /** @type {number[]} */ - const output = [] - - // 2. For each byte byte in input: - for (let i = 0; i < input.length; i++) { - const byte = input[i] - - // 1. If byte is not 0x25 (%), then append byte to output. - if (byte !== 0x25) { - output.push(byte) - - // 2. Otherwise, if byte is 0x25 (%) and the next two bytes - // after byte in input are not in the ranges - // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), - // and 0x61 (a) to 0x66 (f), all inclusive, append byte - // to output. - } else if ( - byte === 0x25 && - !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) - ) { - output.push(0x25) - - // 3. Otherwise: - } else { - // 1. Let bytePoint be the two bytes after byte in input, - // decoded, and then interpreted as hexadecimal number. - const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) - const bytePoint = Number.parseInt(nextTwoBytes, 16) - - // 2. Append a byte whose value is bytePoint to output. - output.push(bytePoint) - - // 3. Skip the next two bytes in input. - i += 2 - } - } - - // 3. Return output. - return Uint8Array.from(output) -} - -// https://mimesniff.spec.whatwg.org/#parse-a-mime-type -/** @param {string} input */ -function parseMIMEType (input) { - // 1. Remove any leading and trailing HTTP whitespace - // from input. - input = removeHTTPWhitespace(input, true, true) - - // 2. Let position be a position variable for input, - // initially pointing at the start of input. - const position = { position: 0 } - - // 3. Let type be the result of collecting a sequence - // of code points that are not U+002F (/) from - // input, given position. - const type = collectASequenceOfCodePointsFast( - '/', - input, - position - ) - - // 4. If type is the empty string or does not solely - // contain HTTP token code points, then return failure. - // https://mimesniff.spec.whatwg.org/#http-token-code-point - if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { - return 'failure' - } - - // 5. If position is past the end of input, then return - // failure - if (position.position > input.length) { - return 'failure' - } - - // 6. Advance position by 1. (This skips past U+002F (/).) - position.position++ - - // 7. Let subtype be the result of collecting a sequence of - // code points that are not U+003B (;) from input, given - // position. - let subtype = collectASequenceOfCodePointsFast( - ';', - input, - position - ) - - // 8. Remove any trailing HTTP whitespace from subtype. - subtype = removeHTTPWhitespace(subtype, false, true) - - // 9. If subtype is the empty string or does not solely - // contain HTTP token code points, then return failure. - if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { - return 'failure' - } - - const typeLowercase = type.toLowerCase() - const subtypeLowercase = subtype.toLowerCase() - - // 10. Let mimeType be a new MIME type record whose type - // is type, in ASCII lowercase, and subtype is subtype, - // in ASCII lowercase. - // https://mimesniff.spec.whatwg.org/#mime-type - const mimeType = { - type: typeLowercase, - subtype: subtypeLowercase, - /** @type {Map} */ - parameters: new Map(), - // https://mimesniff.spec.whatwg.org/#mime-type-essence - essence: `${typeLowercase}/${subtypeLowercase}` - } - - // 11. While position is not past the end of input: - while (position.position < input.length) { - // 1. Advance position by 1. (This skips past U+003B (;).) - position.position++ - - // 2. Collect a sequence of code points that are HTTP - // whitespace from input given position. - collectASequenceOfCodePoints( - // https://fetch.spec.whatwg.org/#http-whitespace - char => HTTP_WHITESPACE_REGEX.test(char), - input, - position - ) - - // 3. Let parameterName be the result of collecting a - // sequence of code points that are not U+003B (;) - // or U+003D (=) from input, given position. - let parameterName = collectASequenceOfCodePoints( - (char) => char !== ';' && char !== '=', - input, - position - ) - - // 4. Set parameterName to parameterName, in ASCII - // lowercase. - parameterName = parameterName.toLowerCase() - - // 5. If position is not past the end of input, then: - if (position.position < input.length) { - // 1. If the code point at position within input is - // U+003B (;), then continue. - if (input[position.position] === ';') { - continue - } - - // 2. Advance position by 1. (This skips past U+003D (=).) - position.position++ - } - - // 6. If position is past the end of input, then break. - if (position.position > input.length) { - break - } - - // 7. Let parameterValue be null. - let parameterValue = null - - // 8. If the code point at position within input is - // U+0022 ("), then: - if (input[position.position] === '"') { - // 1. Set parameterValue to the result of collecting - // an HTTP quoted string from input, given position - // and the extract-value flag. - parameterValue = collectAnHTTPQuotedString(input, position, true) - - // 2. Collect a sequence of code points that are not - // U+003B (;) from input, given position. - collectASequenceOfCodePointsFast( - ';', - input, - position - ) - - // 9. Otherwise: - } else { - // 1. Set parameterValue to the result of collecting - // a sequence of code points that are not U+003B (;) - // from input, given position. - parameterValue = collectASequenceOfCodePointsFast( - ';', - input, - position - ) - - // 2. Remove any trailing HTTP whitespace from parameterValue. - parameterValue = removeHTTPWhitespace(parameterValue, false, true) - - // 3. If parameterValue is the empty string, then continue. - if (parameterValue.length === 0) { - continue - } - } - - // 10. If all of the following are true - // - parameterName is not the empty string - // - parameterName solely contains HTTP token code points - // - parameterValue solely contains HTTP quoted-string token code points - // - mimeType’s parameters[parameterName] does not exist - // then set mimeType’s parameters[parameterName] to parameterValue. - if ( - parameterName.length !== 0 && - HTTP_TOKEN_CODEPOINTS.test(parameterName) && - (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && - !mimeType.parameters.has(parameterName) - ) { - mimeType.parameters.set(parameterName, parameterValue) - } - } - - // 12. Return mimeType. - return mimeType -} - -// https://infra.spec.whatwg.org/#forgiving-base64-decode -/** @param {string} data */ -function forgivingBase64 (data) { - // 1. Remove all ASCII whitespace from data. - data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line - - // 2. If data’s code point length divides by 4 leaving - // no remainder, then: - if (data.length % 4 === 0) { - // 1. If data ends with one or two U+003D (=) code points, - // then remove them from data. - data = data.replace(/=?=$/, '') - } - - // 3. If data’s code point length divides by 4 leaving - // a remainder of 1, then return failure. - if (data.length % 4 === 1) { - return 'failure' - } - - // 4. If data contains a code point that is not one of - // U+002B (+) - // U+002F (/) - // ASCII alphanumeric - // then return failure. - if (/[^+/0-9A-Za-z]/.test(data)) { - return 'failure' - } - - const binary = atob(data) - const bytes = new Uint8Array(binary.length) - - for (let byte = 0; byte < binary.length; byte++) { - bytes[byte] = binary.charCodeAt(byte) - } - - return bytes -} - -// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string -// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string -/** - * @param {string} input - * @param {{ position: number }} position - * @param {boolean?} extractValue - */ -function collectAnHTTPQuotedString (input, position, extractValue) { - // 1. Let positionStart be position. - const positionStart = position.position - - // 2. Let value be the empty string. - let value = '' - - // 3. Assert: the code point at position within input - // is U+0022 ("). - assert(input[position.position] === '"') - - // 4. Advance position by 1. - position.position++ - - // 5. While true: - while (true) { - // 1. Append the result of collecting a sequence of code points - // that are not U+0022 (") or U+005C (\) from input, given - // position, to value. - value += collectASequenceOfCodePoints( - (char) => char !== '"' && char !== '\\', - input, - position - ) - - // 2. If position is past the end of input, then break. - if (position.position >= input.length) { - break - } - - // 3. Let quoteOrBackslash be the code point at position within - // input. - const quoteOrBackslash = input[position.position] - - // 4. Advance position by 1. - position.position++ - - // 5. If quoteOrBackslash is U+005C (\), then: - if (quoteOrBackslash === '\\') { - // 1. If position is past the end of input, then append - // U+005C (\) to value and break. - if (position.position >= input.length) { - value += '\\' - break - } - - // 2. Append the code point at position within input to value. - value += input[position.position] - - // 3. Advance position by 1. - position.position++ - - // 6. Otherwise: - } else { - // 1. Assert: quoteOrBackslash is U+0022 ("). - assert(quoteOrBackslash === '"') - - // 2. Break. - break - } - } - - // 6. If the extract-value flag is set, then return value. - if (extractValue) { - return value - } - - // 7. Return the code points from positionStart to position, - // inclusive, within input. - return input.slice(positionStart, position.position) -} - -/** - * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type - */ -function serializeAMimeType (mimeType) { - assert(mimeType !== 'failure') - const { parameters, essence } = mimeType - - // 1. Let serialization be the concatenation of mimeType’s - // type, U+002F (/), and mimeType’s subtype. - let serialization = essence - - // 2. For each name → value of mimeType’s parameters: - for (let [name, value] of parameters.entries()) { - // 1. Append U+003B (;) to serialization. - serialization += ';' - - // 2. Append name to serialization. - serialization += name - - // 3. Append U+003D (=) to serialization. - serialization += '=' - - // 4. If value does not solely contain HTTP token code - // points or value is the empty string, then: - if (!HTTP_TOKEN_CODEPOINTS.test(value)) { - // 1. Precede each occurence of U+0022 (") or - // U+005C (\) in value with U+005C (\). - value = value.replace(/(\\|")/g, '\\$1') - - // 2. Prepend U+0022 (") to value. - value = '"' + value - - // 3. Append U+0022 (") to value. - value += '"' - } - - // 5. Append value to serialization. - serialization += value - } - - // 3. Return serialization. - return serialization -} - -/** - * @see https://fetch.spec.whatwg.org/#http-whitespace - * @param {string} char - */ -function isHTTPWhiteSpace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === ' ' -} - -/** - * @see https://fetch.spec.whatwg.org/#http-whitespace - * @param {string} str - */ -function removeHTTPWhitespace (str, leading = true, trailing = true) { - let lead = 0 - let trail = str.length - 1 - - if (leading) { - for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); - } - - if (trailing) { - for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); - } - - return str.slice(lead, trail + 1) -} - -/** - * @see https://infra.spec.whatwg.org/#ascii-whitespace - * @param {string} char - */ -function isASCIIWhitespace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' -} - -/** - * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace - */ -function removeASCIIWhitespace (str, leading = true, trailing = true) { - let lead = 0 - let trail = str.length - 1 - - if (leading) { - for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); - } - - if (trailing) { - for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); - } - - return str.slice(lead, trail + 1) -} - -module.exports = { - dataURLProcessor, - URLSerializer, - collectASequenceOfCodePoints, - collectASequenceOfCodePointsFast, - stringPercentDecode, - parseMIMEType, - collectAnHTTPQuotedString, - serializeAMimeType -} - - -/***/ }), - -/***/ 3041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Blob, File: NativeFile } = __nccwpck_require__(181) -const { types } = __nccwpck_require__(9023) -const { kState } = __nccwpck_require__(9710) -const { isBlobLike } = __nccwpck_require__(5523) -const { webidl } = __nccwpck_require__(4222) -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const encoder = new TextEncoder() - -class File extends Blob { - constructor (fileBits, fileName, options = {}) { - // The File constructor is invoked with two or three parameters, depending - // on whether the optional dictionary parameter is used. When the File() - // constructor is invoked, user agents must run the following steps: - webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) - - fileBits = webidl.converters['sequence'](fileBits) - fileName = webidl.converters.USVString(fileName) - options = webidl.converters.FilePropertyBag(options) - - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - // Note: Blob handles this for us - - // 2. Let n be the fileName argument to the constructor. - const n = fileName - - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: - - // 1. If the type member is provided and is not the empty string, let t - // be set to the type dictionary member. If t contains any characters - // outside the range U+0020 to U+007E, then set t to the empty string - // and return from these substeps. - // 2. Convert every character in t to ASCII lowercase. - let t = options.type - let d - - // eslint-disable-next-line no-labels - substep: { - if (t) { - t = parseMIMEType(t) - - if (t === 'failure') { - t = '' - // eslint-disable-next-line no-labels - break substep - } - - t = serializeAMimeType(t).toLowerCase() - } - - // 3. If the lastModified member is provided, let d be set to the - // lastModified dictionary member. If it is not provided, set d to the - // current date and time represented as the number of milliseconds since - // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). - d = options.lastModified - } - - // 4. Return a new File object F such that: - // F refers to the bytes byte sequence. - // F.size is set to the number of total bytes in bytes. - // F.name is set to n. - // F.type is set to t. - // F.lastModified is set to d. - - super(processBlobParts(fileBits, options), { type: t }) - this[kState] = { - name: n, - lastModified: d, - type: t - } - } - - get name () { - webidl.brandCheck(this, File) - - return this[kState].name - } - - get lastModified () { - webidl.brandCheck(this, File) - - return this[kState].lastModified - } - - get type () { - webidl.brandCheck(this, File) - - return this[kState].type - } -} - -class FileLike { - constructor (blobLike, fileName, options = {}) { - // TODO: argument idl type check - - // The File constructor is invoked with two or three parameters, depending - // on whether the optional dictionary parameter is used. When the File() - // constructor is invoked, user agents must run the following steps: - - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - - // 2. Let n be the fileName argument to the constructor. - const n = fileName - - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: - - // 1. If the type member is provided and is not the empty string, let t - // be set to the type dictionary member. If t contains any characters - // outside the range U+0020 to U+007E, then set t to the empty string - // and return from these substeps. - // TODO - const t = options.type - - // 2. Convert every character in t to ASCII lowercase. - // TODO - - // 3. If the lastModified member is provided, let d be set to the - // lastModified dictionary member. If it is not provided, set d to the - // current date and time represented as the number of milliseconds since - // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). - const d = options.lastModified ?? Date.now() - - // 4. Return a new File object F such that: - // F refers to the bytes byte sequence. - // F.size is set to the number of total bytes in bytes. - // F.name is set to n. - // F.type is set to t. - // F.lastModified is set to d. - - this[kState] = { - blobLike, - name: n, - type: t, - lastModified: d - } - } - - stream (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.stream(...args) - } - - arrayBuffer (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.arrayBuffer(...args) - } - - slice (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.slice(...args) - } - - text (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.text(...args) - } - - get size () { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.size - } - - get type () { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.type - } - - get name () { - webidl.brandCheck(this, FileLike) - - return this[kState].name - } - - get lastModified () { - webidl.brandCheck(this, FileLike) - - return this[kState].lastModified - } - - get [Symbol.toStringTag] () { - return 'File' - } -} - -Object.defineProperties(File.prototype, { - [Symbol.toStringTag]: { - value: 'File', - configurable: true - }, - name: kEnumerableProperty, - lastModified: kEnumerableProperty -}) - -webidl.converters.Blob = webidl.interfaceConverter(Blob) - -webidl.converters.BlobPart = function (V, opts) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } - - if ( - ArrayBuffer.isView(V) || - types.isAnyArrayBuffer(V) - ) { - return webidl.converters.BufferSource(V, opts) - } - } - - return webidl.converters.USVString(V, opts) -} - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.BlobPart -) - -// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag -webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ - { - key: 'lastModified', - converter: webidl.converters['long long'], - get defaultValue () { - return Date.now() - } - }, - { - key: 'type', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'endings', - converter: (value) => { - value = webidl.converters.DOMString(value) - value = value.toLowerCase() - - if (value !== 'native') { - value = 'transparent' - } - - return value - }, - defaultValue: 'transparent' - } -]) - -/** - * @see https://www.w3.org/TR/FileAPI/#process-blob-parts - * @param {(NodeJS.TypedArray|Blob|string)[]} parts - * @param {{ type: string, endings: string }} options - */ -function processBlobParts (parts, options) { - // 1. Let bytes be an empty sequence of bytes. - /** @type {NodeJS.TypedArray[]} */ - const bytes = [] - - // 2. For each element in parts: - for (const element of parts) { - // 1. If element is a USVString, run the following substeps: - if (typeof element === 'string') { - // 1. Let s be element. - let s = element - - // 2. If the endings member of options is "native", set s - // to the result of converting line endings to native - // of element. - if (options.endings === 'native') { - s = convertLineEndingsNative(s) - } - - // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(encoder.encode(s)) - } else if ( - types.isAnyArrayBuffer(element) || - types.isTypedArray(element) - ) { - // 2. If element is a BufferSource, get a copy of the - // bytes held by the buffer source, and append those - // bytes to bytes. - if (!element.buffer) { // ArrayBuffer - bytes.push(new Uint8Array(element)) - } else { - bytes.push( - new Uint8Array(element.buffer, element.byteOffset, element.byteLength) - ) - } - } else if (isBlobLike(element)) { - // 3. If element is a Blob, append the bytes it represents - // to bytes. - bytes.push(element) - } - } - - // 3. Return bytes. - return bytes -} - -/** - * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native - * @param {string} s - */ -function convertLineEndingsNative (s) { - // 1. Let native line ending be be the code point U+000A LF. - let nativeLineEnding = '\n' - - // 2. If the underlying platform’s conventions are to - // represent newlines as a carriage return and line feed - // sequence, set native line ending to the code point - // U+000D CR followed by the code point U+000A LF. - if (process.platform === 'win32') { - nativeLineEnding = '\r\n' - } - - return s.replace(/\r?\n/g, nativeLineEnding) -} - -// If this function is moved to ./util.js, some tools (such as -// rollup) will warn about circular dependencies. See: -// https://github.com/nodejs/undici/issues/1629 -function isFileLike (object) { - return ( - (NativeFile && object instanceof NativeFile) || - object instanceof File || ( - object && - (typeof object.stream === 'function' || - typeof object.arrayBuffer === 'function') && - object[Symbol.toStringTag] === 'File' - ) - ) -} - -module.exports = { File, FileLike, isFileLike } - - -/***/ }), - -/***/ 3073: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523) -const { kState } = __nccwpck_require__(9710) -const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041) -const { webidl } = __nccwpck_require__(4222) -const { Blob, File: NativeFile } = __nccwpck_require__(181) - -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile - -// https://xhr.spec.whatwg.org/#formdata -class FormData { - constructor (form) { - if (form !== undefined) { - throw webidl.errors.conversionFailed({ - prefix: 'FormData constructor', - argument: 'Argument 1', - types: ['undefined'] - }) - } - - this[kState] = [] - } - - append (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) - - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" - ) - } - - // 1. Let value be value if given; otherwise blobValue. - - name = webidl.converters.USVString(name) - value = isBlobLike(value) - ? webidl.converters.Blob(value, { strict: false }) - : webidl.converters.USVString(value) - filename = arguments.length === 3 - ? webidl.converters.USVString(filename) - : undefined - - // 2. Let entry be the result of creating an entry with - // name, value, and filename if given. - const entry = makeEntry(name, value, filename) - - // 3. Append entry to this’s entry list. - this[kState].push(entry) - } - - delete (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) - - name = webidl.converters.USVString(name) - - // The delete(name) method steps are to remove all entries whose name - // is name from this’s entry list. - this[kState] = this[kState].filter(entry => entry.name !== name) - } - - get (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) - - name = webidl.converters.USVString(name) - - // 1. If there is no entry whose name is name in this’s entry list, - // then return null. - const idx = this[kState].findIndex((entry) => entry.name === name) - if (idx === -1) { - return null - } - - // 2. Return the value of the first entry whose name is name from - // this’s entry list. - return this[kState][idx].value - } - - getAll (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) - - name = webidl.converters.USVString(name) - - // 1. If there is no entry whose name is name in this’s entry list, - // then return the empty list. - // 2. Return the values of all entries whose name is name, in order, - // from this’s entry list. - return this[kState] - .filter((entry) => entry.name === name) - .map((entry) => entry.value) - } - - has (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) - - name = webidl.converters.USVString(name) - - // The has(name) method steps are to return true if there is an entry - // whose name is name in this’s entry list; otherwise false. - return this[kState].findIndex((entry) => entry.name === name) !== -1 - } - - set (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) - - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" - ) - } - - // The set(name, value) and set(name, blobValue, filename) method steps - // are: - - // 1. Let value be value if given; otherwise blobValue. - - name = webidl.converters.USVString(name) - value = isBlobLike(value) - ? webidl.converters.Blob(value, { strict: false }) - : webidl.converters.USVString(value) - filename = arguments.length === 3 - ? toUSVString(filename) - : undefined - - // 2. Let entry be the result of creating an entry with name, value, and - // filename if given. - const entry = makeEntry(name, value, filename) - - // 3. If there are entries in this’s entry list whose name is name, then - // replace the first such entry with entry and remove the others. - const idx = this[kState].findIndex((entry) => entry.name === name) - if (idx !== -1) { - this[kState] = [ - ...this[kState].slice(0, idx), - entry, - ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) - ] - } else { - // 4. Otherwise, append entry to this’s entry list. - this[kState].push(entry) - } - } - - entries () { - webidl.brandCheck(this, FormData) - - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key+value' - ) - } - - keys () { - webidl.brandCheck(this, FormData) - - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key' - ) - } - - values () { - webidl.brandCheck(this, FormData) - - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'value' - ) - } - - /** - * @param {(value: string, key: string, self: FormData) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) - - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." - ) - } - - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } - } -} - -FormData.prototype[Symbol.iterator] = FormData.prototype.entries - -Object.defineProperties(FormData.prototype, { - [Symbol.toStringTag]: { - value: 'FormData', - configurable: true - } -}) - -/** - * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry - * @param {string} name - * @param {string|Blob} value - * @param {?string} filename - * @returns - */ -function makeEntry (name, value, filename) { - // 1. Set name to the result of converting name into a scalar value string. - // "To convert a string into a scalar value string, replace any surrogates - // with U+FFFD." - // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end - name = Buffer.from(name).toString('utf8') - - // 2. If value is a string, then set value to the result of converting - // value into a scalar value string. - if (typeof value === 'string') { - value = Buffer.from(value).toString('utf8') - } else { - // 3. Otherwise: - - // 1. If value is not a File object, then set value to a new File object, - // representing the same bytes, whose name attribute value is "blob" - if (!isFileLike(value)) { - value = value instanceof Blob - ? new File([value], 'blob', { type: value.type }) - : new FileLike(value, 'blob', { type: value.type }) - } - - // 2. If filename is given, then set value to a new File object, - // representing the same bytes, whose name attribute is filename. - if (filename !== undefined) { - /** @type {FilePropertyBag} */ - const options = { - type: value.type, - lastModified: value.lastModified - } - - value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile - ? new File([value], filename, options) - : new FileLike(value, filename, options) - } - } - - // 4. Return an entry whose name is name and whose value is value. - return { name, value } -} - -module.exports = { FormData } - - -/***/ }), - -/***/ 5628: -/***/ ((module) => { - - - -// In case of breaking changes, increase the version -// number to avoid conflicts. -const globalOrigin = Symbol.for('undici.globalOrigin.1') - -function getGlobalOrigin () { - return globalThis[globalOrigin] -} - -function setGlobalOrigin (newOrigin) { - if (newOrigin === undefined) { - Object.defineProperty(globalThis, globalOrigin, { - value: undefined, - writable: true, - enumerable: false, - configurable: false - }) - - return - } - - const parsedURL = new URL(newOrigin) - - if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { - throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) - } - - Object.defineProperty(globalThis, globalOrigin, { - value: parsedURL, - writable: true, - enumerable: false, - configurable: false - }) -} - -module.exports = { - getGlobalOrigin, - setGlobalOrigin -} - - -/***/ }), - -/***/ 6349: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// https://github.com/Ethan-Arrowood/undici-fetch - - - -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const { kGuard } = __nccwpck_require__(9710) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const { - makeIterator, - isValidHeaderName, - isValidHeaderValue -} = __nccwpck_require__(5523) -const util = __nccwpck_require__(9023) -const { webidl } = __nccwpck_require__(4222) -const assert = __nccwpck_require__(2613) - -const kHeadersMap = Symbol('headers map') -const kHeadersSortedMap = Symbol('headers map sorted') - -/** - * @param {number} code - */ -function isHTTPWhiteSpaceCharCode (code) { - return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize - * @param {string} potentialValue - */ -function headerValueNormalize (potentialValue) { - // To normalize a byte sequence potentialValue, remove - // any leading and trailing HTTP whitespace bytes from - // potentialValue. - let i = 0; let j = potentialValue.length - - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i - - return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) -} - -function fill (headers, object) { - // To fill a Headers object headers with a given object object, run these steps: - - // 1. If object is a sequence, then for each header in object: - // Note: webidl conversion to array has already been done. - if (Array.isArray(object)) { - for (let i = 0; i < object.length; ++i) { - const header = object[i] - // 1. If header does not contain exactly two items, then throw a TypeError. - if (header.length !== 2) { - throw webidl.errors.exception({ - header: 'Headers constructor', - message: `expected name/value pair to be length 2, found ${header.length}.` - }) - } - - // 2. Append (header’s first item, header’s second item) to headers. - appendHeader(headers, header[0], header[1]) - } - } else if (typeof object === 'object' && object !== null) { - // Note: null should throw - - // 2. Otherwise, object is a record, then for each key → value in object, - // append (key, value) to headers - const keys = Object.keys(object) - for (let i = 0; i < keys.length; ++i) { - appendHeader(headers, keys[i], object[keys[i]]) - } - } else { - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) - } -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-headers-append - */ -function appendHeader (headers, name, value) { - // 1. Normalize value. - value = headerValueNormalize(value) - - // 2. If name is not a header name or value is not a - // header value, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.append', - value: name, - type: 'header name' - }) - } else if (!isValidHeaderValue(value)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.append', - value, - type: 'header value' - }) - } - - // 3. If headers’s guard is "immutable", then throw a TypeError. - // 4. Otherwise, if headers’s guard is "request" and name is a - // forbidden header name, return. - // Note: undici does not implement forbidden header names - if (headers[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (headers[kGuard] === 'request-no-cors') { - // 5. Otherwise, if headers’s guard is "request-no-cors": - // TODO - } - - // 6. Otherwise, if headers’s guard is "response" and name is a - // forbidden response-header name, return. - - // 7. Append (name, value) to headers’s header list. - return headers[kHeadersList].append(name, value) - - // 8. If headers’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from headers -} - -class HeadersList { - /** @type {[string, string][]|null} */ - cookies = null - - constructor (init) { - if (init instanceof HeadersList) { - this[kHeadersMap] = new Map(init[kHeadersMap]) - this[kHeadersSortedMap] = init[kHeadersSortedMap] - this.cookies = init.cookies === null ? null : [...init.cookies] - } else { - this[kHeadersMap] = new Map(init) - this[kHeadersSortedMap] = null - } - } - - // https://fetch.spec.whatwg.org/#header-list-contains - contains (name) { - // A header list list contains a header name name if list - // contains a header whose name is a byte-case-insensitive - // match for name. - name = name.toLowerCase() - - return this[kHeadersMap].has(name) - } - - clear () { - this[kHeadersMap].clear() - this[kHeadersSortedMap] = null - this.cookies = null - } - - // https://fetch.spec.whatwg.org/#concept-header-list-append - append (name, value) { - this[kHeadersSortedMap] = null - - // 1. If list contains name, then set name to the first such - // header’s name. - const lowercaseName = name.toLowerCase() - const exists = this[kHeadersMap].get(lowercaseName) - - // 2. Append (name, value) to list. - if (exists) { - const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' - this[kHeadersMap].set(lowercaseName, { - name: exists.name, - value: `${exists.value}${delimiter}${value}` - }) - } else { - this[kHeadersMap].set(lowercaseName, { name, value }) - } - - if (lowercaseName === 'set-cookie') { - this.cookies ??= [] - this.cookies.push(value) - } - } - - // https://fetch.spec.whatwg.org/#concept-header-list-set - set (name, value) { - this[kHeadersSortedMap] = null - const lowercaseName = name.toLowerCase() - - if (lowercaseName === 'set-cookie') { - this.cookies = [value] - } - - // 1. If list contains name, then set the value of - // the first such header to value and remove the - // others. - // 2. Otherwise, append header (name, value) to list. - this[kHeadersMap].set(lowercaseName, { name, value }) - } - - // https://fetch.spec.whatwg.org/#concept-header-list-delete - delete (name) { - this[kHeadersSortedMap] = null - - name = name.toLowerCase() - - if (name === 'set-cookie') { - this.cookies = null - } - - this[kHeadersMap].delete(name) - } - - // https://fetch.spec.whatwg.org/#concept-header-list-get - get (name) { - const value = this[kHeadersMap].get(name.toLowerCase()) - - // 1. If list does not contain name, then return null. - // 2. Return the values of all headers in list whose name - // is a byte-case-insensitive match for name, - // separated from each other by 0x2C 0x20, in order. - return value === undefined ? null : value.value - } - - * [Symbol.iterator] () { - // use the lowercased name - for (const [name, { value }] of this[kHeadersMap]) { - yield [name, value] - } - } - - get entries () { - const headers = {} - - if (this[kHeadersMap].size) { - for (const { name, value } of this[kHeadersMap].values()) { - headers[name] = value - } - } - - return headers - } -} - -// https://fetch.spec.whatwg.org/#headers-class -class Headers { - constructor (init = undefined) { - if (init === kConstruct) { - return - } - this[kHeadersList] = new HeadersList() - - // The new Headers(init) constructor steps are: - - // 1. Set this’s guard to "none". - this[kGuard] = 'none' - - // 2. If init is given, then fill this with init. - if (init !== undefined) { - init = webidl.converters.HeadersInit(init) - fill(this, init) - } - } - - // https://fetch.spec.whatwg.org/#dom-headers-append - append (name, value) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) - - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) - - return appendHeader(this, name, value) - } - - // https://fetch.spec.whatwg.org/#dom-headers-delete - delete (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) - - name = webidl.converters.ByteString(name) - - // 1. If name is not a header name, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.delete', - value: name, - type: 'header name' - }) - } - - // 2. If this’s guard is "immutable", then throw a TypeError. - // 3. Otherwise, if this’s guard is "request" and name is a - // forbidden header name, return. - // 4. Otherwise, if this’s guard is "request-no-cors", name - // is not a no-CORS-safelisted request-header name, and - // name is not a privileged no-CORS request-header name, - // return. - // 5. Otherwise, if this’s guard is "response" and name is - // a forbidden response-header name, return. - // Note: undici does not implement forbidden header names - if (this[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (this[kGuard] === 'request-no-cors') { - // TODO - } - - // 6. If this’s header list does not contain name, then - // return. - if (!this[kHeadersList].contains(name)) { - return - } - - // 7. Delete name from this’s header list. - // 8. If this’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from this. - this[kHeadersList].delete(name) - } - - // https://fetch.spec.whatwg.org/#dom-headers-get - get (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) - - name = webidl.converters.ByteString(name) - - // 1. If name is not a header name, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.get', - value: name, - type: 'header name' - }) - } - - // 2. Return the result of getting name from this’s header - // list. - return this[kHeadersList].get(name) - } - - // https://fetch.spec.whatwg.org/#dom-headers-has - has (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) - - name = webidl.converters.ByteString(name) - - // 1. If name is not a header name, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.has', - value: name, - type: 'header name' - }) - } - - // 2. Return true if this’s header list contains name; - // otherwise false. - return this[kHeadersList].contains(name) - } - - // https://fetch.spec.whatwg.org/#dom-headers-set - set (name, value) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) - - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) - - // 1. Normalize value. - value = headerValueNormalize(value) - - // 2. If name is not a header name or value is not a - // header value, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.set', - value: name, - type: 'header name' - }) - } else if (!isValidHeaderValue(value)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.set', - value, - type: 'header value' - }) - } - - // 3. If this’s guard is "immutable", then throw a TypeError. - // 4. Otherwise, if this’s guard is "request" and name is a - // forbidden header name, return. - // 5. Otherwise, if this’s guard is "request-no-cors" and - // name/value is not a no-CORS-safelisted request-header, - // return. - // 6. Otherwise, if this’s guard is "response" and name is a - // forbidden response-header name, return. - // Note: undici does not implement forbidden header names - if (this[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (this[kGuard] === 'request-no-cors') { - // TODO - } - - // 7. Set (name, value) in this’s header list. - // 8. If this’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from this - this[kHeadersList].set(name, value) - } - - // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie - getSetCookie () { - webidl.brandCheck(this, Headers) - - // 1. If this’s header list does not contain `Set-Cookie`, then return « ». - // 2. Return the values of all headers in this’s header list whose name is - // a byte-case-insensitive match for `Set-Cookie`, in order. - - const list = this[kHeadersList].cookies - - if (list) { - return [...list] - } - - return [] - } - - // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine - get [kHeadersSortedMap] () { - if (this[kHeadersList][kHeadersSortedMap]) { - return this[kHeadersList][kHeadersSortedMap] - } - - // 1. Let headers be an empty list of headers with the key being the name - // and value the value. - const headers = [] - - // 2. Let names be the result of convert header names to a sorted-lowercase - // set with all the names of the headers in list. - const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) - const cookies = this[kHeadersList].cookies - - // 3. For each name of names: - for (let i = 0; i < names.length; ++i) { - const [name, value] = names[i] - // 1. If name is `set-cookie`, then: - if (name === 'set-cookie') { - // 1. Let values be a list of all values of headers in list whose name - // is a byte-case-insensitive match for name, in order. - - // 2. For each value of values: - // 1. Append (name, value) to headers. - for (let j = 0; j < cookies.length; ++j) { - headers.push([name, cookies[j]]) - } - } else { - // 2. Otherwise: - - // 1. Let value be the result of getting name from list. - - // 2. Assert: value is non-null. - assert(value !== null) - - // 3. Append (name, value) to headers. - headers.push([name, value]) - } - } - - this[kHeadersList][kHeadersSortedMap] = headers - - // 4. Return headers. - return headers - } - - keys () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key') - } - - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key' - ) - } - - values () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'value') - } - - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'value' - ) - } - - entries () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key+value') - } - - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key+value' - ) - } - - /** - * @param {(value: string, key: string, self: Headers) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) - - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." - ) - } - - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } - } - - [Symbol.for('nodejs.util.inspect.custom')] () { - webidl.brandCheck(this, Headers) - - return this[kHeadersList] - } -} - -Headers.prototype[Symbol.iterator] = Headers.prototype.entries - -Object.defineProperties(Headers.prototype, { - append: kEnumerableProperty, - delete: kEnumerableProperty, - get: kEnumerableProperty, - has: kEnumerableProperty, - set: kEnumerableProperty, - getSetCookie: kEnumerableProperty, - keys: kEnumerableProperty, - values: kEnumerableProperty, - entries: kEnumerableProperty, - forEach: kEnumerableProperty, - [Symbol.iterator]: { enumerable: false }, - [Symbol.toStringTag]: { - value: 'Headers', - configurable: true - }, - [util.inspect.custom]: { - enumerable: false - } -}) - -webidl.converters.HeadersInit = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (V[Symbol.iterator]) { - return webidl.converters['sequence>'](V) - } - - return webidl.converters['record'](V) - } - - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) -} - -module.exports = { - fill, - Headers, - HeadersList -} - - -/***/ }), - -/***/ 2315: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// https://github.com/Ethan-Arrowood/undici-fetch - - - -const { - Response, - makeNetworkError, - makeAppropriateNetworkError, - filterResponse, - makeResponse -} = __nccwpck_require__(8676) -const { Headers } = __nccwpck_require__(6349) -const { Request, makeRequest } = __nccwpck_require__(5194) -const zlib = __nccwpck_require__(3106) -const { - bytesMatch, - makePolicyContainer, - clonePolicyContainer, - requestBadPort, - TAOCheck, - appendRequestOriginHeader, - responseLocationURL, - requestCurrentURL, - setRequestReferrerPolicyOnRedirect, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - createOpaqueTimingInfo, - appendFetchMetadata, - corsCheck, - crossOriginResourcePolicyCheck, - determineRequestsReferrer, - coarsenedSharedCurrentTime, - createDeferredPromise, - isBlobLike, - sameOrigin, - isCancelled, - isAborted, - isErrorLike, - fullyReadBody, - readableStreamClose, - isomorphicEncode, - urlIsLocal, - urlIsHttpHttpsScheme, - urlHasHttpsScheme -} = __nccwpck_require__(5523) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const assert = __nccwpck_require__(2613) -const { safelyExtractBody } = __nccwpck_require__(8923) -const { - redirectStatusSet, - nullBodyStatus, - safeMethodsSet, - requestBodyHeader, - subresourceSet, - DOMException -} = __nccwpck_require__(7326) -const { kHeadersList } = __nccwpck_require__(6443) -const EE = __nccwpck_require__(4434) -const { Readable, pipeline } = __nccwpck_require__(2203) -const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440) -const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322) -const { TransformStream } = __nccwpck_require__(3774) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { webidl } = __nccwpck_require__(4222) -const { STATUS_CODES } = __nccwpck_require__(8611) -const GET_OR_HEAD = ['GET', 'HEAD'] - -/** @type {import('buffer').resolveObjectURL} */ -let resolveObjectURL -let ReadableStream = globalThis.ReadableStream - -class Fetch extends EE { - constructor (dispatcher) { - super() - - this.dispatcher = dispatcher - this.connection = null - this.dump = false - this.state = 'ongoing' - // 2 terminated listeners get added per request, - // but only 1 gets removed. If there are 20 redirects, - // 21 listeners will be added. - // See https://github.com/nodejs/undici/issues/1711 - // TODO (fix): Find and fix root cause for leaked listener. - this.setMaxListeners(21) - } - - terminate (reason) { - if (this.state !== 'ongoing') { - return - } - - this.state = 'terminated' - this.connection?.destroy(reason) - this.emit('terminated', reason) - } - - // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort (error) { - if (this.state !== 'ongoing') { - return - } - - // 1. Set controller’s state to "aborted". - this.state = 'aborted' - - // 2. Let fallbackError be an "AbortError" DOMException. - // 3. Set error to fallbackError if it is not given. - if (!error) { - error = new DOMException('The operation was aborted.', 'AbortError') - } - - // 4. Let serializedError be StructuredSerialize(error). - // If that threw an exception, catch it, and let - // serializedError be StructuredSerialize(fallbackError). - - // 5. Set controller’s serialized abort reason to serializedError. - this.serializedAbortReason = error - - this.connection?.destroy(error) - this.emit('terminated', error) - } -} - -// https://fetch.spec.whatwg.org/#fetch-method -function fetch (input, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) - - // 1. Let p be a new promise. - const p = createDeferredPromise() - - // 2. Let requestObject be the result of invoking the initial value of - // Request as constructor with input and init as arguments. If this throws - // an exception, reject p with it and return p. - let requestObject - - try { - requestObject = new Request(input, init) - } catch (e) { - p.reject(e) - return p.promise - } - - // 3. Let request be requestObject’s request. - const request = requestObject[kState] - - // 4. If requestObject’s signal’s aborted flag is set, then: - if (requestObject.signal.aborted) { - // 1. Abort the fetch() call with p, request, null, and - // requestObject’s signal’s abort reason. - abortFetch(p, request, null, requestObject.signal.reason) - - // 2. Return p. - return p.promise - } - - // 5. Let globalObject be request’s client’s global object. - const globalObject = request.client.globalObject - - // 6. If globalObject is a ServiceWorkerGlobalScope object, then set - // request’s service-workers mode to "none". - if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { - request.serviceWorkers = 'none' - } - - // 7. Let responseObject be null. - let responseObject = null - - // 8. Let relevantRealm be this’s relevant Realm. - const relevantRealm = null - - // 9. Let locallyAborted be false. - let locallyAborted = false - - // 10. Let controller be null. - let controller = null - - // 11. Add the following abort steps to requestObject’s signal: - addAbortListener( - requestObject.signal, - () => { - // 1. Set locallyAborted to true. - locallyAborted = true - - // 2. Assert: controller is non-null. - assert(controller != null) - - // 3. Abort controller with requestObject’s signal’s abort reason. - controller.abort(requestObject.signal.reason) - - // 4. Abort the fetch() call with p, request, responseObject, - // and requestObject’s signal’s abort reason. - abortFetch(p, request, responseObject, requestObject.signal.reason) - } - ) - - // 12. Let handleFetchDone given response response be to finalize and - // report timing with response, globalObject, and "fetch". - const handleFetchDone = (response) => - finalizeAndReportTiming(response, 'fetch') - - // 13. Set controller to the result of calling fetch given request, - // with processResponseEndOfBody set to handleFetchDone, and processResponse - // given response being these substeps: - - const processResponse = (response) => { - // 1. If locallyAborted is true, terminate these substeps. - if (locallyAborted) { - return Promise.resolve() - } - - // 2. If response’s aborted flag is set, then: - if (response.aborted) { - // 1. Let deserializedError be the result of deserialize a serialized - // abort reason given controller’s serialized abort reason and - // relevantRealm. - - // 2. Abort the fetch() call with p, request, responseObject, and - // deserializedError. - - abortFetch(p, request, responseObject, controller.serializedAbortReason) - return Promise.resolve() - } - - // 3. If response is a network error, then reject p with a TypeError - // and terminate these substeps. - if (response.type === 'error') { - p.reject( - Object.assign(new TypeError('fetch failed'), { cause: response.error }) - ) - return Promise.resolve() - } - - // 4. Set responseObject to the result of creating a Response object, - // given response, "immutable", and relevantRealm. - responseObject = new Response() - responseObject[kState] = response - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kHeadersList] = response.headersList - responseObject[kHeaders][kGuard] = 'immutable' - responseObject[kHeaders][kRealm] = relevantRealm - - // 5. Resolve p with responseObject. - p.resolve(responseObject) - } - - controller = fetching({ - request, - processResponseEndOfBody: handleFetchDone, - processResponse, - dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici - }) - - // 14. Return p. - return p.promise -} - -// https://fetch.spec.whatwg.org/#finalize-and-report-timing -function finalizeAndReportTiming (response, initiatorType = 'other') { - // 1. If response is an aborted network error, then return. - if (response.type === 'error' && response.aborted) { - return - } - - // 2. If response’s URL list is null or empty, then return. - if (!response.urlList?.length) { - return - } - - // 3. Let originalURL be response’s URL list[0]. - const originalURL = response.urlList[0] - - // 4. Let timingInfo be response’s timing info. - let timingInfo = response.timingInfo - - // 5. Let cacheState be response’s cache state. - let cacheState = response.cacheState - - // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. - if (!urlIsHttpHttpsScheme(originalURL)) { - return - } - - // 7. If timingInfo is null, then return. - if (timingInfo === null) { - return - } - - // 8. If response’s timing allow passed flag is not set, then: - if (!response.timingAllowPassed) { - // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. - timingInfo = createOpaqueTimingInfo({ - startTime: timingInfo.startTime - }) - - // 2. Set cacheState to the empty string. - cacheState = '' - } - - // 9. Set timingInfo’s end time to the coarsened shared current time - // given global’s relevant settings object’s cross-origin isolated - // capability. - // TODO: given global’s relevant settings object’s cross-origin isolated - // capability? - timingInfo.endTime = coarsenedSharedCurrentTime() - - // 10. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo - - // 11. Mark resource timing for timingInfo, originalURL, initiatorType, - // global, and cacheState. - markResourceTiming( - timingInfo, - originalURL, - initiatorType, - globalThis, - cacheState - ) -} - -// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing -function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { - if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { - performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) - } -} - -// https://fetch.spec.whatwg.org/#abort-fetch -function abortFetch (p, request, responseObject, error) { - // Note: AbortSignal.reason was added in node v17.2.0 - // which would give us an undefined error to reject with. - // Remove this once node v16 is no longer supported. - if (!error) { - error = new DOMException('The operation was aborted.', 'AbortError') - } - - // 1. Reject promise with error. - p.reject(error) - - // 2. If request’s body is not null and is readable, then cancel request’s - // body with error. - if (request.body != null && isReadable(request.body?.stream)) { - request.body.stream.cancel(error).catch((err) => { - if (err.code === 'ERR_INVALID_STATE') { - // Node bug? - return - } - throw err - }) - } - - // 3. If responseObject is null, then return. - if (responseObject == null) { - return - } - - // 4. Let response be responseObject’s response. - const response = responseObject[kState] - - // 5. If response’s body is not null and is readable, then error response’s - // body with error. - if (response.body != null && isReadable(response.body?.stream)) { - response.body.stream.cancel(error).catch((err) => { - if (err.code === 'ERR_INVALID_STATE') { - // Node bug? - return - } - throw err - }) - } -} - -// https://fetch.spec.whatwg.org/#fetching -function fetching ({ - request, - processRequestBodyChunkLength, - processRequestEndOfBody, - processResponse, - processResponseEndOfBody, - processResponseConsumeBody, - useParallelQueue = false, - dispatcher // undici -}) { - // 1. Let taskDestination be null. - let taskDestination = null - - // 2. Let crossOriginIsolatedCapability be false. - let crossOriginIsolatedCapability = false - - // 3. If request’s client is non-null, then: - if (request.client != null) { - // 1. Set taskDestination to request’s client’s global object. - taskDestination = request.client.globalObject - - // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin - // isolated capability. - crossOriginIsolatedCapability = - request.client.crossOriginIsolatedCapability - } - - // 4. If useParallelQueue is true, then set taskDestination to the result of - // starting a new parallel queue. - // TODO - - // 5. Let timingInfo be a new fetch timing info whose start time and - // post-redirect start time are the coarsened shared current time given - // crossOriginIsolatedCapability. - const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) - const timingInfo = createOpaqueTimingInfo({ - startTime: currenTime - }) - - // 6. Let fetchParams be a new fetch params whose - // request is request, - // timing info is timingInfo, - // process request body chunk length is processRequestBodyChunkLength, - // process request end-of-body is processRequestEndOfBody, - // process response is processResponse, - // process response consume body is processResponseConsumeBody, - // process response end-of-body is processResponseEndOfBody, - // task destination is taskDestination, - // and cross-origin isolated capability is crossOriginIsolatedCapability. - const fetchParams = { - controller: new Fetch(dispatcher), - request, - timingInfo, - processRequestBodyChunkLength, - processRequestEndOfBody, - processResponse, - processResponseConsumeBody, - processResponseEndOfBody, - taskDestination, - crossOriginIsolatedCapability - } - - // 7. If request’s body is a byte sequence, then set request’s body to - // request’s body as a body. - // NOTE: Since fetching is only called from fetch, body should already be - // extracted. - assert(!request.body || request.body.stream) - - // 8. If request’s window is "client", then set request’s window to request’s - // client, if request’s client’s global object is a Window object; otherwise - // "no-window". - if (request.window === 'client') { - // TODO: What if request.client is null? - request.window = - request.client?.globalObject?.constructor?.name === 'Window' - ? request.client - : 'no-window' - } - - // 9. If request’s origin is "client", then set request’s origin to request’s - // client’s origin. - if (request.origin === 'client') { - // TODO: What if request.client is null? - request.origin = request.client?.origin - } - - // 10. If all of the following conditions are true: - // TODO - - // 11. If request’s policy container is "client", then: - if (request.policyContainer === 'client') { - // 1. If request’s client is non-null, then set request’s policy - // container to a clone of request’s client’s policy container. [HTML] - if (request.client != null) { - request.policyContainer = clonePolicyContainer( - request.client.policyContainer - ) - } else { - // 2. Otherwise, set request’s policy container to a new policy - // container. - request.policyContainer = makePolicyContainer() - } - } - - // 12. If request’s header list does not contain `Accept`, then: - if (!request.headersList.contains('accept')) { - // 1. Let value be `*/*`. - const value = '*/*' - - // 2. A user agent should set value to the first matching statement, if - // any, switching on request’s destination: - // "document" - // "frame" - // "iframe" - // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` - // "image" - // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` - // "style" - // `text/css,*/*;q=0.1` - // TODO - - // 3. Append `Accept`/value to request’s header list. - request.headersList.append('accept', value) - } - - // 13. If request’s header list does not contain `Accept-Language`, then - // user agents should append `Accept-Language`/an appropriate value to - // request’s header list. - if (!request.headersList.contains('accept-language')) { - request.headersList.append('accept-language', '*') - } - - // 14. If request’s priority is null, then use request’s initiator and - // destination appropriately in setting request’s priority to a - // user-agent-defined object. - if (request.priority === null) { - // TODO - } - - // 15. If request is a subresource request, then: - if (subresourceSet.has(request.destination)) { - // TODO - } - - // 16. Run main fetch given fetchParams. - mainFetch(fetchParams) - .catch(err => { - fetchParams.controller.terminate(err) - }) - - // 17. Return fetchParam's controller - return fetchParams.controller -} - -// https://fetch.spec.whatwg.org/#concept-main-fetch -async function mainFetch (fetchParams, recursive = false) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null - - // 3. If request’s local-URLs-only flag is set and request’s current URL is - // not local, then set response to a network error. - if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { - response = makeNetworkError('local URLs only') - } - - // 4. Run report Content Security Policy violations for request. - // TODO - - // 5. Upgrade request to a potentially trustworthy URL, if appropriate. - tryUpgradeRequestToAPotentiallyTrustworthyURL(request) - - // 6. If should request be blocked due to a bad port, should fetching request - // be blocked as mixed content, or should request be blocked by Content - // Security Policy returns blocked, then set response to a network error. - if (requestBadPort(request) === 'blocked') { - response = makeNetworkError('bad port') - } - // TODO: should fetching request be blocked as mixed content? - // TODO: should request be blocked by Content Security Policy? - - // 7. If request’s referrer policy is the empty string, then set request’s - // referrer policy to request’s policy container’s referrer policy. - if (request.referrerPolicy === '') { - request.referrerPolicy = request.policyContainer.referrerPolicy - } - - // 8. If request’s referrer is not "no-referrer", then set request’s - // referrer to the result of invoking determine request’s referrer. - if (request.referrer !== 'no-referrer') { - request.referrer = determineRequestsReferrer(request) - } - - // 9. Set request’s current URL’s scheme to "https" if all of the following - // conditions are true: - // - request’s current URL’s scheme is "http" - // - request’s current URL’s host is a domain - // - Matching request’s current URL’s host per Known HSTS Host Domain Name - // Matching results in either a superdomain match with an asserted - // includeSubDomains directive or a congruent match (with or without an - // asserted includeSubDomains directive). [HSTS] - // TODO - - // 10. If recursive is false, then run the remaining steps in parallel. - // TODO - - // 11. If response is null, then set response to the result of running - // the steps corresponding to the first matching statement: - if (response === null) { - response = await (async () => { - const currentURL = requestCurrentURL(request) - - if ( - // - request’s current URL’s origin is same origin with request’s origin, - // and request’s response tainting is "basic" - (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || - // request’s current URL’s scheme is "data" - (currentURL.protocol === 'data:') || - // - request’s mode is "navigate" or "websocket" - (request.mode === 'navigate' || request.mode === 'websocket') - ) { - // 1. Set request’s response tainting to "basic". - request.responseTainting = 'basic' - - // 2. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } - - // request’s mode is "same-origin" - if (request.mode === 'same-origin') { - // 1. Return a network error. - return makeNetworkError('request mode cannot be "same-origin"') - } - - // request’s mode is "no-cors" - if (request.mode === 'no-cors') { - // 1. If request’s redirect mode is not "follow", then return a network - // error. - if (request.redirect !== 'follow') { - return makeNetworkError( - 'redirect mode cannot be "follow" for "no-cors" request' - ) - } - - // 2. Set request’s response tainting to "opaque". - request.responseTainting = 'opaque' - - // 3. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } - - // request’s current URL’s scheme is not an HTTP(S) scheme - if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { - // Return a network error. - return makeNetworkError('URL scheme must be a HTTP(S) scheme') - } - - // - request’s use-CORS-preflight flag is set - // - request’s unsafe-request flag is set and either request’s method is - // not a CORS-safelisted method or CORS-unsafe request-header names with - // request’s header list is not empty - // 1. Set request’s response tainting to "cors". - // 2. Let corsWithPreflightResponse be the result of running HTTP fetch - // given fetchParams and true. - // 3. If corsWithPreflightResponse is a network error, then clear cache - // entries using request. - // 4. Return corsWithPreflightResponse. - // TODO - - // Otherwise - // 1. Set request’s response tainting to "cors". - request.responseTainting = 'cors' - - // 2. Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) - })() - } - - // 12. If recursive is true, then return response. - if (recursive) { - return response - } - - // 13. If response is not a network error and response is not a filtered - // response, then: - if (response.status !== 0 && !response.internalResponse) { - // If request’s response tainting is "cors", then: - if (request.responseTainting === 'cors') { - // 1. Let headerNames be the result of extracting header list values - // given `Access-Control-Expose-Headers` and response’s header list. - // TODO - // 2. If request’s credentials mode is not "include" and headerNames - // contains `*`, then set response’s CORS-exposed header-name list to - // all unique header names in response’s header list. - // TODO - // 3. Otherwise, if headerNames is not null or failure, then set - // response’s CORS-exposed header-name list to headerNames. - // TODO - } - - // Set response to the following filtered response with response as its - // internal response, depending on request’s response tainting: - if (request.responseTainting === 'basic') { - response = filterResponse(response, 'basic') - } else if (request.responseTainting === 'cors') { - response = filterResponse(response, 'cors') - } else if (request.responseTainting === 'opaque') { - response = filterResponse(response, 'opaque') - } else { - assert(false) - } - } - - // 14. Let internalResponse be response, if response is a network error, - // and response’s internal response otherwise. - let internalResponse = - response.status === 0 ? response : response.internalResponse - - // 15. If internalResponse’s URL list is empty, then set it to a clone of - // request’s URL list. - if (internalResponse.urlList.length === 0) { - internalResponse.urlList.push(...request.urlList) - } - - // 16. If request’s timing allow failed flag is unset, then set - // internalResponse’s timing allow passed flag. - if (!request.timingAllowFailed) { - response.timingAllowPassed = true - } - - // 17. If response is not a network error and any of the following returns - // blocked - // - should internalResponse to request be blocked as mixed content - // - should internalResponse to request be blocked by Content Security Policy - // - should internalResponse to request be blocked due to its MIME type - // - should internalResponse to request be blocked due to nosniff - // TODO - - // 18. If response’s type is "opaque", internalResponse’s status is 206, - // internalResponse’s range-requested flag is set, and request’s header - // list does not contain `Range`, then set response and internalResponse - // to a network error. - if ( - response.type === 'opaque' && - internalResponse.status === 206 && - internalResponse.rangeRequested && - !request.headers.contains('range') - ) { - response = internalResponse = makeNetworkError() - } - - // 19. If response is not a network error and either request’s method is - // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, - // set internalResponse’s body to null and disregard any enqueuing toward - // it (if any). - if ( - response.status !== 0 && - (request.method === 'HEAD' || - request.method === 'CONNECT' || - nullBodyStatus.includes(internalResponse.status)) - ) { - internalResponse.body = null - fetchParams.controller.dump = true - } - - // 20. If request’s integrity metadata is not the empty string, then: - if (request.integrity) { - // 1. Let processBodyError be this step: run fetch finale given fetchParams - // and a network error. - const processBodyError = (reason) => - fetchFinale(fetchParams, makeNetworkError(reason)) - - // 2. If request’s response tainting is "opaque", or response’s body is null, - // then run processBodyError and abort these steps. - if (request.responseTainting === 'opaque' || response.body == null) { - processBodyError(response.error) - return - } - - // 3. Let processBody given bytes be these steps: - const processBody = (bytes) => { - // 1. If bytes do not match request’s integrity metadata, - // then run processBodyError and abort these steps. [SRI] - if (!bytesMatch(bytes, request.integrity)) { - processBodyError('integrity mismatch') - return - } - - // 2. Set response’s body to bytes as a body. - response.body = safelyExtractBody(bytes)[0] - - // 3. Run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) - } - - // 4. Fully read response’s body given processBody and processBodyError. - await fullyReadBody(response.body, processBody, processBodyError) - } else { - // 21. Otherwise, run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) - } -} - -// https://fetch.spec.whatwg.org/#concept-scheme-fetch -// given a fetch params fetchParams -function schemeFetch (fetchParams) { - // Note: since the connection is destroyed on redirect, which sets fetchParams to a - // cancelled state, we do not want this condition to trigger *unless* there have been - // no redirects. See https://github.com/nodejs/undici/issues/1776 - // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { - return Promise.resolve(makeAppropriateNetworkError(fetchParams)) - } - - // 2. Let request be fetchParams’s request. - const { request } = fetchParams - - const { protocol: scheme } = requestCurrentURL(request) - - // 3. Switch on request’s current URL’s scheme and run the associated steps: - switch (scheme) { - case 'about:': { - // If request’s current URL’s path is the string "blank", then return a new response - // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », - // and body is the empty byte sequence as a body. - - // Otherwise, return a network error. - return Promise.resolve(makeNetworkError('about scheme is not supported')) - } - case 'blob:': { - if (!resolveObjectURL) { - resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL) - } - - // 1. Let blobURLEntry be request’s current URL’s blob URL entry. - const blobURLEntry = requestCurrentURL(request) - - // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 - // Buffer.resolveObjectURL does not ignore URL queries. - if (blobURLEntry.search.length !== 0) { - return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) - } - - const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) - - // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s - // object is not a Blob object, then return a network error. - if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { - return Promise.resolve(makeNetworkError('invalid method')) - } - - // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. - const bodyWithType = safelyExtractBody(blobURLEntryObject) - - // 4. Let body be bodyWithType’s body. - const body = bodyWithType[0] - - // 5. Let length be body’s length, serialized and isomorphic encoded. - const length = isomorphicEncode(`${body.length}`) - - // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. - const type = bodyWithType[1] ?? '' - - // 7. Return a new response whose status message is `OK`, header list is - // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. - const response = makeResponse({ - statusText: 'OK', - headersList: [ - ['content-length', { name: 'Content-Length', value: length }], - ['content-type', { name: 'Content-Type', value: type }] - ] - }) - - response.body = body - - return Promise.resolve(response) - } - case 'data:': { - // 1. Let dataURLStruct be the result of running the - // data: URL processor on request’s current URL. - const currentURL = requestCurrentURL(request) - const dataURLStruct = dataURLProcessor(currentURL) - - // 2. If dataURLStruct is failure, then return a - // network error. - if (dataURLStruct === 'failure') { - return Promise.resolve(makeNetworkError('failed to fetch the data URL')) - } - - // 3. Let mimeType be dataURLStruct’s MIME type, serialized. - const mimeType = serializeAMimeType(dataURLStruct.mimeType) - - // 4. Return a response whose status message is `OK`, - // header list is « (`Content-Type`, mimeType) », - // and body is dataURLStruct’s body as a body. - return Promise.resolve(makeResponse({ - statusText: 'OK', - headersList: [ - ['content-type', { name: 'Content-Type', value: mimeType }] - ], - body: safelyExtractBody(dataURLStruct.body)[0] - })) - } - case 'file:': { - // For now, unfortunate as it is, file URLs are left as an exercise for the reader. - // When in doubt, return a network error. - return Promise.resolve(makeNetworkError('not implemented... yet...')) - } - case 'http:': - case 'https:': { - // Return the result of running HTTP fetch given fetchParams. - - return httpFetch(fetchParams) - .catch((err) => makeNetworkError(err)) - } - default: { - return Promise.resolve(makeNetworkError('unknown scheme')) - } - } -} - -// https://fetch.spec.whatwg.org/#finalize-response -function finalizeResponse (fetchParams, response) { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true - - // 2, If fetchParams’s process response done is not null, then queue a fetch - // task to run fetchParams’s process response done given response, with - // fetchParams’s task destination. - if (fetchParams.processResponseDone != null) { - queueMicrotask(() => fetchParams.processResponseDone(response)) - } -} - -// https://fetch.spec.whatwg.org/#fetch-finale -function fetchFinale (fetchParams, response) { - // 1. If response is a network error, then: - if (response.type === 'error') { - // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». - response.urlList = [fetchParams.request.urlList[0]] - - // 2. Set response’s timing info to the result of creating an opaque timing - // info for fetchParams’s timing info. - response.timingInfo = createOpaqueTimingInfo({ - startTime: fetchParams.timingInfo.startTime - }) - } - - // 2. Let processResponseEndOfBody be the following steps: - const processResponseEndOfBody = () => { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true - - // If fetchParams’s process response end-of-body is not null, - // then queue a fetch task to run fetchParams’s process response - // end-of-body given response with fetchParams’s task destination. - if (fetchParams.processResponseEndOfBody != null) { - queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) - } - } - - // 3. If fetchParams’s process response is non-null, then queue a fetch task - // to run fetchParams’s process response given response, with fetchParams’s - // task destination. - if (fetchParams.processResponse != null) { - queueMicrotask(() => fetchParams.processResponse(response)) - } - - // 4. If response’s body is null, then run processResponseEndOfBody. - if (response.body == null) { - processResponseEndOfBody() - } else { - // 5. Otherwise: - - // 1. Let transformStream be a new a TransformStream. - - // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, - // enqueues chunk in transformStream. - const identityTransformAlgorithm = (chunk, controller) => { - controller.enqueue(chunk) - } - - // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm - // and flushAlgorithm set to processResponseEndOfBody. - const transformStream = new TransformStream({ - start () {}, - transform: identityTransformAlgorithm, - flush: processResponseEndOfBody - }, { - size () { - return 1 - } - }, { - size () { - return 1 - } - }) - - // 4. Set response’s body to the result of piping response’s body through transformStream. - response.body = { stream: response.body.stream.pipeThrough(transformStream) } - } - - // 6. If fetchParams’s process response consume body is non-null, then: - if (fetchParams.processResponseConsumeBody != null) { - // 1. Let processBody given nullOrBytes be this step: run fetchParams’s - // process response consume body given response and nullOrBytes. - const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) - - // 2. Let processBodyError be this step: run fetchParams’s process - // response consume body given response and failure. - const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) - - // 3. If response’s body is null, then queue a fetch task to run processBody - // given null, with fetchParams’s task destination. - if (response.body == null) { - queueMicrotask(() => processBody(null)) - } else { - // 4. Otherwise, fully read response’s body given processBody, processBodyError, - // and fetchParams’s task destination. - return fullyReadBody(response.body, processBody, processBodyError) - } - return Promise.resolve() - } -} - -// https://fetch.spec.whatwg.org/#http-fetch -async function httpFetch (fetchParams) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null - - // 3. Let actualResponse be null. - let actualResponse = null - - // 4. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo - - // 5. If request’s service-workers mode is "all", then: - if (request.serviceWorkers === 'all') { - // TODO - } - - // 6. If response is null, then: - if (response === null) { - // 1. If makeCORSPreflight is true and one of these conditions is true: - // TODO - - // 2. If request’s redirect mode is "follow", then set request’s - // service-workers mode to "none". - if (request.redirect === 'follow') { - request.serviceWorkers = 'none' - } - - // 3. Set response and actualResponse to the result of running - // HTTP-network-or-cache fetch given fetchParams. - actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) - - // 4. If request’s response tainting is "cors" and a CORS check - // for request and response returns failure, then return a network error. - if ( - request.responseTainting === 'cors' && - corsCheck(request, response) === 'failure' - ) { - return makeNetworkError('cors failure') - } - - // 5. If the TAO check for request and response returns failure, then set - // request’s timing allow failed flag. - if (TAOCheck(request, response) === 'failure') { - request.timingAllowFailed = true - } - } - - // 7. If either request’s response tainting or response’s type - // is "opaque", and the cross-origin resource policy check with - // request’s origin, request’s client, request’s destination, - // and actualResponse returns blocked, then return a network error. - if ( - (request.responseTainting === 'opaque' || response.type === 'opaque') && - crossOriginResourcePolicyCheck( - request.origin, - request.client, - request.destination, - actualResponse - ) === 'blocked' - ) { - return makeNetworkError('blocked') - } - - // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatusSet.has(actualResponse.status)) { - // 1. If actualResponse’s status is not 303, request’s body is not null, - // and the connection uses HTTP/2, then user agents may, and are even - // encouraged to, transmit an RST_STREAM frame. - // See, https://github.com/whatwg/fetch/issues/1288 - if (request.redirect !== 'manual') { - fetchParams.controller.connection.destroy() - } - - // 2. Switch on request’s redirect mode: - if (request.redirect === 'error') { - // Set response to a network error. - response = makeNetworkError('unexpected redirect') - } else if (request.redirect === 'manual') { - // Set response to an opaque-redirect filtered response whose internal - // response is actualResponse. - // NOTE(spec): On the web this would return an `opaqueredirect` response, - // but that doesn't make sense server side. - // See https://github.com/nodejs/undici/issues/1193. - response = actualResponse - } else if (request.redirect === 'follow') { - // Set response to the result of running HTTP-redirect fetch given - // fetchParams and response. - response = await httpRedirectFetch(fetchParams, response) - } else { - assert(false) - } - } - - // 9. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo - - // 10. Return response. - return response -} - -// https://fetch.spec.whatwg.org/#http-redirect-fetch -function httpRedirectFetch (fetchParams, response) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let actualResponse be response, if response is not a filtered response, - // and response’s internal response otherwise. - const actualResponse = response.internalResponse - ? response.internalResponse - : response - - // 3. Let locationURL be actualResponse’s location URL given request’s current - // URL’s fragment. - let locationURL - - try { - locationURL = responseLocationURL( - actualResponse, - requestCurrentURL(request).hash - ) - - // 4. If locationURL is null, then return response. - if (locationURL == null) { - return response - } - } catch (err) { - // 5. If locationURL is failure, then return a network error. - return Promise.resolve(makeNetworkError(err)) - } - - // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network - // error. - if (!urlIsHttpHttpsScheme(locationURL)) { - return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) - } - - // 7. If request’s redirect count is 20, then return a network error. - if (request.redirectCount === 20) { - return Promise.resolve(makeNetworkError('redirect count exceeded')) - } - - // 8. Increase request’s redirect count by 1. - request.redirectCount += 1 - - // 9. If request’s mode is "cors", locationURL includes credentials, and - // request’s origin is not same origin with locationURL’s origin, then return - // a network error. - if ( - request.mode === 'cors' && - (locationURL.username || locationURL.password) && - !sameOrigin(request, locationURL) - ) { - return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) - } - - // 10. If request’s response tainting is "cors" and locationURL includes - // credentials, then return a network error. - if ( - request.responseTainting === 'cors' && - (locationURL.username || locationURL.password) - ) { - return Promise.resolve(makeNetworkError( - 'URL cannot contain credentials for request mode "cors"' - )) - } - - // 11. If actualResponse’s status is not 303, request’s body is non-null, - // and request’s body’s source is null, then return a network error. - if ( - actualResponse.status !== 303 && - request.body != null && - request.body.source == null - ) { - return Promise.resolve(makeNetworkError()) - } - - // 12. If one of the following is true - // - actualResponse’s status is 301 or 302 and request’s method is `POST` - // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` - if ( - ([301, 302].includes(actualResponse.status) && request.method === 'POST') || - (actualResponse.status === 303 && - !GET_OR_HEAD.includes(request.method)) - ) { - // then: - // 1. Set request’s method to `GET` and request’s body to null. - request.method = 'GET' - request.body = null - - // 2. For each headerName of request-body-header name, delete headerName from - // request’s header list. - for (const headerName of requestBodyHeader) { - request.headersList.delete(headerName) - } - } - - // 13. If request’s current URL’s origin is not same origin with locationURL’s - // origin, then for each headerName of CORS non-wildcard request-header name, - // delete headerName from request’s header list. - if (!sameOrigin(requestCurrentURL(request), locationURL)) { - // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name - request.headersList.delete('authorization') - - // https://fetch.spec.whatwg.org/#authentication-entries - request.headersList.delete('proxy-authorization', true) - - // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. - request.headersList.delete('cookie') - request.headersList.delete('host') - } - - // 14. If request’s body is non-null, then set request’s body to the first return - // value of safely extracting request’s body’s source. - if (request.body != null) { - assert(request.body.source != null) - request.body = safelyExtractBody(request.body.source)[0] - } - - // 15. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo - - // 16. Set timingInfo’s redirect end time and post-redirect start time to the - // coarsened shared current time given fetchParams’s cross-origin isolated - // capability. - timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = - coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) - - // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s - // redirect start time to timingInfo’s start time. - if (timingInfo.redirectStartTime === 0) { - timingInfo.redirectStartTime = timingInfo.startTime - } - - // 18. Append locationURL to request’s URL list. - request.urlList.push(locationURL) - - // 19. Invoke set request’s referrer policy on redirect on request and - // actualResponse. - setRequestReferrerPolicyOnRedirect(request, actualResponse) - - // 20. Return the result of running main fetch given fetchParams and true. - return mainFetch(fetchParams, true) -} - -// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch -async function httpNetworkOrCacheFetch ( - fetchParams, - isAuthenticationFetch = false, - isNewConnectionFetch = false -) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let httpFetchParams be null. - let httpFetchParams = null - - // 3. Let httpRequest be null. - let httpRequest = null - - // 4. Let response be null. - let response = null - - // 5. Let storedResponse be null. - // TODO: cache - - // 6. Let httpCache be null. - const httpCache = null - - // 7. Let the revalidatingFlag be unset. - const revalidatingFlag = false - - // 8. Run these steps, but abort when the ongoing fetch is terminated: - - // 1. If request’s window is "no-window" and request’s redirect mode is - // "error", then set httpFetchParams to fetchParams and httpRequest to - // request. - if (request.window === 'no-window' && request.redirect === 'error') { - httpFetchParams = fetchParams - httpRequest = request - } else { - // Otherwise: - - // 1. Set httpRequest to a clone of request. - httpRequest = makeRequest(request) - - // 2. Set httpFetchParams to a copy of fetchParams. - httpFetchParams = { ...fetchParams } - - // 3. Set httpFetchParams’s request to httpRequest. - httpFetchParams.request = httpRequest - } - - // 3. Let includeCredentials be true if one of - const includeCredentials = - request.credentials === 'include' || - (request.credentials === 'same-origin' && - request.responseTainting === 'basic') - - // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s - // body is non-null; otherwise null. - const contentLength = httpRequest.body ? httpRequest.body.length : null - - // 5. Let contentLengthHeaderValue be null. - let contentLengthHeaderValue = null - - // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or - // `PUT`, then set contentLengthHeaderValue to `0`. - if ( - httpRequest.body == null && - ['POST', 'PUT'].includes(httpRequest.method) - ) { - contentLengthHeaderValue = '0' - } - - // 7. If contentLength is non-null, then set contentLengthHeaderValue to - // contentLength, serialized and isomorphic encoded. - if (contentLength != null) { - contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) - } - - // 8. If contentLengthHeaderValue is non-null, then append - // `Content-Length`/contentLengthHeaderValue to httpRequest’s header - // list. - if (contentLengthHeaderValue != null) { - httpRequest.headersList.append('content-length', contentLengthHeaderValue) - } - - // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, - // contentLengthHeaderValue) to httpRequest’s header list. - - // 10. If contentLength is non-null and httpRequest’s keepalive is true, - // then: - if (contentLength != null && httpRequest.keepalive) { - // NOTE: keepalive is a noop outside of browser context. - } - - // 11. If httpRequest’s referrer is a URL, then append - // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, - // to httpRequest’s header list. - if (httpRequest.referrer instanceof URL) { - httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) - } - - // 12. Append a request `Origin` header for httpRequest. - appendRequestOriginHeader(httpRequest) - - // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] - appendFetchMetadata(httpRequest) - - // 14. If httpRequest’s header list does not contain `User-Agent`, then - // user agents should append `User-Agent`/default `User-Agent` value to - // httpRequest’s header list. - if (!httpRequest.headersList.contains('user-agent')) { - httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') - } - - // 15. If httpRequest’s cache mode is "default" and httpRequest’s header - // list contains `If-Modified-Since`, `If-None-Match`, - // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set - // httpRequest’s cache mode to "no-store". - if ( - httpRequest.cache === 'default' && - (httpRequest.headersList.contains('if-modified-since') || - httpRequest.headersList.contains('if-none-match') || - httpRequest.headersList.contains('if-unmodified-since') || - httpRequest.headersList.contains('if-match') || - httpRequest.headersList.contains('if-range')) - ) { - httpRequest.cache = 'no-store' - } - - // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent - // no-cache cache-control header modification flag is unset, and - // httpRequest’s header list does not contain `Cache-Control`, then append - // `Cache-Control`/`max-age=0` to httpRequest’s header list. - if ( - httpRequest.cache === 'no-cache' && - !httpRequest.preventNoCacheCacheControlHeaderModification && - !httpRequest.headersList.contains('cache-control') - ) { - httpRequest.headersList.append('cache-control', 'max-age=0') - } - - // 17. If httpRequest’s cache mode is "no-store" or "reload", then: - if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { - // 1. If httpRequest’s header list does not contain `Pragma`, then append - // `Pragma`/`no-cache` to httpRequest’s header list. - if (!httpRequest.headersList.contains('pragma')) { - httpRequest.headersList.append('pragma', 'no-cache') - } - - // 2. If httpRequest’s header list does not contain `Cache-Control`, - // then append `Cache-Control`/`no-cache` to httpRequest’s header list. - if (!httpRequest.headersList.contains('cache-control')) { - httpRequest.headersList.append('cache-control', 'no-cache') - } - } - - // 18. If httpRequest’s header list contains `Range`, then append - // `Accept-Encoding`/`identity` to httpRequest’s header list. - if (httpRequest.headersList.contains('range')) { - httpRequest.headersList.append('accept-encoding', 'identity') - } - - // 19. Modify httpRequest’s header list per HTTP. Do not append a given - // header if httpRequest’s header list contains that header’s name. - // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 - if (!httpRequest.headersList.contains('accept-encoding')) { - if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { - httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') - } else { - httpRequest.headersList.append('accept-encoding', 'gzip, deflate') - } - } - - httpRequest.headersList.delete('host') - - // 20. If includeCredentials is true, then: - if (includeCredentials) { - // 1. If the user agent is not configured to block cookies for httpRequest - // (see section 7 of [COOKIES]), then: - // TODO: credentials - // 2. If httpRequest’s header list does not contain `Authorization`, then: - // TODO: credentials - } - - // 21. If there’s a proxy-authentication entry, use it as appropriate. - // TODO: proxy-authentication - - // 22. Set httpCache to the result of determining the HTTP cache - // partition, given httpRequest. - // TODO: cache - - // 23. If httpCache is null, then set httpRequest’s cache mode to - // "no-store". - if (httpCache == null) { - httpRequest.cache = 'no-store' - } - - // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", - // then: - if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { - // TODO: cache - } - - // 9. If aborted, then return the appropriate network error for fetchParams. - // TODO - - // 10. If response is null, then: - if (response == null) { - // 1. If httpRequest’s cache mode is "only-if-cached", then return a - // network error. - if (httpRequest.mode === 'only-if-cached') { - return makeNetworkError('only if cached') - } - - // 2. Let forwardResponse be the result of running HTTP-network fetch - // given httpFetchParams, includeCredentials, and isNewConnectionFetch. - const forwardResponse = await httpNetworkFetch( - httpFetchParams, - includeCredentials, - isNewConnectionFetch - ) - - // 3. If httpRequest’s method is unsafe and forwardResponse’s status is - // in the range 200 to 399, inclusive, invalidate appropriate stored - // responses in httpCache, as per the "Invalidation" chapter of HTTP - // Caching, and set storedResponse to null. [HTTP-CACHING] - if ( - !safeMethodsSet.has(httpRequest.method) && - forwardResponse.status >= 200 && - forwardResponse.status <= 399 - ) { - // TODO: cache - } - - // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, - // then: - if (revalidatingFlag && forwardResponse.status === 304) { - // TODO: cache - } - - // 5. If response is null, then: - if (response == null) { - // 1. Set response to forwardResponse. - response = forwardResponse - - // 2. Store httpRequest and forwardResponse in httpCache, as per the - // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] - // TODO: cache - } - } - - // 11. Set response’s URL list to a clone of httpRequest’s URL list. - response.urlList = [...httpRequest.urlList] - - // 12. If httpRequest’s header list contains `Range`, then set response’s - // range-requested flag. - if (httpRequest.headersList.contains('range')) { - response.rangeRequested = true - } - - // 13. Set response’s request-includes-credentials to includeCredentials. - response.requestIncludesCredentials = includeCredentials - - // 14. If response’s status is 401, httpRequest’s response tainting is not - // "cors", includeCredentials is true, and request’s window is an environment - // settings object, then: - // TODO - - // 15. If response’s status is 407, then: - if (response.status === 407) { - // 1. If request’s window is "no-window", then return a network error. - if (request.window === 'no-window') { - return makeNetworkError() - } - - // 2. ??? - - // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) - } - - // 4. Prompt the end user as appropriate in request’s window and store - // the result as a proxy-authentication entry. [HTTP-AUTH] - // TODO: Invoke some kind of callback? - - // 5. Set response to the result of running HTTP-network-or-cache fetch given - // fetchParams. - // TODO - return makeNetworkError('proxy authentication required') - } - - // 16. If all of the following are true - if ( - // response’s status is 421 - response.status === 421 && - // isNewConnectionFetch is false - !isNewConnectionFetch && - // request’s body is null, or request’s body is non-null and request’s body’s source is non-null - (request.body == null || request.body.source != null) - ) { - // then: - - // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) - } - - // 2. Set response to the result of running HTTP-network-or-cache - // fetch given fetchParams, isAuthenticationFetch, and true. - - // TODO (spec): The spec doesn't specify this but we need to cancel - // the active response before we can start a new one. - // https://github.com/whatwg/fetch/issues/1293 - fetchParams.controller.connection.destroy() - - response = await httpNetworkOrCacheFetch( - fetchParams, - isAuthenticationFetch, - true - ) - } - - // 17. If isAuthenticationFetch is true, then create an authentication entry - if (isAuthenticationFetch) { - // TODO - } - - // 18. Return response. - return response -} - -// https://fetch.spec.whatwg.org/#http-network-fetch -async function httpNetworkFetch ( - fetchParams, - includeCredentials = false, - forceNewConnection = false -) { - assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) - - fetchParams.controller.connection = { - abort: null, - destroyed: false, - destroy (err) { - if (!this.destroyed) { - this.destroyed = true - this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) - } - } - } - - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null - - // 3. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo - - // 4. Let httpCache be the result of determining the HTTP cache partition, - // given request. - // TODO: cache - const httpCache = null - - // 5. If httpCache is null, then set request’s cache mode to "no-store". - if (httpCache == null) { - request.cache = 'no-store' - } - - // 6. Let networkPartitionKey be the result of determining the network - // partition key given request. - // TODO - - // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise - // "no". - const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars - - // 8. Switch on request’s mode: - if (request.mode === 'websocket') { - // Let connection be the result of obtaining a WebSocket connection, - // given request’s current URL. - // TODO - } else { - // Let connection be the result of obtaining a connection, given - // networkPartitionKey, request’s current URL’s origin, - // includeCredentials, and forceNewConnection. - // TODO - } - - // 9. Run these steps, but abort when the ongoing fetch is terminated: - - // 1. If connection is failure, then return a network error. - - // 2. Set timingInfo’s final connection timing info to the result of - // calling clamp and coarsen connection timing info with connection’s - // timing info, timingInfo’s post-redirect start time, and fetchParams’s - // cross-origin isolated capability. - - // 3. If connection is not an HTTP/2 connection, request’s body is non-null, - // and request’s body’s source is null, then append (`Transfer-Encoding`, - // `chunked`) to request’s header list. - - // 4. Set timingInfo’s final network-request start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated - // capability. - - // 5. Set response to the result of making an HTTP request over connection - // using request with the following caveats: - - // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] - // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] - - // - If request’s body is non-null, and request’s body’s source is null, - // then the user agent may have a buffer of up to 64 kibibytes and store - // a part of request’s body in that buffer. If the user agent reads from - // request’s body beyond that buffer’s size and the user agent needs to - // resend request, then instead return a network error. - - // - Set timingInfo’s final network-response start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated capability, - // immediately after the user agent’s HTTP parser receives the first byte - // of the response (e.g., frame header bytes for HTTP/2 or response status - // line for HTTP/1.x). - - // - Wait until all the headers are transmitted. - - // - Any responses whose status is in the range 100 to 199, inclusive, - // and is not 101, are to be ignored, except for the purposes of setting - // timingInfo’s final network-response start time above. - - // - If request’s header list contains `Transfer-Encoding`/`chunked` and - // response is transferred via HTTP/1.0 or older, then return a network - // error. - - // - If the HTTP request results in a TLS client certificate dialog, then: - - // 1. If request’s window is an environment settings object, make the - // dialog available in request’s window. - - // 2. Otherwise, return a network error. - - // To transmit request’s body body, run these steps: - let requestBody = null - // 1. If body is null and fetchParams’s process request end-of-body is - // non-null, then queue a fetch task given fetchParams’s process request - // end-of-body and fetchParams’s task destination. - if (request.body == null && fetchParams.processRequestEndOfBody) { - queueMicrotask(() => fetchParams.processRequestEndOfBody()) - } else if (request.body != null) { - // 2. Otherwise, if body is non-null: - - // 1. Let processBodyChunk given bytes be these steps: - const processBodyChunk = async function * (bytes) { - // 1. If the ongoing fetch is terminated, then abort these steps. - if (isCancelled(fetchParams)) { - return - } - - // 2. Run this step in parallel: transmit bytes. - yield bytes - - // 3. If fetchParams’s process request body is non-null, then run - // fetchParams’s process request body given bytes’s length. - fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) - } - - // 2. Let processEndOfBody be these steps: - const processEndOfBody = () => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } - - // 2. If fetchParams’s process request end-of-body is non-null, - // then run fetchParams’s process request end-of-body. - if (fetchParams.processRequestEndOfBody) { - fetchParams.processRequestEndOfBody() - } - } - - // 3. Let processBodyError given e be these steps: - const processBodyError = (e) => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } - - // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. - if (e.name === 'AbortError') { - fetchParams.controller.abort() - } else { - fetchParams.controller.terminate(e) - } - } - - // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, - // processBodyError, and fetchParams’s task destination. - requestBody = (async function * () { - try { - for await (const bytes of request.body.stream) { - yield * processBodyChunk(bytes) - } - processEndOfBody() - } catch (err) { - processBodyError(err) - } - })() - } - - try { - // socket is only provided for websockets - const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) - - if (socket) { - response = makeResponse({ status, statusText, headersList, socket }) - } else { - const iterator = body[Symbol.asyncIterator]() - fetchParams.controller.next = () => iterator.next() - - response = makeResponse({ status, statusText, headersList }) - } - } catch (err) { - // 10. If aborted, then: - if (err.name === 'AbortError') { - // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. - fetchParams.controller.connection.destroy() - - // 2. Return the appropriate network error for fetchParams. - return makeAppropriateNetworkError(fetchParams, err) - } - - return makeNetworkError(err) - } - - // 11. Let pullAlgorithm be an action that resumes the ongoing fetch - // if it is suspended. - const pullAlgorithm = () => { - fetchParams.controller.resume() - } - - // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s - // controller with reason, given reason. - const cancelAlgorithm = (reason) => { - fetchParams.controller.abort(reason) - } - - // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by - // the user agent. - // TODO - - // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object - // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. - // TODO - - // 15. Let stream be a new ReadableStream. - // 16. Set up stream with pullAlgorithm set to pullAlgorithm, - // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to - // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - const stream = new ReadableStream( - { - async start (controller) { - fetchParams.controller.controller = controller - }, - async pull (controller) { - await pullAlgorithm(controller) - }, - async cancel (reason) { - await cancelAlgorithm(reason) - } - }, - { - highWaterMark: 0, - size () { - return 1 - } - } - ) - - // 17. Run these steps, but abort when the ongoing fetch is terminated: - - // 1. Set response’s body to a new body whose stream is stream. - response.body = { stream } - - // 2. If response is not a network error and request’s cache mode is - // not "no-store", then update response in httpCache for request. - // TODO - - // 3. If includeCredentials is true and the user agent is not configured - // to block cookies for request (see section 7 of [COOKIES]), then run the - // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on - // the value of each header whose name is a byte-case-insensitive match for - // `Set-Cookie` in response’s header list, if any, and request’s current URL. - // TODO - - // 18. If aborted, then: - // TODO - - // 19. Run these steps in parallel: - - // 1. Run these steps, but abort when fetchParams is canceled: - fetchParams.controller.on('terminated', onAborted) - fetchParams.controller.resume = async () => { - // 1. While true - while (true) { - // 1-3. See onData... - - // 4. Set bytes to the result of handling content codings given - // codings and bytes. - let bytes - let isFailure - try { - const { done, value } = await fetchParams.controller.next() - - if (isAborted(fetchParams)) { - break - } - - bytes = done ? undefined : value - } catch (err) { - if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { - // zlib doesn't like empty streams. - bytes = undefined - } else { - bytes = err - - // err may be propagated from the result of calling readablestream.cancel, - // which might not be an error. https://github.com/nodejs/undici/issues/2009 - isFailure = true - } - } - - if (bytes === undefined) { - // 2. Otherwise, if the bytes transmission for response’s message - // body is done normally and stream is readable, then close - // stream, finalize response for fetchParams and response, and - // abort these in-parallel steps. - readableStreamClose(fetchParams.controller.controller) - - finalizeResponse(fetchParams, response) - - return - } - - // 5. Increase timingInfo’s decoded body size by bytes’s length. - timingInfo.decodedBodySize += bytes?.byteLength ?? 0 - - // 6. If bytes is failure, then terminate fetchParams’s controller. - if (isFailure) { - fetchParams.controller.terminate(bytes) - return - } - - // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes - // into stream. - fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) - - // 8. If stream is errored, then terminate the ongoing fetch. - if (isErrored(stream)) { - fetchParams.controller.terminate() - return - } - - // 9. If stream doesn’t need more data ask the user agent to suspend - // the ongoing fetch. - if (!fetchParams.controller.controller.desiredSize) { - return - } - } - } - - // 2. If aborted, then: - function onAborted (reason) { - // 2. If fetchParams is aborted, then: - if (isAborted(fetchParams)) { - // 1. Set response’s aborted flag. - response.aborted = true - - // 2. If stream is readable, then error stream with the result of - // deserialize a serialized abort reason given fetchParams’s - // controller’s serialized abort reason and an - // implementation-defined realm. - if (isReadable(stream)) { - fetchParams.controller.controller.error( - fetchParams.controller.serializedAbortReason - ) - } - } else { - // 3. Otherwise, if stream is readable, error stream with a TypeError. - if (isReadable(stream)) { - fetchParams.controller.controller.error(new TypeError('terminated', { - cause: isErrorLike(reason) ? reason : undefined - })) - } - } - - // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. - // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. - fetchParams.controller.connection.destroy() - } - - // 20. Return response. - return response - - async function dispatch ({ body }) { - const url = requestCurrentURL(request) - /** @type {import('../..').Agent} */ - const agent = fetchParams.controller.dispatcher - - return new Promise((resolve, reject) => agent.dispatch( - { - path: url.pathname + url.search, - origin: url.origin, - method: request.method, - body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, - headers: request.headersList.entries, - maxRedirections: 0, - upgrade: request.mode === 'websocket' ? 'websocket' : undefined - }, - { - body: null, - abort: null, - - onConnect (abort) { - // TODO (fix): Do we need connection here? - const { connection } = fetchParams.controller - - if (connection.destroyed) { - abort(new DOMException('The operation was aborted.', 'AbortError')) - } else { - fetchParams.controller.on('terminated', abort) - this.abort = connection.abort = abort - } - }, - - onHeaders (status, headersList, resume, statusText) { - if (status < 200) { - return - } - - let codings = [] - let location = '' - - const headers = new Headers() - - // For H2, the headers are a plain JS object - // We distinguish between them and iterate accordingly - if (Array.isArray(headersList)) { - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') - if (key.toLowerCase() === 'content-encoding') { - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 - // "All content-coding values are case-insensitive..." - codings = val.toLowerCase().split(',').map((x) => x.trim()) - } else if (key.toLowerCase() === 'location') { - location = val - } - - headers[kHeadersList].append(key, val) - } - } else { - const keys = Object.keys(headersList) - for (const key of keys) { - const val = headersList[key] - if (key.toLowerCase() === 'content-encoding') { - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 - // "All content-coding values are case-insensitive..." - codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() - } else if (key.toLowerCase() === 'location') { - location = val - } - - headers[kHeadersList].append(key, val) - } - } - - this.body = new Readable({ read: resume }) - - const decoders = [] - - const willFollow = request.redirect === 'follow' && - location && - redirectStatusSet.has(status) - - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { - for (const coding of codings) { - // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 - if (coding === 'x-gzip' || coding === 'gzip') { - decoders.push(zlib.createGunzip({ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: zlib.constants.Z_SYNC_FLUSH - })) - } else if (coding === 'deflate') { - decoders.push(zlib.createInflate()) - } else if (coding === 'br') { - decoders.push(zlib.createBrotliDecompress()) - } else { - decoders.length = 0 - break - } - } - } - - resolve({ - status, - statusText, - headersList: headers[kHeadersList], - body: decoders.length - ? pipeline(this.body, ...decoders, () => { }) - : this.body.on('error', () => {}) - }) - - return true - }, - - onData (chunk) { - if (fetchParams.controller.dump) { - return - } - - // 1. If one or more bytes have been transmitted from response’s - // message body, then: - - // 1. Let bytes be the transmitted bytes. - const bytes = chunk - - // 2. Let codings be the result of extracting header list values - // given `Content-Encoding` and response’s header list. - // See pullAlgorithm. - - // 3. Increase timingInfo’s encoded body size by bytes’s length. - timingInfo.encodedBodySize += bytes.byteLength - - // 4. See pullAlgorithm... - - return this.body.push(bytes) - }, - - onComplete () { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } - - fetchParams.controller.ended = true - - this.body.push(null) - }, - - onError (error) { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } - - this.body?.destroy(error) - - fetchParams.controller.terminate(error) - - reject(error) - }, - - onUpgrade (status, headersList, socket) { - if (status !== 101) { - return - } - - const headers = new Headers() - - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') - - headers[kHeadersList].append(key, val) - } - - resolve({ - status, - statusText: STATUS_CODES[status], - headersList: headers[kHeadersList], - socket - }) - - return true - } - } - )) - } -} - -module.exports = { - fetch, - Fetch, - fetching, - finalizeAndReportTiming -} - - -/***/ }), - -/***/ 5194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* globals AbortController */ - - - -const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923) -const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349) -const { FinalizationRegistry } = __nccwpck_require__(3194)() -const util = __nccwpck_require__(3440) -const { - isValidHTTPToken, - sameOrigin, - normalizeMethod, - makePolicyContainer, - normalizeMethodRecord -} = __nccwpck_require__(5523) -const { - forbiddenMethodsSet, - corsSafeListedMethodsSet, - referrerPolicy, - requestRedirect, - requestMode, - requestCredentials, - requestCache, - requestDuplex -} = __nccwpck_require__(7326) -const { kEnumerableProperty } = util -const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { URLSerializer } = __nccwpck_require__(4322) -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434) - -let TransformStream = globalThis.TransformStream - -const kAbortController = Symbol('abortController') - -const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { - signal.removeEventListener('abort', abort) -}) - -// https://fetch.spec.whatwg.org/#request-class -class Request { - // https://fetch.spec.whatwg.org/#dom-request - constructor (input, init = {}) { - if (input === kConstruct) { - return - } - - webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) - - input = webidl.converters.RequestInfo(input) - init = webidl.converters.RequestInit(init) - - // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object - this[kRealm] = { - settingsObject: { - baseUrl: getGlobalOrigin(), - get origin () { - return this.baseUrl?.origin - }, - policyContainer: makePolicyContainer() - } - } - - // 1. Let request be null. - let request = null - - // 2. Let fallbackMode be null. - let fallbackMode = null - - // 3. Let baseURL be this’s relevant settings object’s API base URL. - const baseUrl = this[kRealm].settingsObject.baseUrl - - // 4. Let signal be null. - let signal = null - - // 5. If input is a string, then: - if (typeof input === 'string') { - // 1. Let parsedURL be the result of parsing input with baseURL. - // 2. If parsedURL is failure, then throw a TypeError. - let parsedURL - try { - parsedURL = new URL(input, baseUrl) - } catch (err) { - throw new TypeError('Failed to parse URL from ' + input, { cause: err }) - } - - // 3. If parsedURL includes credentials, then throw a TypeError. - if (parsedURL.username || parsedURL.password) { - throw new TypeError( - 'Request cannot be constructed from a URL that includes credentials: ' + - input - ) - } - - // 4. Set request to a new request whose URL is parsedURL. - request = makeRequest({ urlList: [parsedURL] }) - - // 5. Set fallbackMode to "cors". - fallbackMode = 'cors' - } else { - // 6. Otherwise: - - // 7. Assert: input is a Request object. - assert(input instanceof Request) - - // 8. Set request to input’s request. - request = input[kState] - - // 9. Set signal to input’s signal. - signal = input[kSignal] - } - - // 7. Let origin be this’s relevant settings object’s origin. - const origin = this[kRealm].settingsObject.origin - - // 8. Let window be "client". - let window = 'client' - - // 9. If request’s window is an environment settings object and its origin - // is same origin with origin, then set window to request’s window. - if ( - request.window?.constructor?.name === 'EnvironmentSettingsObject' && - sameOrigin(request.window, origin) - ) { - window = request.window - } - - // 10. If init["window"] exists and is non-null, then throw a TypeError. - if (init.window != null) { - throw new TypeError(`'window' option '${window}' must be null`) - } - - // 11. If init["window"] exists, then set window to "no-window". - if ('window' in init) { - window = 'no-window' - } - - // 12. Set request to a new request with the following properties: - request = makeRequest({ - // URL request’s URL. - // undici implementation note: this is set as the first item in request's urlList in makeRequest - // method request’s method. - method: request.method, - // header list A copy of request’s header list. - // undici implementation note: headersList is cloned in makeRequest - headersList: request.headersList, - // unsafe-request flag Set. - unsafeRequest: request.unsafeRequest, - // client This’s relevant settings object. - client: this[kRealm].settingsObject, - // window window. - window, - // priority request’s priority. - priority: request.priority, - // origin request’s origin. The propagation of the origin is only significant for navigation requests - // being handled by a service worker. In this scenario a request can have an origin that is different - // from the current client. - origin: request.origin, - // referrer request’s referrer. - referrer: request.referrer, - // referrer policy request’s referrer policy. - referrerPolicy: request.referrerPolicy, - // mode request’s mode. - mode: request.mode, - // credentials mode request’s credentials mode. - credentials: request.credentials, - // cache mode request’s cache mode. - cache: request.cache, - // redirect mode request’s redirect mode. - redirect: request.redirect, - // integrity metadata request’s integrity metadata. - integrity: request.integrity, - // keepalive request’s keepalive. - keepalive: request.keepalive, - // reload-navigation flag request’s reload-navigation flag. - reloadNavigation: request.reloadNavigation, - // history-navigation flag request’s history-navigation flag. - historyNavigation: request.historyNavigation, - // URL list A clone of request’s URL list. - urlList: [...request.urlList] - }) - - const initHasKey = Object.keys(init).length !== 0 - - // 13. If init is not empty, then: - if (initHasKey) { - // 1. If request’s mode is "navigate", then set it to "same-origin". - if (request.mode === 'navigate') { - request.mode = 'same-origin' - } - - // 2. Unset request’s reload-navigation flag. - request.reloadNavigation = false - - // 3. Unset request’s history-navigation flag. - request.historyNavigation = false - - // 4. Set request’s origin to "client". - request.origin = 'client' - - // 5. Set request’s referrer to "client" - request.referrer = 'client' - - // 6. Set request’s referrer policy to the empty string. - request.referrerPolicy = '' - - // 7. Set request’s URL to request’s current URL. - request.url = request.urlList[request.urlList.length - 1] - - // 8. Set request’s URL list to « request’s URL ». - request.urlList = [request.url] - } - - // 14. If init["referrer"] exists, then: - if (init.referrer !== undefined) { - // 1. Let referrer be init["referrer"]. - const referrer = init.referrer - - // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". - if (referrer === '') { - request.referrer = 'no-referrer' - } else { - // 1. Let parsedReferrer be the result of parsing referrer with - // baseURL. - // 2. If parsedReferrer is failure, then throw a TypeError. - let parsedReferrer - try { - parsedReferrer = new URL(referrer, baseUrl) - } catch (err) { - throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) - } - - // 3. If one of the following is true - // - parsedReferrer’s scheme is "about" and path is the string "client" - // - parsedReferrer’s origin is not same origin with origin - // then set request’s referrer to "client". - if ( - (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || - (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) - ) { - request.referrer = 'client' - } else { - // 4. Otherwise, set request’s referrer to parsedReferrer. - request.referrer = parsedReferrer - } - } - } - - // 15. If init["referrerPolicy"] exists, then set request’s referrer policy - // to it. - if (init.referrerPolicy !== undefined) { - request.referrerPolicy = init.referrerPolicy - } - - // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. - let mode - if (init.mode !== undefined) { - mode = init.mode - } else { - mode = fallbackMode - } - - // 17. If mode is "navigate", then throw a TypeError. - if (mode === 'navigate') { - throw webidl.errors.exception({ - header: 'Request constructor', - message: 'invalid request mode navigate.' - }) - } - - // 18. If mode is non-null, set request’s mode to mode. - if (mode != null) { - request.mode = mode - } - - // 19. If init["credentials"] exists, then set request’s credentials mode - // to it. - if (init.credentials !== undefined) { - request.credentials = init.credentials - } - - // 18. If init["cache"] exists, then set request’s cache mode to it. - if (init.cache !== undefined) { - request.cache = init.cache - } - - // 21. If request’s cache mode is "only-if-cached" and request’s mode is - // not "same-origin", then throw a TypeError. - if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { - throw new TypeError( - "'only-if-cached' can be set only with 'same-origin' mode" - ) - } - - // 22. If init["redirect"] exists, then set request’s redirect mode to it. - if (init.redirect !== undefined) { - request.redirect = init.redirect - } - - // 23. If init["integrity"] exists, then set request’s integrity metadata to it. - if (init.integrity != null) { - request.integrity = String(init.integrity) - } - - // 24. If init["keepalive"] exists, then set request’s keepalive to it. - if (init.keepalive !== undefined) { - request.keepalive = Boolean(init.keepalive) - } - - // 25. If init["method"] exists, then: - if (init.method !== undefined) { - // 1. Let method be init["method"]. - let method = init.method - - // 2. If method is not a method or method is a forbidden method, then - // throw a TypeError. - if (!isValidHTTPToken(method)) { - throw new TypeError(`'${method}' is not a valid HTTP method.`) - } - - if (forbiddenMethodsSet.has(method.toUpperCase())) { - throw new TypeError(`'${method}' HTTP method is unsupported.`) - } - - // 3. Normalize method. - method = normalizeMethodRecord[method] ?? normalizeMethod(method) - - // 4. Set request’s method to method. - request.method = method - } - - // 26. If init["signal"] exists, then set signal to it. - if (init.signal !== undefined) { - signal = init.signal - } - - // 27. Set this’s request to request. - this[kState] = request - - // 28. Set this’s signal to a new AbortSignal object with this’s relevant - // Realm. - // TODO: could this be simplified with AbortSignal.any - // (https://dom.spec.whatwg.org/#dom-abortsignal-any) - const ac = new AbortController() - this[kSignal] = ac.signal - this[kSignal][kRealm] = this[kRealm] - - // 29. If signal is not null, then make this’s signal follow signal. - if (signal != null) { - if ( - !signal || - typeof signal.aborted !== 'boolean' || - typeof signal.addEventListener !== 'function' - ) { - throw new TypeError( - "Failed to construct 'Request': member signal is not of type AbortSignal." - ) - } - - if (signal.aborted) { - ac.abort(signal.reason) - } else { - // Keep a strong ref to ac while request object - // is alive. This is needed to prevent AbortController - // from being prematurely garbage collected. - // See, https://github.com/nodejs/undici/issues/1926. - this[kAbortController] = ac - - const acRef = new WeakRef(ac) - const abort = function () { - const ac = acRef.deref() - if (ac !== undefined) { - ac.abort(this.reason) - } - } - - // Third-party AbortControllers may not work with these. - // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. - try { - // If the max amount of listeners is equal to the default, increase it - // This is only available in node >= v19.9.0 - if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { - setMaxListeners(100, signal) - } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { - setMaxListeners(100, signal) - } - } catch {} - - util.addAbortListener(signal, abort) - requestFinalizer.register(ac, { signal, abort }) - } - } - - // 30. Set this’s headers to a new Headers object with this’s relevant - // Realm, whose header list is request’s header list and guard is - // "request". - this[kHeaders] = new Headers(kConstruct) - this[kHeaders][kHeadersList] = request.headersList - this[kHeaders][kGuard] = 'request' - this[kHeaders][kRealm] = this[kRealm] - - // 31. If this’s request’s mode is "no-cors", then: - if (mode === 'no-cors') { - // 1. If this’s request’s method is not a CORS-safelisted method, - // then throw a TypeError. - if (!corsSafeListedMethodsSet.has(request.method)) { - throw new TypeError( - `'${request.method} is unsupported in no-cors mode.` - ) - } - - // 2. Set this’s headers’s guard to "request-no-cors". - this[kHeaders][kGuard] = 'request-no-cors' - } - - // 32. If init is not empty, then: - if (initHasKey) { - /** @type {HeadersList} */ - const headersList = this[kHeaders][kHeadersList] - // 1. Let headers be a copy of this’s headers and its associated header - // list. - // 2. If init["headers"] exists, then set headers to init["headers"]. - const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) - - // 3. Empty this’s headers’s header list. - headersList.clear() - - // 4. If headers is a Headers object, then for each header in its header - // list, append header’s name/header’s value to this’s headers. - if (headers instanceof HeadersList) { - for (const [key, val] of headers) { - headersList.append(key, val) - } - // Note: Copy the `set-cookie` meta-data. - headersList.cookies = headers.cookies - } else { - // 5. Otherwise, fill this’s headers with headers. - fillHeaders(this[kHeaders], headers) - } - } - - // 33. Let inputBody be input’s request’s body if input is a Request - // object; otherwise null. - const inputBody = input instanceof Request ? input[kState].body : null - - // 34. If either init["body"] exists and is non-null or inputBody is - // non-null, and request’s method is `GET` or `HEAD`, then throw a - // TypeError. - if ( - (init.body != null || inputBody != null) && - (request.method === 'GET' || request.method === 'HEAD') - ) { - throw new TypeError('Request with GET/HEAD method cannot have body.') - } - - // 35. Let initBody be null. - let initBody = null - - // 36. If init["body"] exists and is non-null, then: - if (init.body != null) { - // 1. Let Content-Type be null. - // 2. Set initBody and Content-Type to the result of extracting - // init["body"], with keepalive set to request’s keepalive. - const [extractedBody, contentType] = extractBody( - init.body, - request.keepalive - ) - initBody = extractedBody - - // 3, If Content-Type is non-null and this’s headers’s header list does - // not contain `Content-Type`, then append `Content-Type`/Content-Type to - // this’s headers. - if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { - this[kHeaders].append('content-type', contentType) - } - } - - // 37. Let inputOrInitBody be initBody if it is non-null; otherwise - // inputBody. - const inputOrInitBody = initBody ?? inputBody - - // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is - // null, then: - if (inputOrInitBody != null && inputOrInitBody.source == null) { - // 1. If initBody is non-null and init["duplex"] does not exist, - // then throw a TypeError. - if (initBody != null && init.duplex == null) { - throw new TypeError('RequestInit: duplex option is required when sending a body.') - } - - // 2. If this’s request’s mode is neither "same-origin" nor "cors", - // then throw a TypeError. - if (request.mode !== 'same-origin' && request.mode !== 'cors') { - throw new TypeError( - 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' - ) - } - - // 3. Set this’s request’s use-CORS-preflight flag. - request.useCORSPreflightFlag = true - } - - // 39. Let finalBody be inputOrInitBody. - let finalBody = inputOrInitBody - - // 40. If initBody is null and inputBody is non-null, then: - if (initBody == null && inputBody != null) { - // 1. If input is unusable, then throw a TypeError. - if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { - throw new TypeError( - 'Cannot construct a Request with a Request object that has already been used.' - ) - } - - // 2. Set finalBody to the result of creating a proxy for inputBody. - if (!TransformStream) { - TransformStream = (__nccwpck_require__(3774).TransformStream) - } - - // https://streams.spec.whatwg.org/#readablestream-create-a-proxy - const identityTransform = new TransformStream() - inputBody.stream.pipeThrough(identityTransform) - finalBody = { - source: inputBody.source, - length: inputBody.length, - stream: identityTransform.readable - } - } - - // 41. Set this’s request’s body to finalBody. - this[kState].body = finalBody - } - - // Returns request’s HTTP method, which is "GET" by default. - get method () { - webidl.brandCheck(this, Request) - - // The method getter steps are to return this’s request’s method. - return this[kState].method - } - - // Returns the URL of request as a string. - get url () { - webidl.brandCheck(this, Request) - - // The url getter steps are to return this’s request’s URL, serialized. - return URLSerializer(this[kState].url) - } - - // Returns a Headers object consisting of the headers associated with request. - // Note that headers added in the network layer by the user agent will not - // be accounted for in this object, e.g., the "Host" header. - get headers () { - webidl.brandCheck(this, Request) - - // The headers getter steps are to return this’s headers. - return this[kHeaders] - } - - // Returns the kind of resource requested by request, e.g., "document" - // or "script". - get destination () { - webidl.brandCheck(this, Request) - - // The destination getter are to return this’s request’s destination. - return this[kState].destination - } - - // Returns the referrer of request. Its value can be a same-origin URL if - // explicitly set in init, the empty string to indicate no referrer, and - // "about:client" when defaulting to the global’s default. This is used - // during fetching to determine the value of the `Referer` header of the - // request being made. - get referrer () { - webidl.brandCheck(this, Request) - - // 1. If this’s request’s referrer is "no-referrer", then return the - // empty string. - if (this[kState].referrer === 'no-referrer') { - return '' - } - - // 2. If this’s request’s referrer is "client", then return - // "about:client". - if (this[kState].referrer === 'client') { - return 'about:client' - } - - // Return this’s request’s referrer, serialized. - return this[kState].referrer.toString() - } - - // Returns the referrer policy associated with request. - // This is used during fetching to compute the value of the request’s - // referrer. - get referrerPolicy () { - webidl.brandCheck(this, Request) - - // The referrerPolicy getter steps are to return this’s request’s referrer policy. - return this[kState].referrerPolicy - } - - // Returns the mode associated with request, which is a string indicating - // whether the request will use CORS, or will be restricted to same-origin - // URLs. - get mode () { - webidl.brandCheck(this, Request) - - // The mode getter steps are to return this’s request’s mode. - return this[kState].mode - } - - // Returns the credentials mode associated with request, - // which is a string indicating whether credentials will be sent with the - // request always, never, or only when sent to a same-origin URL. - get credentials () { - // The credentials getter steps are to return this’s request’s credentials mode. - return this[kState].credentials - } - - // Returns the cache mode associated with request, - // which is a string indicating how the request will - // interact with the browser’s cache when fetching. - get cache () { - webidl.brandCheck(this, Request) - - // The cache getter steps are to return this’s request’s cache mode. - return this[kState].cache - } - - // Returns the redirect mode associated with request, - // which is a string indicating how redirects for the - // request will be handled during fetching. A request - // will follow redirects by default. - get redirect () { - webidl.brandCheck(this, Request) - - // The redirect getter steps are to return this’s request’s redirect mode. - return this[kState].redirect - } - - // Returns request’s subresource integrity metadata, which is a - // cryptographic hash of the resource being fetched. Its value - // consists of multiple hashes separated by whitespace. [SRI] - get integrity () { - webidl.brandCheck(this, Request) - - // The integrity getter steps are to return this’s request’s integrity - // metadata. - return this[kState].integrity - } - - // Returns a boolean indicating whether or not request can outlive the - // global in which it was created. - get keepalive () { - webidl.brandCheck(this, Request) - - // The keepalive getter steps are to return this’s request’s keepalive. - return this[kState].keepalive - } - - // Returns a boolean indicating whether or not request is for a reload - // navigation. - get isReloadNavigation () { - webidl.brandCheck(this, Request) - - // The isReloadNavigation getter steps are to return true if this’s - // request’s reload-navigation flag is set; otherwise false. - return this[kState].reloadNavigation - } - - // Returns a boolean indicating whether or not request is for a history - // navigation (a.k.a. back-foward navigation). - get isHistoryNavigation () { - webidl.brandCheck(this, Request) - - // The isHistoryNavigation getter steps are to return true if this’s request’s - // history-navigation flag is set; otherwise false. - return this[kState].historyNavigation - } - - // Returns the signal associated with request, which is an AbortSignal - // object indicating whether or not request has been aborted, and its - // abort event handler. - get signal () { - webidl.brandCheck(this, Request) - - // The signal getter steps are to return this’s signal. - return this[kSignal] - } - - get body () { - webidl.brandCheck(this, Request) - - return this[kState].body ? this[kState].body.stream : null - } - - get bodyUsed () { - webidl.brandCheck(this, Request) - - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } - - get duplex () { - webidl.brandCheck(this, Request) - - return 'half' - } - - // Returns a clone of request. - clone () { - webidl.brandCheck(this, Request) - - // 1. If this is unusable, then throw a TypeError. - if (this.bodyUsed || this.body?.locked) { - throw new TypeError('unusable') - } - - // 2. Let clonedRequest be the result of cloning this’s request. - const clonedRequest = cloneRequest(this[kState]) - - // 3. Let clonedRequestObject be the result of creating a Request object, - // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. - const clonedRequestObject = new Request(kConstruct) - clonedRequestObject[kState] = clonedRequest - clonedRequestObject[kRealm] = this[kRealm] - clonedRequestObject[kHeaders] = new Headers(kConstruct) - clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList - clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] - clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] - - // 4. Make clonedRequestObject’s signal follow this’s signal. - const ac = new AbortController() - if (this.signal.aborted) { - ac.abort(this.signal.reason) - } else { - util.addAbortListener( - this.signal, - () => { - ac.abort(this.signal.reason) - } - ) - } - clonedRequestObject[kSignal] = ac.signal - - // 4. Return clonedRequestObject. - return clonedRequestObject - } -} - -mixinBody(Request) - -function makeRequest (init) { - // https://fetch.spec.whatwg.org/#requests - const request = { - method: 'GET', - localURLsOnly: false, - unsafeRequest: false, - body: null, - client: null, - reservedClient: null, - replacesClientId: '', - window: 'client', - keepalive: false, - serviceWorkers: 'all', - initiator: '', - destination: '', - priority: null, - origin: 'client', - policyContainer: 'client', - referrer: 'client', - referrerPolicy: '', - mode: 'no-cors', - useCORSPreflightFlag: false, - credentials: 'same-origin', - useCredentials: false, - cache: 'default', - redirect: 'follow', - integrity: '', - cryptoGraphicsNonceMetadata: '', - parserMetadata: '', - reloadNavigation: false, - historyNavigation: false, - userActivation: false, - taintedOrigin: false, - redirectCount: 0, - responseTainting: 'basic', - preventNoCacheCacheControlHeaderModification: false, - done: false, - timingAllowFailed: false, - ...init, - headersList: init.headersList - ? new HeadersList(init.headersList) - : new HeadersList() - } - request.url = request.urlList[0] - return request -} - -// https://fetch.spec.whatwg.org/#concept-request-clone -function cloneRequest (request) { - // To clone a request request, run these steps: - - // 1. Let newRequest be a copy of request, except for its body. - const newRequest = makeRequest({ ...request, body: null }) - - // 2. If request’s body is non-null, set newRequest’s body to the - // result of cloning request’s body. - if (request.body != null) { - newRequest.body = cloneBody(request.body) - } - - // 3. Return newRequest. - return newRequest -} - -Object.defineProperties(Request.prototype, { - method: kEnumerableProperty, - url: kEnumerableProperty, - headers: kEnumerableProperty, - redirect: kEnumerableProperty, - clone: kEnumerableProperty, - signal: kEnumerableProperty, - duplex: kEnumerableProperty, - destination: kEnumerableProperty, - body: kEnumerableProperty, - bodyUsed: kEnumerableProperty, - isHistoryNavigation: kEnumerableProperty, - isReloadNavigation: kEnumerableProperty, - keepalive: kEnumerableProperty, - integrity: kEnumerableProperty, - cache: kEnumerableProperty, - credentials: kEnumerableProperty, - attribute: kEnumerableProperty, - referrerPolicy: kEnumerableProperty, - referrer: kEnumerableProperty, - mode: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'Request', - configurable: true - } -}) - -webidl.converters.Request = webidl.interfaceConverter( - Request -) - -// https://fetch.spec.whatwg.org/#requestinfo -webidl.converters.RequestInfo = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) - } - - if (V instanceof Request) { - return webidl.converters.Request(V) - } - - return webidl.converters.USVString(V) -} - -webidl.converters.AbortSignal = webidl.interfaceConverter( - AbortSignal -) - -// https://fetch.spec.whatwg.org/#requestinit -webidl.converters.RequestInit = webidl.dictionaryConverter([ - { - key: 'method', - converter: webidl.converters.ByteString - }, - { - key: 'headers', - converter: webidl.converters.HeadersInit - }, - { - key: 'body', - converter: webidl.nullableConverter( - webidl.converters.BodyInit - ) - }, - { - key: 'referrer', - converter: webidl.converters.USVString - }, - { - key: 'referrerPolicy', - converter: webidl.converters.DOMString, - // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy - allowedValues: referrerPolicy - }, - { - key: 'mode', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#concept-request-mode - allowedValues: requestMode - }, - { - key: 'credentials', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#requestcredentials - allowedValues: requestCredentials - }, - { - key: 'cache', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#requestcache - allowedValues: requestCache - }, - { - key: 'redirect', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#requestredirect - allowedValues: requestRedirect - }, - { - key: 'integrity', - converter: webidl.converters.DOMString - }, - { - key: 'keepalive', - converter: webidl.converters.boolean - }, - { - key: 'signal', - converter: webidl.nullableConverter( - (signal) => webidl.converters.AbortSignal( - signal, - { strict: false } - ) - ) - }, - { - key: 'window', - converter: webidl.converters.any - }, - { - key: 'duplex', - converter: webidl.converters.DOMString, - allowedValues: requestDuplex - } -]) - -module.exports = { Request, makeRequest } - - -/***/ }), - -/***/ 8676: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Headers, HeadersList, fill } = __nccwpck_require__(6349) -const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923) -const util = __nccwpck_require__(3440) -const { kEnumerableProperty } = util -const { - isValidReasonPhrase, - isCancelled, - isAborted, - isBlobLike, - serializeJavascriptValueToJSONString, - isErrorLike, - isomorphicEncode -} = __nccwpck_require__(5523) -const { - redirectStatusSet, - nullBodyStatus, - DOMException -} = __nccwpck_require__(7326) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { FormData } = __nccwpck_require__(3073) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { URLSerializer } = __nccwpck_require__(4322) -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { types } = __nccwpck_require__(9023) - -const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream) -const textEncoder = new TextEncoder('utf-8') - -// https://fetch.spec.whatwg.org/#response-class -class Response { - // Creates network error Response. - static error () { - // TODO - const relevantRealm = { settingsObject: {} } - - // The static error() method steps are to return the result of creating a - // Response object, given a new network error, "immutable", and this’s - // relevant Realm. - const responseObject = new Response() - responseObject[kState] = makeNetworkError() - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList - responseObject[kHeaders][kGuard] = 'immutable' - responseObject[kHeaders][kRealm] = relevantRealm - return responseObject - } - - // https://fetch.spec.whatwg.org/#dom-response-json - static json (data, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) - - if (init !== null) { - init = webidl.converters.ResponseInit(init) - } - - // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = textEncoder.encode( - serializeJavascriptValueToJSONString(data) - ) - - // 2. Let body be the result of extracting bytes. - const body = extractBody(bytes) - - // 3. Let responseObject be the result of creating a Response object, given a new response, - // "response", and this’s relevant Realm. - const relevantRealm = { settingsObject: {} } - const responseObject = new Response() - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kGuard] = 'response' - responseObject[kHeaders][kRealm] = relevantRealm - - // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). - initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) - - // 5. Return responseObject. - return responseObject - } - - // Creates a redirect Response that redirects to url with status status. - static redirect (url, status = 302) { - const relevantRealm = { settingsObject: {} } - - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) - - url = webidl.converters.USVString(url) - status = webidl.converters['unsigned short'](status) - - // 1. Let parsedURL be the result of parsing url with current settings - // object’s API base URL. - // 2. If parsedURL is failure, then throw a TypeError. - // TODO: base-URL? - let parsedURL - try { - parsedURL = new URL(url, getGlobalOrigin()) - } catch (err) { - throw Object.assign(new TypeError('Failed to parse URL from ' + url), { - cause: err - }) - } - - // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatusSet.has(status)) { - throw new RangeError('Invalid status code ' + status) - } - - // 4. Let responseObject be the result of creating a Response object, - // given a new response, "immutable", and this’s relevant Realm. - const responseObject = new Response() - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kGuard] = 'immutable' - responseObject[kHeaders][kRealm] = relevantRealm - - // 5. Set responseObject’s response’s status to status. - responseObject[kState].status = status - - // 6. Let value be parsedURL, serialized and isomorphic encoded. - const value = isomorphicEncode(URLSerializer(parsedURL)) - - // 7. Append `Location`/value to responseObject’s response’s header list. - responseObject[kState].headersList.append('location', value) - - // 8. Return responseObject. - return responseObject - } - - // https://fetch.spec.whatwg.org/#dom-response - constructor (body = null, init = {}) { - if (body !== null) { - body = webidl.converters.BodyInit(body) - } - - init = webidl.converters.ResponseInit(init) - - // TODO - this[kRealm] = { settingsObject: {} } - - // 1. Set this’s response to a new response. - this[kState] = makeResponse({}) - - // 2. Set this’s headers to a new Headers object with this’s relevant - // Realm, whose header list is this’s response’s header list and guard - // is "response". - this[kHeaders] = new Headers(kConstruct) - this[kHeaders][kGuard] = 'response' - this[kHeaders][kHeadersList] = this[kState].headersList - this[kHeaders][kRealm] = this[kRealm] - - // 3. Let bodyWithType be null. - let bodyWithType = null - - // 4. If body is non-null, then set bodyWithType to the result of extracting body. - if (body != null) { - const [extractedBody, type] = extractBody(body) - bodyWithType = { body: extractedBody, type } - } - - // 5. Perform initialize a response given this, init, and bodyWithType. - initializeResponse(this, init, bodyWithType) - } - - // Returns response’s type, e.g., "cors". - get type () { - webidl.brandCheck(this, Response) - - // The type getter steps are to return this’s response’s type. - return this[kState].type - } - - // Returns response’s URL, if it has one; otherwise the empty string. - get url () { - webidl.brandCheck(this, Response) - - const urlList = this[kState].urlList - - // The url getter steps are to return the empty string if this’s - // response’s URL is null; otherwise this’s response’s URL, - // serialized with exclude fragment set to true. - const url = urlList[urlList.length - 1] ?? null - - if (url === null) { - return '' - } - - return URLSerializer(url, true) - } - - // Returns whether response was obtained through a redirect. - get redirected () { - webidl.brandCheck(this, Response) - - // The redirected getter steps are to return true if this’s response’s URL - // list has more than one item; otherwise false. - return this[kState].urlList.length > 1 - } - - // Returns response’s status. - get status () { - webidl.brandCheck(this, Response) - - // The status getter steps are to return this’s response’s status. - return this[kState].status - } - - // Returns whether response’s status is an ok status. - get ok () { - webidl.brandCheck(this, Response) - - // The ok getter steps are to return true if this’s response’s status is an - // ok status; otherwise false. - return this[kState].status >= 200 && this[kState].status <= 299 - } - - // Returns response’s status message. - get statusText () { - webidl.brandCheck(this, Response) - - // The statusText getter steps are to return this’s response’s status - // message. - return this[kState].statusText - } - - // Returns response’s headers as Headers. - get headers () { - webidl.brandCheck(this, Response) - - // The headers getter steps are to return this’s headers. - return this[kHeaders] - } - - get body () { - webidl.brandCheck(this, Response) - - return this[kState].body ? this[kState].body.stream : null - } - - get bodyUsed () { - webidl.brandCheck(this, Response) - - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } - - // Returns a clone of response. - clone () { - webidl.brandCheck(this, Response) - - // 1. If this is unusable, then throw a TypeError. - if (this.bodyUsed || (this.body && this.body.locked)) { - throw webidl.errors.exception({ - header: 'Response.clone', - message: 'Body has already been consumed.' - }) - } - - // 2. Let clonedResponse be the result of cloning this’s response. - const clonedResponse = cloneResponse(this[kState]) - - // 3. Return the result of creating a Response object, given - // clonedResponse, this’s headers’s guard, and this’s relevant Realm. - const clonedResponseObject = new Response() - clonedResponseObject[kState] = clonedResponse - clonedResponseObject[kRealm] = this[kRealm] - clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList - clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] - clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] - - return clonedResponseObject - } -} - -mixinBody(Response) - -Object.defineProperties(Response.prototype, { - type: kEnumerableProperty, - url: kEnumerableProperty, - status: kEnumerableProperty, - ok: kEnumerableProperty, - redirected: kEnumerableProperty, - statusText: kEnumerableProperty, - headers: kEnumerableProperty, - clone: kEnumerableProperty, - body: kEnumerableProperty, - bodyUsed: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'Response', - configurable: true - } -}) - -Object.defineProperties(Response, { - json: kEnumerableProperty, - redirect: kEnumerableProperty, - error: kEnumerableProperty -}) - -// https://fetch.spec.whatwg.org/#concept-response-clone -function cloneResponse (response) { - // To clone a response response, run these steps: - - // 1. If response is a filtered response, then return a new identical - // filtered response whose internal response is a clone of response’s - // internal response. - if (response.internalResponse) { - return filterResponse( - cloneResponse(response.internalResponse), - response.type - ) - } - - // 2. Let newResponse be a copy of response, except for its body. - const newResponse = makeResponse({ ...response, body: null }) - - // 3. If response’s body is non-null, then set newResponse’s body to the - // result of cloning response’s body. - if (response.body != null) { - newResponse.body = cloneBody(response.body) - } - - // 4. Return newResponse. - return newResponse -} - -function makeResponse (init) { - return { - aborted: false, - rangeRequested: false, - timingAllowPassed: false, - requestIncludesCredentials: false, - type: 'default', - status: 200, - timingInfo: null, - cacheState: '', - statusText: '', - ...init, - headersList: init.headersList - ? new HeadersList(init.headersList) - : new HeadersList(), - urlList: init.urlList ? [...init.urlList] : [] - } -} - -function makeNetworkError (reason) { - const isError = isErrorLike(reason) - return makeResponse({ - type: 'error', - status: 0, - error: isError - ? reason - : new Error(reason ? String(reason) : reason), - aborted: reason && reason.name === 'AbortError' - }) -} - -function makeFilteredResponse (response, state) { - state = { - internalResponse: response, - ...state - } - - return new Proxy(response, { - get (target, p) { - return p in state ? state[p] : target[p] - }, - set (target, p, value) { - assert(!(p in state)) - target[p] = value - return true - } - }) -} - -// https://fetch.spec.whatwg.org/#concept-filtered-response -function filterResponse (response, type) { - // Set response to the following filtered response with response as its - // internal response, depending on request’s response tainting: - if (type === 'basic') { - // A basic filtered response is a filtered response whose type is "basic" - // and header list excludes any headers in internal response’s header list - // whose name is a forbidden response-header name. - - // Note: undici does not implement forbidden response-header names - return makeFilteredResponse(response, { - type: 'basic', - headersList: response.headersList - }) - } else if (type === 'cors') { - // A CORS filtered response is a filtered response whose type is "cors" - // and header list excludes any headers in internal response’s header - // list whose name is not a CORS-safelisted response-header name, given - // internal response’s CORS-exposed header-name list. - - // Note: undici does not implement CORS-safelisted response-header names - return makeFilteredResponse(response, { - type: 'cors', - headersList: response.headersList - }) - } else if (type === 'opaque') { - // An opaque filtered response is a filtered response whose type is - // "opaque", URL list is the empty list, status is 0, status message - // is the empty byte sequence, header list is empty, and body is null. - - return makeFilteredResponse(response, { - type: 'opaque', - urlList: Object.freeze([]), - status: 0, - statusText: '', - body: null - }) - } else if (type === 'opaqueredirect') { - // An opaque-redirect filtered response is a filtered response whose type - // is "opaqueredirect", status is 0, status message is the empty byte - // sequence, header list is empty, and body is null. - - return makeFilteredResponse(response, { - type: 'opaqueredirect', - status: 0, - statusText: '', - headersList: [], - body: null - }) - } else { - assert(false) - } -} - -// https://fetch.spec.whatwg.org/#appropriate-network-error -function makeAppropriateNetworkError (fetchParams, err = null) { - // 1. Assert: fetchParams is canceled. - assert(isCancelled(fetchParams)) - - // 2. Return an aborted network error if fetchParams is aborted; - // otherwise return a network error. - return isAborted(fetchParams) - ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) - : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) -} - -// https://whatpr.org/fetch/1392.html#initialize-a-response -function initializeResponse (response, init, body) { - // 1. If init["status"] is not in the range 200 to 599, inclusive, then - // throw a RangeError. - if (init.status !== null && (init.status < 200 || init.status > 599)) { - throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') - } - - // 2. If init["statusText"] does not match the reason-phrase token production, - // then throw a TypeError. - if ('statusText' in init && init.statusText != null) { - // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: - // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) - if (!isValidReasonPhrase(String(init.statusText))) { - throw new TypeError('Invalid statusText') - } - } - - // 3. Set response’s response’s status to init["status"]. - if ('status' in init && init.status != null) { - response[kState].status = init.status - } - - // 4. Set response’s response’s status message to init["statusText"]. - if ('statusText' in init && init.statusText != null) { - response[kState].statusText = init.statusText - } - - // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. - if ('headers' in init && init.headers != null) { - fill(response[kHeaders], init.headers) - } - - // 6. If body was given, then: - if (body) { - // 1. If response's status is a null body status, then throw a TypeError. - if (nullBodyStatus.includes(response.status)) { - throw webidl.errors.exception({ - header: 'Response constructor', - message: 'Invalid response status code ' + response.status - }) - } - - // 2. Set response's body to body's body. - response[kState].body = body.body - - // 3. If body's type is non-null and response's header list does not contain - // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. - if (body.type != null && !response[kState].headersList.contains('Content-Type')) { - response[kState].headersList.append('content-type', body.type) - } - } -} - -webidl.converters.ReadableStream = webidl.interfaceConverter( - ReadableStream -) - -webidl.converters.FormData = webidl.interfaceConverter( - FormData -) - -webidl.converters.URLSearchParams = webidl.interfaceConverter( - URLSearchParams -) - -// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit -webidl.converters.XMLHttpRequestBodyInit = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) - } - - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } - - if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { - return webidl.converters.BufferSource(V) - } - - if (util.isFormDataLike(V)) { - return webidl.converters.FormData(V, { strict: false }) - } - - if (V instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V) - } - - return webidl.converters.DOMString(V) -} - -// https://fetch.spec.whatwg.org/#bodyinit -webidl.converters.BodyInit = function (V) { - if (V instanceof ReadableStream) { - return webidl.converters.ReadableStream(V) - } - - // Note: the spec doesn't include async iterables, - // this is an undici extension. - if (V?.[Symbol.asyncIterator]) { - return V - } - - return webidl.converters.XMLHttpRequestBodyInit(V) -} - -webidl.converters.ResponseInit = webidl.dictionaryConverter([ - { - key: 'status', - converter: webidl.converters['unsigned short'], - defaultValue: 200 - }, - { - key: 'statusText', - converter: webidl.converters.ByteString, - defaultValue: '' - }, - { - key: 'headers', - converter: webidl.converters.HeadersInit - } -]) - -module.exports = { - makeNetworkError, - makeResponse, - makeAppropriateNetworkError, - filterResponse, - Response, - cloneResponse -} - - -/***/ }), - -/***/ 9710: -/***/ ((module) => { - - - -module.exports = { - kUrl: Symbol('url'), - kHeaders: Symbol('headers'), - kSignal: Symbol('signal'), - kState: Symbol('state'), - kGuard: Symbol('guard'), - kRealm: Symbol('realm') -} - - -/***/ }), - -/***/ 5523: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(7326) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { performance } = __nccwpck_require__(2987) -const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440) -const assert = __nccwpck_require__(2613) -const { isUint8Array } = __nccwpck_require__(8253) - -let supportedHashes = [] - -// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable -/** @type {import('crypto')|undefined} */ -let crypto - -try { - crypto = __nccwpck_require__(6982) - const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] - supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) -/* c8 ignore next 3 */ -} catch { -} - -function responseURL (response) { - // https://fetch.spec.whatwg.org/#responses - // A response has an associated URL. It is a pointer to the last URL - // in response’s URL list and null if response’s URL list is empty. - const urlList = response.urlList - const length = urlList.length - return length === 0 ? null : urlList[length - 1].toString() -} - -// https://fetch.spec.whatwg.org/#concept-response-location-url -function responseLocationURL (response, requestFragment) { - // 1. If response’s status is not a redirect status, then return null. - if (!redirectStatusSet.has(response.status)) { - return null - } - - // 2. Let location be the result of extracting header list values given - // `Location` and response’s header list. - let location = response.headersList.get('location') - - // 3. If location is a header value, then set location to the result of - // parsing location with response’s URL. - if (location !== null && isValidHeaderValue(location)) { - location = new URL(location, responseURL(response)) - } - - // 4. If location is a URL whose fragment is null, then set location’s - // fragment to requestFragment. - if (location && !location.hash) { - location.hash = requestFragment - } - - // 5. Return location. - return location -} - -/** @returns {URL} */ -function requestCurrentURL (request) { - return request.urlList[request.urlList.length - 1] -} - -function requestBadPort (request) { - // 1. Let url be request’s current URL. - const url = requestCurrentURL(request) - - // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, - // then return blocked. - if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { - return 'blocked' - } - - // 3. Return allowed. - return 'allowed' -} - -function isErrorLike (object) { - return object instanceof Error || ( - object?.constructor?.name === 'Error' || - object?.constructor?.name === 'DOMException' - ) -} - -// Check whether |statusText| is a ByteString and -// matches the Reason-Phrase token production. -// RFC 2616: https://tools.ietf.org/html/rfc2616 -// RFC 7230: https://tools.ietf.org/html/rfc7230 -// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" -// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 -function isValidReasonPhrase (statusText) { - for (let i = 0; i < statusText.length; ++i) { - const c = statusText.charCodeAt(i) - if ( - !( - ( - c === 0x09 || // HTAB - (c >= 0x20 && c <= 0x7e) || // SP / VCHAR - (c >= 0x80 && c <= 0xff) - ) // obs-text - ) - ) { - return false - } - } - return true -} - -/** - * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 - * @param {number} c - */ -function isTokenCharCode (c) { - switch (c) { - case 0x22: - case 0x28: - case 0x29: - case 0x2c: - case 0x2f: - case 0x3a: - case 0x3b: - case 0x3c: - case 0x3d: - case 0x3e: - case 0x3f: - case 0x40: - case 0x5b: - case 0x5c: - case 0x5d: - case 0x7b: - case 0x7d: - // DQUOTE and "(),/:;<=>?@[\]{}" - return false - default: - // VCHAR %x21-7E - return c >= 0x21 && c <= 0x7e - } -} - -/** - * @param {string} characters - */ -function isValidHTTPToken (characters) { - if (characters.length === 0) { - return false - } - for (let i = 0; i < characters.length; ++i) { - if (!isTokenCharCode(characters.charCodeAt(i))) { - return false - } - } - return true -} - -/** - * @see https://fetch.spec.whatwg.org/#header-name - * @param {string} potentialValue - */ -function isValidHeaderName (potentialValue) { - return isValidHTTPToken(potentialValue) -} - -/** - * @see https://fetch.spec.whatwg.org/#header-value - * @param {string} potentialValue - */ -function isValidHeaderValue (potentialValue) { - // - Has no leading or trailing HTTP tab or space bytes. - // - Contains no 0x00 (NUL) or HTTP newline bytes. - if ( - potentialValue.startsWith('\t') || - potentialValue.startsWith(' ') || - potentialValue.endsWith('\t') || - potentialValue.endsWith(' ') - ) { - return false - } - - if ( - potentialValue.includes('\0') || - potentialValue.includes('\r') || - potentialValue.includes('\n') - ) { - return false - } - - return true -} - -// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect -function setRequestReferrerPolicyOnRedirect (request, actualResponse) { - // Given a request request and a response actualResponse, this algorithm - // updates request’s referrer policy according to the Referrer-Policy - // header (if any) in actualResponse. - - // 1. Let policy be the result of executing § 8.1 Parse a referrer policy - // from a Referrer-Policy header on actualResponse. - - // 8.1 Parse a referrer policy from a Referrer-Policy header - // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. - const { headersList } = actualResponse - // 2. Let policy be the empty string. - // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. - // 4. Return policy. - const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') - - // Note: As the referrer-policy can contain multiple policies - // separated by comma, we need to loop through all of them - // and pick the first valid one. - // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy - let policy = '' - if (policyHeader.length > 0) { - // The right-most policy takes precedence. - // The left-most policy is the fallback. - for (let i = policyHeader.length; i !== 0; i--) { - const token = policyHeader[i - 1].trim() - if (referrerPolicyTokens.has(token)) { - policy = token - break - } - } - } - - // 2. If policy is not the empty string, then set request’s referrer policy to policy. - if (policy !== '') { - request.referrerPolicy = policy - } -} - -// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check -function crossOriginResourcePolicyCheck () { - // TODO - return 'allowed' -} - -// https://fetch.spec.whatwg.org/#concept-cors-check -function corsCheck () { - // TODO - return 'success' -} - -// https://fetch.spec.whatwg.org/#concept-tao-check -function TAOCheck () { - // TODO - return 'success' -} - -function appendFetchMetadata (httpRequest) { - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header - // TODO - - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header - - // 1. Assert: r’s url is a potentially trustworthy URL. - // TODO - - // 2. Let header be a Structured Header whose value is a token. - let header = null - - // 3. Set header’s value to r’s mode. - header = httpRequest.mode - - // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. - httpRequest.headersList.set('sec-fetch-mode', header) - - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header - // TODO - - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header - // TODO -} - -// https://fetch.spec.whatwg.org/#append-a-request-origin-header -function appendRequestOriginHeader (request) { - // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. - let serializedOrigin = request.origin - - // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. - if (request.responseTainting === 'cors' || request.mode === 'websocket') { - if (serializedOrigin) { - request.headersList.append('origin', serializedOrigin) - } - - // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: - } else if (request.method !== 'GET' && request.method !== 'HEAD') { - // 1. Switch on request’s referrer policy: - switch (request.referrerPolicy) { - case 'no-referrer': - // Set serializedOrigin to `null`. - serializedOrigin = null - break - case 'no-referrer-when-downgrade': - case 'strict-origin': - case 'strict-origin-when-cross-origin': - // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. - if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { - serializedOrigin = null - } - break - case 'same-origin': - // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. - if (!sameOrigin(request, requestCurrentURL(request))) { - serializedOrigin = null - } - break - default: - // Do nothing. - } - - if (serializedOrigin) { - // 2. Append (`Origin`, serializedOrigin) to request’s header list. - request.headersList.append('origin', serializedOrigin) - } - } -} - -function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { - // TODO - return performance.now() -} - -// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info -function createOpaqueTimingInfo (timingInfo) { - return { - startTime: timingInfo.startTime ?? 0, - redirectStartTime: 0, - redirectEndTime: 0, - postRedirectStartTime: timingInfo.startTime ?? 0, - finalServiceWorkerStartTime: 0, - finalNetworkResponseStartTime: 0, - finalNetworkRequestStartTime: 0, - endTime: 0, - encodedBodySize: 0, - decodedBodySize: 0, - finalConnectionTimingInfo: null - } -} - -// https://html.spec.whatwg.org/multipage/origin.html#policy-container -function makePolicyContainer () { - // Note: the fetch spec doesn't make use of embedder policy or CSP list - return { - referrerPolicy: 'strict-origin-when-cross-origin' - } -} - -// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container -function clonePolicyContainer (policyContainer) { - return { - referrerPolicy: policyContainer.referrerPolicy - } -} - -// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer -function determineRequestsReferrer (request) { - // 1. Let policy be request's referrer policy. - const policy = request.referrerPolicy - - // Note: policy cannot (shouldn't) be null or an empty string. - assert(policy) - - // 2. Let environment be request’s client. - - let referrerSource = null - - // 3. Switch on request’s referrer: - if (request.referrer === 'client') { - // Note: node isn't a browser and doesn't implement document/iframes, - // so we bypass this step and replace it with our own. - - const globalOrigin = getGlobalOrigin() - - if (!globalOrigin || globalOrigin.origin === 'null') { - return 'no-referrer' - } - - // note: we need to clone it as it's mutated - referrerSource = new URL(globalOrigin) - } else if (request.referrer instanceof URL) { - // Let referrerSource be request’s referrer. - referrerSource = request.referrer - } - - // 4. Let request’s referrerURL be the result of stripping referrerSource for - // use as a referrer. - let referrerURL = stripURLForReferrer(referrerSource) - - // 5. Let referrerOrigin be the result of stripping referrerSource for use as - // a referrer, with the origin-only flag set to true. - const referrerOrigin = stripURLForReferrer(referrerSource, true) - - // 6. If the result of serializing referrerURL is a string whose length is - // greater than 4096, set referrerURL to referrerOrigin. - if (referrerURL.toString().length > 4096) { - referrerURL = referrerOrigin - } - - const areSameOrigin = sameOrigin(request, referrerURL) - const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && - !isURLPotentiallyTrustworthy(request.url) - - // 8. Execute the switch statements corresponding to the value of policy: - switch (policy) { - case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) - case 'unsafe-url': return referrerURL - case 'same-origin': - return areSameOrigin ? referrerOrigin : 'no-referrer' - case 'origin-when-cross-origin': - return areSameOrigin ? referrerURL : referrerOrigin - case 'strict-origin-when-cross-origin': { - const currentURL = requestCurrentURL(request) - - // 1. If the origin of referrerURL and the origin of request’s current - // URL are the same, then return referrerURL. - if (sameOrigin(referrerURL, currentURL)) { - return referrerURL - } - - // 2. If referrerURL is a potentially trustworthy URL and request’s - // current URL is not a potentially trustworthy URL, then return no - // referrer. - if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { - return 'no-referrer' - } - - // 3. Return referrerOrigin. - return referrerOrigin - } - case 'strict-origin': // eslint-disable-line - /** - * 1. If referrerURL is a potentially trustworthy URL and - * request’s current URL is not a potentially trustworthy URL, - * then return no referrer. - * 2. Return referrerOrigin - */ - case 'no-referrer-when-downgrade': // eslint-disable-line - /** - * 1. If referrerURL is a potentially trustworthy URL and - * request’s current URL is not a potentially trustworthy URL, - * then return no referrer. - * 2. Return referrerOrigin - */ - - default: // eslint-disable-line - return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin - } -} - -/** - * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url - * @param {URL} url - * @param {boolean|undefined} originOnly - */ -function stripURLForReferrer (url, originOnly) { - // 1. Assert: url is a URL. - assert(url instanceof URL) - - // 2. If url’s scheme is a local scheme, then return no referrer. - if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { - return 'no-referrer' - } - - // 3. Set url’s username to the empty string. - url.username = '' - - // 4. Set url’s password to the empty string. - url.password = '' - - // 5. Set url’s fragment to null. - url.hash = '' - - // 6. If the origin-only flag is true, then: - if (originOnly) { - // 1. Set url’s path to « the empty string ». - url.pathname = '' - - // 2. Set url’s query to null. - url.search = '' - } - - // 7. Return url. - return url -} - -function isURLPotentiallyTrustworthy (url) { - if (!(url instanceof URL)) { - return false - } - - // If child of about, return true - if (url.href === 'about:blank' || url.href === 'about:srcdoc') { - return true - } - - // If scheme is data, return true - if (url.protocol === 'data:') return true - - // If file, return true - if (url.protocol === 'file:') return true - - return isOriginPotentiallyTrustworthy(url.origin) - - function isOriginPotentiallyTrustworthy (origin) { - // If origin is explicitly null, return false - if (origin == null || origin === 'null') return false - - const originAsURL = new URL(origin) - - // If secure, return true - if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { - return true - } - - // If localhost or variants, return true - if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || - (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || - (originAsURL.hostname.endsWith('.localhost'))) { - return true - } - - // If any other, return false - return false - } -} - -/** - * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist - * @param {Uint8Array} bytes - * @param {string} metadataList - */ -function bytesMatch (bytes, metadataList) { - // If node is not built with OpenSSL support, we cannot check - // a request's integrity, so allow it by default (the spec will - // allow requests if an invalid hash is given, as precedence). - /* istanbul ignore if: only if node is built with --without-ssl */ - if (crypto === undefined) { - return true - } - - // 1. Let parsedMetadata be the result of parsing metadataList. - const parsedMetadata = parseMetadata(metadataList) - - // 2. If parsedMetadata is no metadata, return true. - if (parsedMetadata === 'no metadata') { - return true - } - - // 3. If response is not eligible for integrity validation, return false. - // TODO - - // 4. If parsedMetadata is the empty set, return true. - if (parsedMetadata.length === 0) { - return true - } - - // 5. Let metadata be the result of getting the strongest - // metadata from parsedMetadata. - const strongest = getStrongestMetadata(parsedMetadata) - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) - - // 6. For each item in metadata: - for (const item of metadata) { - // 1. Let algorithm be the alg component of item. - const algorithm = item.algo - - // 2. Let expectedValue be the val component of item. - const expectedValue = item.hash - - // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e - // "be liberal with padding". This is annoying, and it's not even in the spec. - - // 3. Let actualValue be the result of applying algorithm to bytes. - let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') - - if (actualValue[actualValue.length - 1] === '=') { - if (actualValue[actualValue.length - 2] === '=') { - actualValue = actualValue.slice(0, -2) - } else { - actualValue = actualValue.slice(0, -1) - } - } - - // 4. If actualValue is a case-sensitive match for expectedValue, - // return true. - if (compareBase64Mixed(actualValue, expectedValue)) { - return true - } - } - - // 7. Return false. - return false -} - -// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options -// https://www.w3.org/TR/CSP2/#source-list-syntax -// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 -const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i - -/** - * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata - * @param {string} metadata - */ -function parseMetadata (metadata) { - // 1. Let result be the empty set. - /** @type {{ algo: string, hash: string }[]} */ - const result = [] - - // 2. Let empty be equal to true. - let empty = true - - // 3. For each token returned by splitting metadata on spaces: - for (const token of metadata.split(' ')) { - // 1. Set empty to false. - empty = false - - // 2. Parse token as a hash-with-options. - const parsedToken = parseHashWithOptions.exec(token) - - // 3. If token does not parse, continue to the next token. - if ( - parsedToken === null || - parsedToken.groups === undefined || - parsedToken.groups.algo === undefined - ) { - // Note: Chromium blocks the request at this point, but Firefox - // gives a warning that an invalid integrity was given. The - // correct behavior is to ignore these, and subsequently not - // check the integrity of the resource. - continue - } - - // 4. Let algorithm be the hash-algo component of token. - const algorithm = parsedToken.groups.algo.toLowerCase() - - // 5. If algorithm is a hash function recognized by the user - // agent, add the parsed token to result. - if (supportedHashes.includes(algorithm)) { - result.push(parsedToken.groups) - } - } - - // 4. Return no metadata if empty is true, otherwise return result. - if (empty === true) { - return 'no metadata' - } - - return result -} - -/** - * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList - */ -function getStrongestMetadata (metadataList) { - // Let algorithm be the algo component of the first item in metadataList. - // Can be sha256 - let algorithm = metadataList[0].algo - // If the algorithm is sha512, then it is the strongest - // and we can return immediately - if (algorithm[3] === '5') { - return algorithm - } - - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i] - // If the algorithm is sha512, then it is the strongest - // and we can break the loop immediately - if (metadata.algo[3] === '5') { - algorithm = 'sha512' - break - // If the algorithm is sha384, then a potential sha256 or sha384 is ignored - } else if (algorithm[3] === '3') { - continue - // algorithm is sha256, check if algorithm is sha384 and if so, set it as - // the strongest - } else if (metadata.algo[3] === '3') { - algorithm = 'sha384' - } - } - return algorithm -} - -function filterMetadataListByAlgorithm (metadataList, algorithm) { - if (metadataList.length === 1) { - return metadataList - } - - let pos = 0 - for (let i = 0; i < metadataList.length; ++i) { - if (metadataList[i].algo === algorithm) { - metadataList[pos++] = metadataList[i] - } - } - - metadataList.length = pos - - return metadataList -} - -/** - * Compares two base64 strings, allowing for base64url - * in the second string. - * -* @param {string} actualValue always base64 - * @param {string} expectedValue base64 or base64url - * @returns {boolean} - */ -function compareBase64Mixed (actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { - return false - } - for (let i = 0; i < actualValue.length; ++i) { - if (actualValue[i] !== expectedValue[i]) { - if ( - (actualValue[i] === '+' && expectedValue[i] === '-') || - (actualValue[i] === '/' && expectedValue[i] === '_') - ) { - continue - } - return false - } - } - - return true -} - -// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request -function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { - // TODO -} - -/** - * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} - * @param {URL} A - * @param {URL} B - */ -function sameOrigin (A, B) { - // 1. If A and B are the same opaque origin, then return true. - if (A.origin === B.origin && A.origin === 'null') { - return true - } - - // 2. If A and B are both tuple origins and their schemes, - // hosts, and port are identical, then return true. - if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { - return true - } - - // 3. Return false. - return false -} - -function createDeferredPromise () { - let res - let rej - const promise = new Promise((resolve, reject) => { - res = resolve - rej = reject - }) - - return { promise, resolve: res, reject: rej } -} - -function isAborted (fetchParams) { - return fetchParams.controller.state === 'aborted' -} - -function isCancelled (fetchParams) { - return fetchParams.controller.state === 'aborted' || - fetchParams.controller.state === 'terminated' -} - -const normalizeMethodRecord = { - delete: 'DELETE', - DELETE: 'DELETE', - get: 'GET', - GET: 'GET', - head: 'HEAD', - HEAD: 'HEAD', - options: 'OPTIONS', - OPTIONS: 'OPTIONS', - post: 'POST', - POST: 'POST', - put: 'PUT', - PUT: 'PUT' -} - -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizeMethodRecord, null) - -/** - * @see https://fetch.spec.whatwg.org/#concept-method-normalize - * @param {string} method - */ -function normalizeMethod (method) { - return normalizeMethodRecord[method.toLowerCase()] ?? method -} - -// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string -function serializeJavascriptValueToJSONString (value) { - // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). - const result = JSON.stringify(value) - - // 2. If result is undefined, then throw a TypeError. - if (result === undefined) { - throw new TypeError('Value is not JSON serializable') - } - - // 3. Assert: result is a string. - assert(typeof result === 'string') - - // 4. Return result. - return result -} - -// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object -const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) - -/** - * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object - * @param {() => unknown[]} iterator - * @param {string} name name of the instance - * @param {'key'|'value'|'key+value'} kind - */ -function makeIterator (iterator, name, kind) { - const object = { - index: 0, - kind, - target: iterator - } - - const i = { - next () { - // 1. Let interface be the interface for which the iterator prototype object exists. - - // 2. Let thisValue be the this value. - - // 3. Let object be ? ToObject(thisValue). - - // 4. If object is a platform object, then perform a security - // check, passing: - - // 5. If object is not a default iterator object for interface, - // then throw a TypeError. - if (Object.getPrototypeOf(this) !== i) { - throw new TypeError( - `'next' called on an object that does not implement interface ${name} Iterator.` - ) - } - - // 6. Let index be object’s index. - // 7. Let kind be object’s kind. - // 8. Let values be object’s target's value pairs to iterate over. - const { index, kind, target } = object - const values = target() - - // 9. Let len be the length of values. - const len = values.length - - // 10. If index is greater than or equal to len, then return - // CreateIterResultObject(undefined, true). - if (index >= len) { - return { value: undefined, done: true } - } - - // 11. Let pair be the entry in values at index index. - const pair = values[index] - - // 12. Set object’s index to index + 1. - object.index = index + 1 - - // 13. Return the iterator result for pair and kind. - return iteratorResult(pair, kind) - }, - // The class string of an iterator prototype object for a given interface is the - // result of concatenating the identifier of the interface and the string " Iterator". - [Symbol.toStringTag]: `${name} Iterator` - } - - // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. - Object.setPrototypeOf(i, esIteratorPrototype) - // esIteratorPrototype needs to be the prototype of i - // which is the prototype of an empty object. Yes, it's confusing. - return Object.setPrototypeOf({}, i) -} - -// https://webidl.spec.whatwg.org/#iterator-result -function iteratorResult (pair, kind) { - let result - - // 1. Let result be a value determined by the value of kind: - switch (kind) { - case 'key': { - // 1. Let idlKey be pair’s key. - // 2. Let key be the result of converting idlKey to an - // ECMAScript value. - // 3. result is key. - result = pair[0] - break - } - case 'value': { - // 1. Let idlValue be pair’s value. - // 2. Let value be the result of converting idlValue to - // an ECMAScript value. - // 3. result is value. - result = pair[1] - break - } - case 'key+value': { - // 1. Let idlKey be pair’s key. - // 2. Let idlValue be pair’s value. - // 3. Let key be the result of converting idlKey to an - // ECMAScript value. - // 4. Let value be the result of converting idlValue to - // an ECMAScript value. - // 5. Let array be ! ArrayCreate(2). - // 6. Call ! CreateDataProperty(array, "0", key). - // 7. Call ! CreateDataProperty(array, "1", value). - // 8. result is array. - result = pair - break - } - } - - // 2. Return CreateIterResultObject(result, false). - return { value: result, done: false } -} - -/** - * @see https://fetch.spec.whatwg.org/#body-fully-read - */ -async function fullyReadBody (body, processBody, processBodyError) { - // 1. If taskDestination is null, then set taskDestination to - // the result of starting a new parallel queue. - - // 2. Let successSteps given a byte sequence bytes be to queue a - // fetch task to run processBody given bytes, with taskDestination. - const successSteps = processBody - - // 3. Let errorSteps be to queue a fetch task to run processBodyError, - // with taskDestination. - const errorSteps = processBodyError - - // 4. Let reader be the result of getting a reader for body’s stream. - // If that threw an exception, then run errorSteps with that - // exception and return. - let reader - - try { - reader = body.stream.getReader() - } catch (e) { - errorSteps(e) - return - } - - // 5. Read all bytes from reader, given successSteps and errorSteps. - try { - const result = await readAllBytes(reader) - successSteps(result) - } catch (e) { - errorSteps(e) - } -} - -/** @type {ReadableStream} */ -let ReadableStream = globalThis.ReadableStream - -function isReadableStreamLike (stream) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - return stream instanceof ReadableStream || ( - stream[Symbol.toStringTag] === 'ReadableStream' && - typeof stream.tee === 'function' - ) -} - -const MAXIMUM_ARGUMENT_LENGTH = 65535 - -/** - * @see https://infra.spec.whatwg.org/#isomorphic-decode - * @param {number[]|Uint8Array} input - */ -function isomorphicDecode (input) { - // 1. To isomorphic decode a byte sequence input, return a string whose code point - // length is equal to input’s length and whose code points have the same values - // as the values of input’s bytes, in the same order. - - if (input.length < MAXIMUM_ARGUMENT_LENGTH) { - return String.fromCharCode(...input) - } - - return input.reduce((previous, current) => previous + String.fromCharCode(current), '') -} - -/** - * @param {ReadableStreamController} controller - */ -function readableStreamClose (controller) { - try { - controller.close() - } catch (err) { - // TODO: add comment explaining why this error occurs. - if (!err.message.includes('Controller is already closed')) { - throw err - } - } -} - -/** - * @see https://infra.spec.whatwg.org/#isomorphic-encode - * @param {string} input - */ -function isomorphicEncode (input) { - // 1. Assert: input contains no code points greater than U+00FF. - for (let i = 0; i < input.length; i++) { - assert(input.charCodeAt(i) <= 0xFF) - } - - // 2. Return a byte sequence whose length is equal to input’s code - // point length and whose bytes have the same values as the - // values of input’s code points, in the same order - return input -} - -/** - * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes - * @see https://streams.spec.whatwg.org/#read-loop - * @param {ReadableStreamDefaultReader} reader - */ -async function readAllBytes (reader) { - const bytes = [] - let byteLength = 0 - - while (true) { - const { done, value: chunk } = await reader.read() - - if (done) { - // 1. Call successSteps with bytes. - return Buffer.concat(bytes, byteLength) - } - - // 1. If chunk is not a Uint8Array object, call failureSteps - // with a TypeError and abort these steps. - if (!isUint8Array(chunk)) { - throw new TypeError('Received non-Uint8Array chunk') - } - - // 2. Append the bytes represented by chunk to bytes. - bytes.push(chunk) - byteLength += chunk.length - - // 3. Read-loop given reader, bytes, successSteps, and failureSteps. - } -} - -/** - * @see https://fetch.spec.whatwg.org/#is-local - * @param {URL} url - */ -function urlIsLocal (url) { - assert('protocol' in url) // ensure it's a url object - - const protocol = url.protocol - - return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' -} - -/** - * @param {string|URL} url - */ -function urlHasHttpsScheme (url) { - if (typeof url === 'string') { - return url.startsWith('https:') - } - - return url.protocol === 'https:' -} - -/** - * @see https://fetch.spec.whatwg.org/#http-scheme - * @param {URL} url - */ -function urlIsHttpHttpsScheme (url) { - assert('protocol' in url) // ensure it's a url object - - const protocol = url.protocol - - return protocol === 'http:' || protocol === 'https:' -} - -/** - * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. - */ -const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) - -module.exports = { - isAborted, - isCancelled, - createDeferredPromise, - ReadableStreamFrom, - toUSVString, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - coarsenedSharedCurrentTime, - determineRequestsReferrer, - makePolicyContainer, - clonePolicyContainer, - appendFetchMetadata, - appendRequestOriginHeader, - TAOCheck, - corsCheck, - crossOriginResourcePolicyCheck, - createOpaqueTimingInfo, - setRequestReferrerPolicyOnRedirect, - isValidHTTPToken, - requestBadPort, - requestCurrentURL, - responseURL, - responseLocationURL, - isBlobLike, - isURLPotentiallyTrustworthy, - isValidReasonPhrase, - sameOrigin, - normalizeMethod, - serializeJavascriptValueToJSONString, - makeIterator, - isValidHeaderName, - isValidHeaderValue, - hasOwn, - isErrorLike, - fullyReadBody, - bytesMatch, - isReadableStreamLike, - readableStreamClose, - isomorphicEncode, - isomorphicDecode, - urlIsLocal, - urlHasHttpsScheme, - urlIsHttpHttpsScheme, - readAllBytes, - normalizeMethodRecord, - parseMetadata -} - - -/***/ }), - -/***/ 4222: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { types } = __nccwpck_require__(9023) -const { hasOwn, toUSVString } = __nccwpck_require__(5523) - -/** @type {import('../../types/webidl').Webidl} */ -const webidl = {} -webidl.converters = {} -webidl.util = {} -webidl.errors = {} - -webidl.errors.exception = function (message) { - return new TypeError(`${message.header}: ${message.message}`) -} - -webidl.errors.conversionFailed = function (context) { - const plural = context.types.length === 1 ? '' : ' one of' - const message = - `${context.argument} could not be converted to` + - `${plural}: ${context.types.join(', ')}.` - - return webidl.errors.exception({ - header: context.prefix, - message - }) -} - -webidl.errors.invalidArgument = function (context) { - return webidl.errors.exception({ - header: context.prefix, - message: `"${context.value}" is an invalid ${context.type}.` - }) -} - -// https://webidl.spec.whatwg.org/#implements -webidl.brandCheck = function (V, I, opts = undefined) { - if (opts?.strict !== false && !(V instanceof I)) { - throw new TypeError('Illegal invocation') - } else { - return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] - } -} - -webidl.argumentLengthCheck = function ({ length }, min, ctx) { - if (length < min) { - throw webidl.errors.exception({ - message: `${min} argument${min !== 1 ? 's' : ''} required, ` + - `but${length ? ' only' : ''} ${length} found.`, - ...ctx - }) - } -} - -webidl.illegalConstructor = function () { - throw webidl.errors.exception({ - header: 'TypeError', - message: 'Illegal constructor' - }) -} - -// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values -webidl.util.Type = function (V) { - switch (typeof V) { - case 'undefined': return 'Undefined' - case 'boolean': return 'Boolean' - case 'string': return 'String' - case 'symbol': return 'Symbol' - case 'number': return 'Number' - case 'bigint': return 'BigInt' - case 'function': - case 'object': { - if (V === null) { - return 'Null' - } - - return 'Object' - } - } -} - -// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint -webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { - let upperBound - let lowerBound - - // 1. If bitLength is 64, then: - if (bitLength === 64) { - // 1. Let upperBound be 2^53 − 1. - upperBound = Math.pow(2, 53) - 1 - - // 2. If signedness is "unsigned", then let lowerBound be 0. - if (signedness === 'unsigned') { - lowerBound = 0 - } else { - // 3. Otherwise let lowerBound be −2^53 + 1. - lowerBound = Math.pow(-2, 53) + 1 - } - } else if (signedness === 'unsigned') { - // 2. Otherwise, if signedness is "unsigned", then: - - // 1. Let lowerBound be 0. - lowerBound = 0 - - // 2. Let upperBound be 2^bitLength − 1. - upperBound = Math.pow(2, bitLength) - 1 - } else { - // 3. Otherwise: - - // 1. Let lowerBound be -2^bitLength − 1. - lowerBound = Math.pow(-2, bitLength) - 1 - - // 2. Let upperBound be 2^bitLength − 1 − 1. - upperBound = Math.pow(2, bitLength - 1) - 1 - } - - // 4. Let x be ? ToNumber(V). - let x = Number(V) - - // 5. If x is −0, then set x to +0. - if (x === 0) { - x = 0 - } - - // 6. If the conversion is to an IDL type associated - // with the [EnforceRange] extended attribute, then: - if (opts.enforceRange === true) { - // 1. If x is NaN, +∞, or −∞, then throw a TypeError. - if ( - Number.isNaN(x) || - x === Number.POSITIVE_INFINITY || - x === Number.NEGATIVE_INFINITY - ) { - throw webidl.errors.exception({ - header: 'Integer conversion', - message: `Could not convert ${V} to an integer.` - }) - } - - // 2. Set x to IntegerPart(x). - x = webidl.util.IntegerPart(x) - - // 3. If x < lowerBound or x > upperBound, then - // throw a TypeError. - if (x < lowerBound || x > upperBound) { - throw webidl.errors.exception({ - header: 'Integer conversion', - message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` - }) - } - - // 4. Return x. - return x - } - - // 7. If x is not NaN and the conversion is to an IDL - // type associated with the [Clamp] extended - // attribute, then: - if (!Number.isNaN(x) && opts.clamp === true) { - // 1. Set x to min(max(x, lowerBound), upperBound). - x = Math.min(Math.max(x, lowerBound), upperBound) - - // 2. Round x to the nearest integer, choosing the - // even integer if it lies halfway between two, - // and choosing +0 rather than −0. - if (Math.floor(x) % 2 === 0) { - x = Math.floor(x) - } else { - x = Math.ceil(x) - } - - // 3. Return x. - return x - } - - // 8. If x is NaN, +0, +∞, or −∞, then return +0. - if ( - Number.isNaN(x) || - (x === 0 && Object.is(0, x)) || - x === Number.POSITIVE_INFINITY || - x === Number.NEGATIVE_INFINITY - ) { - return 0 - } - - // 9. Set x to IntegerPart(x). - x = webidl.util.IntegerPart(x) - - // 10. Set x to x modulo 2^bitLength. - x = x % Math.pow(2, bitLength) - - // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, - // then return x − 2^bitLength. - if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { - return x - Math.pow(2, bitLength) - } - - // 12. Otherwise, return x. - return x -} - -// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart -webidl.util.IntegerPart = function (n) { - // 1. Let r be floor(abs(n)). - const r = Math.floor(Math.abs(n)) - - // 2. If n < 0, then return -1 × r. - if (n < 0) { - return -1 * r - } - - // 3. Otherwise, return r. - return r -} - -// https://webidl.spec.whatwg.org/#es-sequence -webidl.sequenceConverter = function (converter) { - return (V) => { - // 1. If Type(V) is not Object, throw a TypeError. - if (webidl.util.Type(V) !== 'Object') { - throw webidl.errors.exception({ - header: 'Sequence', - message: `Value of type ${webidl.util.Type(V)} is not an Object.` - }) - } - - // 2. Let method be ? GetMethod(V, @@iterator). - /** @type {Generator} */ - const method = V?.[Symbol.iterator]?.() - const seq = [] - - // 3. If method is undefined, throw a TypeError. - if ( - method === undefined || - typeof method.next !== 'function' - ) { - throw webidl.errors.exception({ - header: 'Sequence', - message: 'Object is not an iterator.' - }) - } - - // https://webidl.spec.whatwg.org/#create-sequence-from-iterable - while (true) { - const { done, value } = method.next() - - if (done) { - break - } - - seq.push(converter(value)) - } - - return seq - } -} - -// https://webidl.spec.whatwg.org/#es-to-record -webidl.recordConverter = function (keyConverter, valueConverter) { - return (O) => { - // 1. If Type(O) is not Object, throw a TypeError. - if (webidl.util.Type(O) !== 'Object') { - throw webidl.errors.exception({ - header: 'Record', - message: `Value of type ${webidl.util.Type(O)} is not an Object.` - }) - } - - // 2. Let result be a new empty instance of record. - const result = {} - - if (!types.isProxy(O)) { - // Object.keys only returns enumerable properties - const keys = Object.keys(O) - - for (const key of keys) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) - - // 2. Let value be ? Get(O, key). - // 3. Let typedValue be value converted to an IDL value of type V. - const typedValue = valueConverter(O[key]) - - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } - - // 5. Return result. - return result - } - - // 3. Let keys be ? O.[[OwnPropertyKeys]](). - const keys = Reflect.ownKeys(O) - - // 4. For each key of keys. - for (const key of keys) { - // 1. Let desc be ? O.[[GetOwnProperty]](key). - const desc = Reflect.getOwnPropertyDescriptor(O, key) - - // 2. If desc is not undefined and desc.[[Enumerable]] is true: - if (desc?.enumerable) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) - - // 2. Let value be ? Get(O, key). - // 3. Let typedValue be value converted to an IDL value of type V. - const typedValue = valueConverter(O[key]) - - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } - } - - // 5. Return result. - return result - } -} - -webidl.interfaceConverter = function (i) { - return (V, opts = {}) => { - if (opts.strict !== false && !(V instanceof i)) { - throw webidl.errors.exception({ - header: i.name, - message: `Expected ${V} to be an instance of ${i.name}.` - }) - } - - return V - } -} - -webidl.dictionaryConverter = function (converters) { - return (dictionary) => { - const type = webidl.util.Type(dictionary) - const dict = {} - - if (type === 'Null' || type === 'Undefined') { - return dict - } else if (type !== 'Object') { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` - }) - } - - for (const options of converters) { - const { key, defaultValue, required, converter } = options - - if (required === true) { - if (!hasOwn(dictionary, key)) { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `Missing required key "${key}".` - }) - } - } - - let value = dictionary[key] - const hasDefault = hasOwn(options, 'defaultValue') - - // Only use defaultValue if value is undefined and - // a defaultValue options was provided. - if (hasDefault && value !== null) { - value = value ?? defaultValue - } - - // A key can be optional and have no default value. - // When this happens, do not perform a conversion, - // and do not assign the key a value. - if (required || hasDefault || value !== undefined) { - value = converter(value) - - if ( - options.allowedValues && - !options.allowedValues.includes(value) - ) { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` - }) - } - - dict[key] = value - } - } - - return dict - } -} - -webidl.nullableConverter = function (converter) { - return (V) => { - if (V === null) { - return V - } - - return converter(V) - } -} - -// https://webidl.spec.whatwg.org/#es-DOMString -webidl.converters.DOMString = function (V, opts = {}) { - // 1. If V is null and the conversion is to an IDL type - // associated with the [LegacyNullToEmptyString] - // extended attribute, then return the DOMString value - // that represents the empty string. - if (V === null && opts.legacyNullToEmptyString) { - return '' - } - - // 2. Let x be ? ToString(V). - if (typeof V === 'symbol') { - throw new TypeError('Could not convert argument of type symbol to string.') - } - - // 3. Return the IDL DOMString value that represents the - // same sequence of code units as the one the - // ECMAScript String value x represents. - return String(V) -} - -// https://webidl.spec.whatwg.org/#es-ByteString -webidl.converters.ByteString = function (V) { - // 1. Let x be ? ToString(V). - // Note: DOMString converter perform ? ToString(V) - const x = webidl.converters.DOMString(V) - - // 2. If the value of any element of x is greater than - // 255, then throw a TypeError. - for (let index = 0; index < x.length; index++) { - if (x.charCodeAt(index) > 255) { - throw new TypeError( - 'Cannot convert argument to a ByteString because the character at ' + - `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` - ) - } - } - - // 3. Return an IDL ByteString value whose length is the - // length of x, and where the value of each element is - // the value of the corresponding element of x. - return x -} - -// https://webidl.spec.whatwg.org/#es-USVString -webidl.converters.USVString = toUSVString - -// https://webidl.spec.whatwg.org/#es-boolean -webidl.converters.boolean = function (V) { - // 1. Let x be the result of computing ToBoolean(V). - const x = Boolean(V) - - // 2. Return the IDL boolean value that is the one that represents - // the same truth value as the ECMAScript Boolean value x. - return x -} - -// https://webidl.spec.whatwg.org/#es-any -webidl.converters.any = function (V) { - return V -} - -// https://webidl.spec.whatwg.org/#es-long-long -webidl.converters['long long'] = function (V) { - // 1. Let x be ? ConvertToInt(V, 64, "signed"). - const x = webidl.util.ConvertToInt(V, 64, 'signed') - - // 2. Return the IDL long long value that represents - // the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#es-unsigned-long-long -webidl.converters['unsigned long long'] = function (V) { - // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). - const x = webidl.util.ConvertToInt(V, 64, 'unsigned') - - // 2. Return the IDL unsigned long long value that - // represents the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#es-unsigned-long -webidl.converters['unsigned long'] = function (V) { - // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). - const x = webidl.util.ConvertToInt(V, 32, 'unsigned') - - // 2. Return the IDL unsigned long value that - // represents the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#es-unsigned-short -webidl.converters['unsigned short'] = function (V, opts) { - // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). - const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) - - // 2. Return the IDL unsigned short value that represents - // the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#idl-ArrayBuffer -webidl.converters.ArrayBuffer = function (V, opts = {}) { - // 1. If Type(V) is not Object, or V does not have an - // [[ArrayBufferData]] internal slot, then throw a - // TypeError. - // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances - // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances - if ( - webidl.util.Type(V) !== 'Object' || - !types.isAnyArrayBuffer(V) - ) { - throw webidl.errors.conversionFailed({ - prefix: `${V}`, - argument: `${V}`, - types: ['ArrayBuffer'] - }) - } - - // 2. If the conversion is not to an IDL type associated - // with the [AllowShared] extended attribute, and - // IsSharedArrayBuffer(V) is true, then throw a - // TypeError. - if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { - throw webidl.errors.exception({ - header: 'ArrayBuffer', - message: 'SharedArrayBuffer is not allowed.' - }) - } - - // 3. If the conversion is not to an IDL type associated - // with the [AllowResizable] extended attribute, and - // IsResizableArrayBuffer(V) is true, then throw a - // TypeError. - // Note: resizable ArrayBuffers are currently a proposal. - - // 4. Return the IDL ArrayBuffer value that is a - // reference to the same object as V. - return V -} - -webidl.converters.TypedArray = function (V, T, opts = {}) { - // 1. Let T be the IDL type V is being converted to. - - // 2. If Type(V) is not Object, or V does not have a - // [[TypedArrayName]] internal slot with a value - // equal to T’s name, then throw a TypeError. - if ( - webidl.util.Type(V) !== 'Object' || - !types.isTypedArray(V) || - V.constructor.name !== T.name - ) { - throw webidl.errors.conversionFailed({ - prefix: `${T.name}`, - argument: `${V}`, - types: [T.name] - }) - } - - // 3. If the conversion is not to an IDL type associated - // with the [AllowShared] extended attribute, and - // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is - // true, then throw a TypeError. - if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { - throw webidl.errors.exception({ - header: 'ArrayBuffer', - message: 'SharedArrayBuffer is not allowed.' - }) - } - - // 4. If the conversion is not to an IDL type associated - // with the [AllowResizable] extended attribute, and - // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is - // true, then throw a TypeError. - // Note: resizable array buffers are currently a proposal - - // 5. Return the IDL value of type T that is a reference - // to the same object as V. - return V -} - -webidl.converters.DataView = function (V, opts = {}) { - // 1. If Type(V) is not Object, or V does not have a - // [[DataView]] internal slot, then throw a TypeError. - if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { - throw webidl.errors.exception({ - header: 'DataView', - message: 'Object is not a DataView.' - }) - } - - // 2. If the conversion is not to an IDL type associated - // with the [AllowShared] extended attribute, and - // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, - // then throw a TypeError. - if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { - throw webidl.errors.exception({ - header: 'ArrayBuffer', - message: 'SharedArrayBuffer is not allowed.' - }) - } - - // 3. If the conversion is not to an IDL type associated - // with the [AllowResizable] extended attribute, and - // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is - // true, then throw a TypeError. - // Note: resizable ArrayBuffers are currently a proposal - - // 4. Return the IDL DataView value that is a reference - // to the same object as V. - return V -} - -// https://webidl.spec.whatwg.org/#BufferSource -webidl.converters.BufferSource = function (V, opts = {}) { - if (types.isAnyArrayBuffer(V)) { - return webidl.converters.ArrayBuffer(V, opts) - } - - if (types.isTypedArray(V)) { - return webidl.converters.TypedArray(V, V.constructor) - } - - if (types.isDataView(V)) { - return webidl.converters.DataView(V, opts) - } - - throw new TypeError(`Could not convert ${V} to a BufferSource.`) -} - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.ByteString -) - -webidl.converters['sequence>'] = webidl.sequenceConverter( - webidl.converters['sequence'] -) - -webidl.converters['record'] = webidl.recordConverter( - webidl.converters.ByteString, - webidl.converters.ByteString -) - -module.exports = { - webidl -} - - -/***/ }), - -/***/ 396: -/***/ ((module) => { - - - -/** - * @see https://encoding.spec.whatwg.org/#concept-encoding-get - * @param {string|undefined} label - */ -function getEncoding (label) { - if (!label) { - return 'failure' - } - - // 1. Remove any leading and trailing ASCII whitespace from label. - // 2. If label is an ASCII case-insensitive match for any of the - // labels listed in the table below, then return the - // corresponding encoding; otherwise return failure. - switch (label.trim().toLowerCase()) { - case 'unicode-1-1-utf-8': - case 'unicode11utf8': - case 'unicode20utf8': - case 'utf-8': - case 'utf8': - case 'x-unicode20utf8': - return 'UTF-8' - case '866': - case 'cp866': - case 'csibm866': - case 'ibm866': - return 'IBM866' - case 'csisolatin2': - case 'iso-8859-2': - case 'iso-ir-101': - case 'iso8859-2': - case 'iso88592': - case 'iso_8859-2': - case 'iso_8859-2:1987': - case 'l2': - case 'latin2': - return 'ISO-8859-2' - case 'csisolatin3': - case 'iso-8859-3': - case 'iso-ir-109': - case 'iso8859-3': - case 'iso88593': - case 'iso_8859-3': - case 'iso_8859-3:1988': - case 'l3': - case 'latin3': - return 'ISO-8859-3' - case 'csisolatin4': - case 'iso-8859-4': - case 'iso-ir-110': - case 'iso8859-4': - case 'iso88594': - case 'iso_8859-4': - case 'iso_8859-4:1988': - case 'l4': - case 'latin4': - return 'ISO-8859-4' - case 'csisolatincyrillic': - case 'cyrillic': - case 'iso-8859-5': - case 'iso-ir-144': - case 'iso8859-5': - case 'iso88595': - case 'iso_8859-5': - case 'iso_8859-5:1988': - return 'ISO-8859-5' - case 'arabic': - case 'asmo-708': - case 'csiso88596e': - case 'csiso88596i': - case 'csisolatinarabic': - case 'ecma-114': - case 'iso-8859-6': - case 'iso-8859-6-e': - case 'iso-8859-6-i': - case 'iso-ir-127': - case 'iso8859-6': - case 'iso88596': - case 'iso_8859-6': - case 'iso_8859-6:1987': - return 'ISO-8859-6' - case 'csisolatingreek': - case 'ecma-118': - case 'elot_928': - case 'greek': - case 'greek8': - case 'iso-8859-7': - case 'iso-ir-126': - case 'iso8859-7': - case 'iso88597': - case 'iso_8859-7': - case 'iso_8859-7:1987': - case 'sun_eu_greek': - return 'ISO-8859-7' - case 'csiso88598e': - case 'csisolatinhebrew': - case 'hebrew': - case 'iso-8859-8': - case 'iso-8859-8-e': - case 'iso-ir-138': - case 'iso8859-8': - case 'iso88598': - case 'iso_8859-8': - case 'iso_8859-8:1988': - case 'visual': - return 'ISO-8859-8' - case 'csiso88598i': - case 'iso-8859-8-i': - case 'logical': - return 'ISO-8859-8-I' - case 'csisolatin6': - case 'iso-8859-10': - case 'iso-ir-157': - case 'iso8859-10': - case 'iso885910': - case 'l6': - case 'latin6': - return 'ISO-8859-10' - case 'iso-8859-13': - case 'iso8859-13': - case 'iso885913': - return 'ISO-8859-13' - case 'iso-8859-14': - case 'iso8859-14': - case 'iso885914': - return 'ISO-8859-14' - case 'csisolatin9': - case 'iso-8859-15': - case 'iso8859-15': - case 'iso885915': - case 'iso_8859-15': - case 'l9': - return 'ISO-8859-15' - case 'iso-8859-16': - return 'ISO-8859-16' - case 'cskoi8r': - case 'koi': - case 'koi8': - case 'koi8-r': - case 'koi8_r': - return 'KOI8-R' - case 'koi8-ru': - case 'koi8-u': - return 'KOI8-U' - case 'csmacintosh': - case 'mac': - case 'macintosh': - case 'x-mac-roman': - return 'macintosh' - case 'iso-8859-11': - case 'iso8859-11': - case 'iso885911': - case 'tis-620': - case 'windows-874': - return 'windows-874' - case 'cp1250': - case 'windows-1250': - case 'x-cp1250': - return 'windows-1250' - case 'cp1251': - case 'windows-1251': - case 'x-cp1251': - return 'windows-1251' - case 'ansi_x3.4-1968': - case 'ascii': - case 'cp1252': - case 'cp819': - case 'csisolatin1': - case 'ibm819': - case 'iso-8859-1': - case 'iso-ir-100': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'iso_8859-1:1987': - case 'l1': - case 'latin1': - case 'us-ascii': - case 'windows-1252': - case 'x-cp1252': - return 'windows-1252' - case 'cp1253': - case 'windows-1253': - case 'x-cp1253': - return 'windows-1253' - case 'cp1254': - case 'csisolatin5': - case 'iso-8859-9': - case 'iso-ir-148': - case 'iso8859-9': - case 'iso88599': - case 'iso_8859-9': - case 'iso_8859-9:1989': - case 'l5': - case 'latin5': - case 'windows-1254': - case 'x-cp1254': - return 'windows-1254' - case 'cp1255': - case 'windows-1255': - case 'x-cp1255': - return 'windows-1255' - case 'cp1256': - case 'windows-1256': - case 'x-cp1256': - return 'windows-1256' - case 'cp1257': - case 'windows-1257': - case 'x-cp1257': - return 'windows-1257' - case 'cp1258': - case 'windows-1258': - case 'x-cp1258': - return 'windows-1258' - case 'x-mac-cyrillic': - case 'x-mac-ukrainian': - return 'x-mac-cyrillic' - case 'chinese': - case 'csgb2312': - case 'csiso58gb231280': - case 'gb2312': - case 'gb_2312': - case 'gb_2312-80': - case 'gbk': - case 'iso-ir-58': - case 'x-gbk': - return 'GBK' - case 'gb18030': - return 'gb18030' - case 'big5': - case 'big5-hkscs': - case 'cn-big5': - case 'csbig5': - case 'x-x-big5': - return 'Big5' - case 'cseucpkdfmtjapanese': - case 'euc-jp': - case 'x-euc-jp': - return 'EUC-JP' - case 'csiso2022jp': - case 'iso-2022-jp': - return 'ISO-2022-JP' - case 'csshiftjis': - case 'ms932': - case 'ms_kanji': - case 'shift-jis': - case 'shift_jis': - case 'sjis': - case 'windows-31j': - case 'x-sjis': - return 'Shift_JIS' - case 'cseuckr': - case 'csksc56011987': - case 'euc-kr': - case 'iso-ir-149': - case 'korean': - case 'ks_c_5601-1987': - case 'ks_c_5601-1989': - case 'ksc5601': - case 'ksc_5601': - case 'windows-949': - return 'EUC-KR' - case 'csiso2022kr': - case 'hz-gb-2312': - case 'iso-2022-cn': - case 'iso-2022-cn-ext': - case 'iso-2022-kr': - case 'replacement': - return 'replacement' - case 'unicodefffe': - case 'utf-16be': - return 'UTF-16BE' - case 'csunicode': - case 'iso-10646-ucs-2': - case 'ucs-2': - case 'unicode': - case 'unicodefeff': - case 'utf-16': - case 'utf-16le': - return 'UTF-16LE' - case 'x-user-defined': - return 'x-user-defined' - default: return 'failure' - } -} - -module.exports = { - getEncoding -} - - -/***/ }), - -/***/ 2160: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent -} = __nccwpck_require__(165) -const { - kState, - kError, - kResult, - kEvents, - kAborted -} = __nccwpck_require__(6812) -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) - -class FileReader extends EventTarget { - constructor () { - super() - - this[kState] = 'empty' - this[kResult] = null - this[kError] = null - this[kEvents] = { - loadend: null, - error: null, - abort: null, - load: null, - progress: null, - loadstart: null - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer - * @param {import('buffer').Blob} blob - */ - readAsArrayBuffer (blob) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - // The readAsArrayBuffer(blob) method, when invoked, - // must initiate a read operation for blob with ArrayBuffer. - readOperation(this, blob, 'ArrayBuffer') - } - - /** - * @see https://w3c.github.io/FileAPI/#readAsBinaryString - * @param {import('buffer').Blob} blob - */ - readAsBinaryString (blob) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - // The readAsBinaryString(blob) method, when invoked, - // must initiate a read operation for blob with BinaryString. - readOperation(this, blob, 'BinaryString') - } - - /** - * @see https://w3c.github.io/FileAPI/#readAsDataText - * @param {import('buffer').Blob} blob - * @param {string?} encoding - */ - readAsText (blob, encoding = undefined) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - if (encoding !== undefined) { - encoding = webidl.converters.DOMString(encoding) - } - - // The readAsText(blob, encoding) method, when invoked, - // must initiate a read operation for blob with Text and encoding. - readOperation(this, blob, 'Text', encoding) - } - - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL - * @param {import('buffer').Blob} blob - */ - readAsDataURL (blob) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - // The readAsDataURL(blob) method, when invoked, must - // initiate a read operation for blob with DataURL. - readOperation(this, blob, 'DataURL') - } - - /** - * @see https://w3c.github.io/FileAPI/#dfn-abort - */ - abort () { - // 1. If this's state is "empty" or if this's state is - // "done" set this's result to null and terminate - // this algorithm. - if (this[kState] === 'empty' || this[kState] === 'done') { - this[kResult] = null - return - } - - // 2. If this's state is "loading" set this's state to - // "done" and set this's result to null. - if (this[kState] === 'loading') { - this[kState] = 'done' - this[kResult] = null - } - - // 3. If there are any tasks from this on the file reading - // task source in an affiliated task queue, then remove - // those tasks from that task queue. - this[kAborted] = true - - // 4. Terminate the algorithm for the read method being processed. - // TODO - - // 5. Fire a progress event called abort at this. - fireAProgressEvent('abort', this) - - // 6. If this's state is not "loading", fire a progress - // event called loadend at this. - if (this[kState] !== 'loading') { - fireAProgressEvent('loadend', this) - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate - */ - get readyState () { - webidl.brandCheck(this, FileReader) - - switch (this[kState]) { - case 'empty': return this.EMPTY - case 'loading': return this.LOADING - case 'done': return this.DONE - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-result - */ - get result () { - webidl.brandCheck(this, FileReader) - - // The result attribute’s getter, when invoked, must return - // this's result. - return this[kResult] - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-error - */ - get error () { - webidl.brandCheck(this, FileReader) - - // The error attribute’s getter, when invoked, must return - // this's error. - return this[kError] - } - - get onloadend () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].loadend - } - - set onloadend (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].loadend) { - this.removeEventListener('loadend', this[kEvents].loadend) - } - - if (typeof fn === 'function') { - this[kEvents].loadend = fn - this.addEventListener('loadend', fn) - } else { - this[kEvents].loadend = null - } - } - - get onerror () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].error - } - - set onerror (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].error) { - this.removeEventListener('error', this[kEvents].error) - } - - if (typeof fn === 'function') { - this[kEvents].error = fn - this.addEventListener('error', fn) - } else { - this[kEvents].error = null - } - } - - get onloadstart () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].loadstart - } - - set onloadstart (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].loadstart) { - this.removeEventListener('loadstart', this[kEvents].loadstart) - } - - if (typeof fn === 'function') { - this[kEvents].loadstart = fn - this.addEventListener('loadstart', fn) - } else { - this[kEvents].loadstart = null - } - } - - get onprogress () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].progress - } - - set onprogress (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].progress) { - this.removeEventListener('progress', this[kEvents].progress) - } - - if (typeof fn === 'function') { - this[kEvents].progress = fn - this.addEventListener('progress', fn) - } else { - this[kEvents].progress = null - } - } - - get onload () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].load - } - - set onload (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].load) { - this.removeEventListener('load', this[kEvents].load) - } - - if (typeof fn === 'function') { - this[kEvents].load = fn - this.addEventListener('load', fn) - } else { - this[kEvents].load = null - } - } - - get onabort () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].abort - } - - set onabort (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].abort) { - this.removeEventListener('abort', this[kEvents].abort) - } - - if (typeof fn === 'function') { - this[kEvents].abort = fn - this.addEventListener('abort', fn) - } else { - this[kEvents].abort = null - } - } -} - -// https://w3c.github.io/FileAPI/#dom-filereader-empty -FileReader.EMPTY = FileReader.prototype.EMPTY = 0 -// https://w3c.github.io/FileAPI/#dom-filereader-loading -FileReader.LOADING = FileReader.prototype.LOADING = 1 -// https://w3c.github.io/FileAPI/#dom-filereader-done -FileReader.DONE = FileReader.prototype.DONE = 2 - -Object.defineProperties(FileReader.prototype, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors, - readAsArrayBuffer: kEnumerableProperty, - readAsBinaryString: kEnumerableProperty, - readAsText: kEnumerableProperty, - readAsDataURL: kEnumerableProperty, - abort: kEnumerableProperty, - readyState: kEnumerableProperty, - result: kEnumerableProperty, - error: kEnumerableProperty, - onloadstart: kEnumerableProperty, - onprogress: kEnumerableProperty, - onload: kEnumerableProperty, - onabort: kEnumerableProperty, - onerror: kEnumerableProperty, - onloadend: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'FileReader', - writable: false, - enumerable: false, - configurable: true - } -}) - -Object.defineProperties(FileReader, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors -}) - -module.exports = { - FileReader -} - - -/***/ }), - -/***/ 5976: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) - -const kState = Symbol('ProgressEvent state') - -/** - * @see https://xhr.spec.whatwg.org/#progressevent - */ -class ProgressEvent extends Event { - constructor (type, eventInitDict = {}) { - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) - - super(type, eventInitDict) - - this[kState] = { - lengthComputable: eventInitDict.lengthComputable, - loaded: eventInitDict.loaded, - total: eventInitDict.total - } - } - - get lengthComputable () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].lengthComputable - } - - get loaded () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].loaded - } - - get total () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].total - } -} - -webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ - { - key: 'lengthComputable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'loaded', - converter: webidl.converters['unsigned long long'], - defaultValue: 0 - }, - { - key: 'total', - converter: webidl.converters['unsigned long long'], - defaultValue: 0 - }, - { - key: 'bubbles', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'cancelable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'composed', - converter: webidl.converters.boolean, - defaultValue: false - } -]) - -module.exports = { - ProgressEvent -} - - -/***/ }), - -/***/ 6812: -/***/ ((module) => { - - - -module.exports = { - kState: Symbol('FileReader state'), - kResult: Symbol('FileReader result'), - kError: Symbol('FileReader error'), - kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), - kEvents: Symbol('FileReader events'), - kAborted: Symbol('FileReader aborted') -} - - -/***/ }), - -/***/ 165: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - kState, - kError, - kResult, - kAborted, - kLastProgressEventFired -} = __nccwpck_require__(6812) -const { ProgressEvent } = __nccwpck_require__(5976) -const { getEncoding } = __nccwpck_require__(396) -const { DOMException } = __nccwpck_require__(7326) -const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(4322) -const { types } = __nccwpck_require__(9023) -const { StringDecoder } = __nccwpck_require__(3193) -const { btoa } = __nccwpck_require__(181) - -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} - -/** - * @see https://w3c.github.io/FileAPI/#readOperation - * @param {import('./filereader').FileReader} fr - * @param {import('buffer').Blob} blob - * @param {string} type - * @param {string?} encodingName - */ -function readOperation (fr, blob, type, encodingName) { - // 1. If fr’s state is "loading", throw an InvalidStateError - // DOMException. - if (fr[kState] === 'loading') { - throw new DOMException('Invalid state', 'InvalidStateError') - } - - // 2. Set fr’s state to "loading". - fr[kState] = 'loading' - - // 3. Set fr’s result to null. - fr[kResult] = null - - // 4. Set fr’s error to null. - fr[kError] = null - - // 5. Let stream be the result of calling get stream on blob. - /** @type {import('stream/web').ReadableStream} */ - const stream = blob.stream() - - // 6. Let reader be the result of getting a reader from stream. - const reader = stream.getReader() - - // 7. Let bytes be an empty byte sequence. - /** @type {Uint8Array[]} */ - const bytes = [] - - // 8. Let chunkPromise be the result of reading a chunk from - // stream with reader. - let chunkPromise = reader.read() - - // 9. Let isFirstChunk be true. - let isFirstChunk = true - - // 10. In parallel, while true: - // Note: "In parallel" just means non-blocking - // Note 2: readOperation itself cannot be async as double - // reading the body would then reject the promise, instead - // of throwing an error. - ;(async () => { - while (!fr[kAborted]) { - // 1. Wait for chunkPromise to be fulfilled or rejected. - try { - const { done, value } = await chunkPromise - - // 2. If chunkPromise is fulfilled, and isFirstChunk is - // true, queue a task to fire a progress event called - // loadstart at fr. - if (isFirstChunk && !fr[kAborted]) { - queueMicrotask(() => { - fireAProgressEvent('loadstart', fr) - }) - } - - // 3. Set isFirstChunk to false. - isFirstChunk = false - - // 4. If chunkPromise is fulfilled with an object whose - // done property is false and whose value property is - // a Uint8Array object, run these steps: - if (!done && types.isUint8Array(value)) { - // 1. Let bs be the byte sequence represented by the - // Uint8Array object. - - // 2. Append bs to bytes. - bytes.push(value) - - // 3. If roughly 50ms have passed since these steps - // were last invoked, queue a task to fire a - // progress event called progress at fr. - if ( - ( - fr[kLastProgressEventFired] === undefined || - Date.now() - fr[kLastProgressEventFired] >= 50 - ) && - !fr[kAborted] - ) { - fr[kLastProgressEventFired] = Date.now() - queueMicrotask(() => { - fireAProgressEvent('progress', fr) - }) - } - - // 4. Set chunkPromise to the result of reading a - // chunk from stream with reader. - chunkPromise = reader.read() - } else if (done) { - // 5. Otherwise, if chunkPromise is fulfilled with an - // object whose done property is true, queue a task - // to run the following steps and abort this algorithm: - queueMicrotask(() => { - // 1. Set fr’s state to "done". - fr[kState] = 'done' - - // 2. Let result be the result of package data given - // bytes, type, blob’s type, and encodingName. - try { - const result = packageData(bytes, type, blob.type, encodingName) - - // 4. Else: - - if (fr[kAborted]) { - return - } - - // 1. Set fr’s result to result. - fr[kResult] = result - - // 2. Fire a progress event called load at the fr. - fireAProgressEvent('load', fr) - } catch (error) { - // 3. If package data threw an exception error: - - // 1. Set fr’s error to error. - fr[kError] = error - - // 2. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - } - - // 5. If fr’s state is not "loading", fire a progress - // event called loadend at the fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) - - break - } - } catch (error) { - if (fr[kAborted]) { - return - } - - // 6. Otherwise, if chunkPromise is rejected with an - // error error, queue a task to run the following - // steps and abort this algorithm: - queueMicrotask(() => { - // 1. Set fr’s state to "done". - fr[kState] = 'done' - - // 2. Set fr’s error to error. - fr[kError] = error - - // 3. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - - // 4. If fr’s state is not "loading", fire a progress - // event called loadend at fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) - - break - } - } - })() -} - -/** - * @see https://w3c.github.io/FileAPI/#fire-a-progress-event - * @see https://dom.spec.whatwg.org/#concept-event-fire - * @param {string} e The name of the event - * @param {import('./filereader').FileReader} reader - */ -function fireAProgressEvent (e, reader) { - // The progress event e does not bubble. e.bubbles must be false - // The progress event e is NOT cancelable. e.cancelable must be false - const event = new ProgressEvent(e, { - bubbles: false, - cancelable: false - }) - - reader.dispatchEvent(event) -} - -/** - * @see https://w3c.github.io/FileAPI/#blob-package-data - * @param {Uint8Array[]} bytes - * @param {string} type - * @param {string?} mimeType - * @param {string?} encodingName - */ -function packageData (bytes, type, mimeType, encodingName) { - // 1. A Blob has an associated package data algorithm, given - // bytes, a type, a optional mimeType, and a optional - // encodingName, which switches on type and runs the - // associated steps: - - switch (type) { - case 'DataURL': { - // 1. Return bytes as a DataURL [RFC2397] subject to - // the considerations below: - // * Use mimeType as part of the Data URL if it is - // available in keeping with the Data URL - // specification [RFC2397]. - // * If mimeType is not available return a Data URL - // without a media-type. [RFC2397]. - - // https://datatracker.ietf.org/doc/html/rfc2397#section-3 - // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data - // mediatype := [ type "/" subtype ] *( ";" parameter ) - // data := *urlchar - // parameter := attribute "=" value - let dataURL = 'data:' - - const parsed = parseMIMEType(mimeType || 'application/octet-stream') - - if (parsed !== 'failure') { - dataURL += serializeAMimeType(parsed) - } - - dataURL += ';base64,' - - const decoder = new StringDecoder('latin1') - - for (const chunk of bytes) { - dataURL += btoa(decoder.write(chunk)) - } - - dataURL += btoa(decoder.end()) - - return dataURL - } - case 'Text': { - // 1. Let encoding be failure - let encoding = 'failure' - - // 2. If the encodingName is present, set encoding to the - // result of getting an encoding from encodingName. - if (encodingName) { - encoding = getEncoding(encodingName) - } - - // 3. If encoding is failure, and mimeType is present: - if (encoding === 'failure' && mimeType) { - // 1. Let type be the result of parse a MIME type - // given mimeType. - const type = parseMIMEType(mimeType) - - // 2. If type is not failure, set encoding to the result - // of getting an encoding from type’s parameters["charset"]. - if (type !== 'failure') { - encoding = getEncoding(type.parameters.get('charset')) - } - } - - // 4. If encoding is failure, then set encoding to UTF-8. - if (encoding === 'failure') { - encoding = 'UTF-8' - } - - // 5. Decode bytes using fallback encoding encoding, and - // return the result. - return decode(bytes, encoding) - } - case 'ArrayBuffer': { - // Return a new ArrayBuffer whose contents are bytes. - const sequence = combineByteSequences(bytes) - - return sequence.buffer - } - case 'BinaryString': { - // Return bytes as a binary string, in which every byte - // is represented by a code unit of equal value [0..255]. - let binaryString = '' - - const decoder = new StringDecoder('latin1') - - for (const chunk of bytes) { - binaryString += decoder.write(chunk) - } - - binaryString += decoder.end() - - return binaryString - } - } -} - -/** - * @see https://encoding.spec.whatwg.org/#decode - * @param {Uint8Array[]} ioQueue - * @param {string} encoding - */ -function decode (ioQueue, encoding) { - const bytes = combineByteSequences(ioQueue) - - // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. - const BOMEncoding = BOMSniffing(bytes) - - let slice = 0 - - // 2. If BOMEncoding is non-null: - if (BOMEncoding !== null) { - // 1. Set encoding to BOMEncoding. - encoding = BOMEncoding - - // 2. Read three bytes from ioQueue, if BOMEncoding is - // UTF-8; otherwise read two bytes. - // (Do nothing with those bytes.) - slice = BOMEncoding === 'UTF-8' ? 3 : 2 - } - - // 3. Process a queue with an instance of encoding’s - // decoder, ioQueue, output, and "replacement". - - // 4. Return output. - - const sliced = bytes.slice(slice) - return new TextDecoder(encoding).decode(sliced) -} - -/** - * @see https://encoding.spec.whatwg.org/#bom-sniff - * @param {Uint8Array} ioQueue - */ -function BOMSniffing (ioQueue) { - // 1. Let BOM be the result of peeking 3 bytes from ioQueue, - // converted to a byte sequence. - const [a, b, c] = ioQueue - - // 2. For each of the rows in the table below, starting with - // the first one and going down, if BOM starts with the - // bytes given in the first column, then return the - // encoding given in the cell in the second column of that - // row. Otherwise, return null. - if (a === 0xEF && b === 0xBB && c === 0xBF) { - return 'UTF-8' - } else if (a === 0xFE && b === 0xFF) { - return 'UTF-16BE' - } else if (a === 0xFF && b === 0xFE) { - return 'UTF-16LE' - } - - return null -} - -/** - * @param {Uint8Array[]} sequences - */ -function combineByteSequences (sequences) { - const size = sequences.reduce((a, b) => { - return a + b.byteLength - }, 0) - - let offset = 0 - - return sequences.reduce((a, b) => { - a.set(b, offset) - offset += b.byteLength - return a - }, new Uint8Array(size)) -} - -module.exports = { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent -} - - -/***/ }), - -/***/ 2581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// We include a version number for the Dispatcher API. In case of breaking changes, -// this version number must be increased to avoid conflicts. -const globalDispatcher = Symbol.for('undici.globalDispatcher.1') -const { InvalidArgumentError } = __nccwpck_require__(8707) -const Agent = __nccwpck_require__(9965) - -if (getGlobalDispatcher() === undefined) { - setGlobalDispatcher(new Agent()) -} - -function setGlobalDispatcher (agent) { - if (!agent || typeof agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument agent must implement Agent') - } - Object.defineProperty(globalThis, globalDispatcher, { - value: agent, - writable: true, - enumerable: false, - configurable: false - }) -} - -function getGlobalDispatcher () { - return globalThis[globalDispatcher] -} - -module.exports = { - setGlobalDispatcher, - getGlobalDispatcher -} - - -/***/ }), - -/***/ 8840: -/***/ ((module) => { - - - -module.exports = class DecoratorHandler { - constructor (handler) { - this.handler = handler - } - - onConnect (...args) { - return this.handler.onConnect(...args) - } - - onError (...args) { - return this.handler.onError(...args) - } - - onUpgrade (...args) { - return this.handler.onUpgrade(...args) - } - - onHeaders (...args) { - return this.handler.onHeaders(...args) - } - - onData (...args) { - return this.handler.onData(...args) - } - - onComplete (...args) { - return this.handler.onComplete(...args) - } - - onBodySent (...args) { - return this.handler.onBodySent(...args) - } -} - - -/***/ }), - -/***/ 8299: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const util = __nccwpck_require__(3440) -const { kBodyUsed } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const EE = __nccwpck_require__(4434) - -const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] - -const kBody = Symbol('body') - -class BodyAsyncIterable { - constructor (body) { - this[kBody] = body - this[kBodyUsed] = false - } - - async * [Symbol.asyncIterator] () { - assert(!this[kBodyUsed], 'disturbed') - this[kBodyUsed] = true - yield * this[kBody] - } -} - -class RedirectHandler { - constructor (dispatch, maxRedirections, opts, handler) { - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } - - util.validateHandler(handler, opts.method, opts.upgrade) - - this.dispatch = dispatch - this.location = null - this.abort = null - this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy - this.maxRedirections = maxRedirections - this.handler = handler - this.history = [] - - if (util.isStream(this.opts.body)) { - // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp - // so that it can be dispatched again? - // TODO (fix): Do we need 100-expect support to provide a way to do this properly? - if (util.bodyLength(this.opts.body) === 0) { - this.opts.body - .on('data', function () { - assert(false) - }) - } - - if (typeof this.opts.body.readableDidRead !== 'boolean') { - this.opts.body[kBodyUsed] = false - EE.prototype.on.call(this.opts.body, 'data', function () { - this[kBodyUsed] = true - }) - } - } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { - // TODO (fix): We can't access ReadableStream internal state - // to determine whether or not it has been disturbed. This is just - // a workaround. - this.opts.body = new BodyAsyncIterable(this.opts.body) - } else if ( - this.opts.body && - typeof this.opts.body !== 'string' && - !ArrayBuffer.isView(this.opts.body) && - util.isIterable(this.opts.body) - ) { - // TODO: Should we allow re-using iterable if !this.opts.idempotent - // or through some other flag? - this.opts.body = new BodyAsyncIterable(this.opts.body) - } - } - - onConnect (abort) { - this.abort = abort - this.handler.onConnect(abort, { history: this.history }) - } - - onUpgrade (statusCode, headers, socket) { - this.handler.onUpgrade(statusCode, headers, socket) - } - - onError (error) { - this.handler.onError(error) - } - - onHeaders (statusCode, headers, resume, statusText) { - this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) - ? null - : parseLocation(statusCode, headers) - - if (this.opts.origin) { - this.history.push(new URL(this.opts.path, this.opts.origin)) - } - - if (!this.location) { - return this.handler.onHeaders(statusCode, headers, resume, statusText) - } - - const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) - const path = search ? `${pathname}${search}` : pathname - - // Remove headers referring to the original URL. - // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. - // https://tools.ietf.org/html/rfc7231#section-6.4 - this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) - this.opts.path = path - this.opts.origin = origin - this.opts.maxRedirections = 0 - this.opts.query = null - - // https://tools.ietf.org/html/rfc7231#section-6.4.4 - // In case of HTTP 303, always replace method to be either HEAD or GET - if (statusCode === 303 && this.opts.method !== 'HEAD') { - this.opts.method = 'GET' - this.opts.body = null - } - } - - onData (chunk) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 - - TLDR: undici always ignores 3xx response bodies. - - Redirection is used to serve the requested resource from another URL, so it is assumes that - no body is generated (and thus can be ignored). Even though generating a body is not prohibited. - - For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually - (which means it's optional and not mandated) contain just an hyperlink to the value of - the Location response header, so the body can be ignored safely. - - For status 300, which is "Multiple Choices", the spec mentions both generating a Location - response header AND a response body with the other possible location to follow. - Since the spec explicitily chooses not to specify a format for such body and leave it to - servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. - */ - } else { - return this.handler.onData(chunk) - } - } - - onComplete (trailers) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 - - TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections - and neither are useful if present. - - See comment on onData method above for more detailed informations. - */ - - this.location = null - this.abort = null - - this.dispatch(this.opts, this) - } else { - this.handler.onComplete(trailers) - } - } - - onBodySent (chunk) { - if (this.handler.onBodySent) { - this.handler.onBodySent(chunk) - } - } -} - -function parseLocation (statusCode, headers) { - if (redirectableStatusCodes.indexOf(statusCode) === -1) { - return null - } - - for (let i = 0; i < headers.length; i += 2) { - if (headers[i].toString().toLowerCase() === 'location') { - return headers[i + 1] - } - } -} - -// https://tools.ietf.org/html/rfc7231#section-6.4.4 -function shouldRemoveHeader (header, removeContent, unknownOrigin) { - if (header.length === 4) { - return util.headerNameToString(header) === 'host' - } - if (removeContent && util.headerNameToString(header).startsWith('content-')) { - return true - } - if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { - const name = util.headerNameToString(header) - return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' - } - return false -} - -// https://tools.ietf.org/html/rfc7231#section-6.4 -function cleanRequestHeaders (headers, removeContent, unknownOrigin) { - const ret = [] - if (Array.isArray(headers)) { - for (let i = 0; i < headers.length; i += 2) { - if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { - ret.push(headers[i], headers[i + 1]) - } - } - } else if (headers && typeof headers === 'object') { - for (const key of Object.keys(headers)) { - if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { - ret.push(key, headers[key]) - } - } - } else { - assert(headers == null, 'headers must be an object or an array') - } - return ret -} - -module.exports = RedirectHandler - - -/***/ }), - -/***/ 3573: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(2613) - -const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443) -const { RequestRetryError } = __nccwpck_require__(8707) -const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3440) - -function calculateRetryAfterHeader (retryAfter) { - const current = Date.now() - const diff = new Date(retryAfter).getTime() - current - - return diff -} - -class RetryHandler { - constructor (opts, handlers) { - const { retryOptions, ...dispatchOpts } = opts - const { - // Retry scoped - retry: retryFn, - maxRetries, - maxTimeout, - minTimeout, - timeoutFactor, - // Response scoped - methods, - errorCodes, - retryAfter, - statusCodes - } = retryOptions ?? {} - - this.dispatch = handlers.dispatch - this.handler = handlers.handler - this.opts = dispatchOpts - this.abort = null - this.aborted = false - this.retryOpts = { - retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], - retryAfter: retryAfter ?? true, - maxTimeout: maxTimeout ?? 30 * 1000, // 30s, - timeout: minTimeout ?? 500, // .5s - timeoutFactor: timeoutFactor ?? 2, - maxRetries: maxRetries ?? 5, - // What errors we should retry - methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], - // Indicates which errors to retry - statusCodes: statusCodes ?? [500, 502, 503, 504, 429], - // List of errors to retry - errorCodes: errorCodes ?? [ - 'ECONNRESET', - 'ECONNREFUSED', - 'ENOTFOUND', - 'ENETDOWN', - 'ENETUNREACH', - 'EHOSTDOWN', - 'EHOSTUNREACH', - 'EPIPE' - ] - } - - this.retryCount = 0 - this.start = 0 - this.end = null - this.etag = null - this.resume = null - - // Handle possible onConnect duplication - this.handler.onConnect(reason => { - this.aborted = true - if (this.abort) { - this.abort(reason) - } else { - this.reason = reason - } - }) - } - - onRequestSent () { - if (this.handler.onRequestSent) { - this.handler.onRequestSent() - } - } - - onUpgrade (statusCode, headers, socket) { - if (this.handler.onUpgrade) { - this.handler.onUpgrade(statusCode, headers, socket) - } - } - - onConnect (abort) { - if (this.aborted) { - abort(this.reason) - } else { - this.abort = abort - } - } - - onBodySent (chunk) { - if (this.handler.onBodySent) return this.handler.onBodySent(chunk) - } - - static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { - const { statusCode, code, headers } = err - const { method, retryOptions } = opts - const { - maxRetries, - timeout, - maxTimeout, - timeoutFactor, - statusCodes, - errorCodes, - methods - } = retryOptions - let { counter, currentTimeout } = state - - currentTimeout = - currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout - - // Any code that is not a Undici's originated and allowed to retry - if ( - code && - code !== 'UND_ERR_REQ_RETRY' && - code !== 'UND_ERR_SOCKET' && - !errorCodes.includes(code) - ) { - cb(err) - return - } - - // If a set of method are provided and the current method is not in the list - if (Array.isArray(methods) && !methods.includes(method)) { - cb(err) - return - } - - // If a set of status code are provided and the current status code is not in the list - if ( - statusCode != null && - Array.isArray(statusCodes) && - !statusCodes.includes(statusCode) - ) { - cb(err) - return - } - - // If we reached the max number of retries - if (counter > maxRetries) { - cb(err) - return - } - - let retryAfterHeader = headers != null && headers['retry-after'] - if (retryAfterHeader) { - retryAfterHeader = Number(retryAfterHeader) - retryAfterHeader = isNaN(retryAfterHeader) - ? calculateRetryAfterHeader(retryAfterHeader) - : retryAfterHeader * 1e3 // Retry-After is in seconds - } - - const retryTimeout = - retryAfterHeader > 0 - ? Math.min(retryAfterHeader, maxTimeout) - : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) - - state.currentTimeout = retryTimeout - - setTimeout(() => cb(null), retryTimeout) - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const headers = parseHeaders(rawHeaders) - - this.retryCount += 1 - - if (statusCode >= 300) { - this.abort( - new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - // Checkpoint for resume from where we left it - if (this.resume != null) { - this.resume = null - - if (statusCode !== 206) { - return true - } - - const contentRange = parseRangeHeader(headers['content-range']) - // If no content range - if (!contentRange) { - this.abort( - new RequestRetryError('Content-Range mismatch', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - // Let's start with a weak etag check - if (this.etag != null && this.etag !== headers.etag) { - this.abort( - new RequestRetryError('ETag mismatch', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - const { start, size, end = size } = contentRange - - assert(this.start === start, 'content-range mismatch') - assert(this.end == null || this.end === end, 'content-range mismatch') - - this.resume = resume - return true - } - - if (this.end == null) { - if (statusCode === 206) { - // First time we receive 206 - const range = parseRangeHeader(headers['content-range']) - - if (range == null) { - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - - const { start, size, end = size } = range - - assert( - start != null && Number.isFinite(start) && this.start !== start, - 'content-range mismatch' - ) - assert(Number.isFinite(start)) - assert( - end != null && Number.isFinite(end) && this.end !== end, - 'invalid content-length' - ) - - this.start = start - this.end = end - } - - // We make our best to checkpoint the body for further range headers - if (this.end == null) { - const contentLength = headers['content-length'] - this.end = contentLength != null ? Number(contentLength) : null - } - - assert(Number.isFinite(this.start)) - assert( - this.end == null || Number.isFinite(this.end), - 'invalid content-length' - ) - - this.resume = resume - this.etag = headers.etag != null ? headers.etag : null - - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - - const err = new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - - this.abort(err) - - return false - } - - onData (chunk) { - this.start += chunk.length - - return this.handler.onData(chunk) - } - - onComplete (rawTrailers) { - this.retryCount = 0 - return this.handler.onComplete(rawTrailers) - } - - onError (err) { - if (this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } - - this.retryOpts.retry( - err, - { - state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, - opts: { retryOptions: this.retryOpts, ...this.opts } - }, - onRetry.bind(this) - ) - - function onRetry (err) { - if (err != null || this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } - - if (this.start !== 0) { - this.opts = { - ...this.opts, - headers: { - ...this.opts.headers, - range: `bytes=${this.start}-${this.end ?? ''}` - } - } - } - - try { - this.dispatch(this.opts, this) - } catch (err) { - this.handler.onError(err) - } - } - } -} - -module.exports = RetryHandler - - -/***/ }), - -/***/ 4415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const RedirectHandler = __nccwpck_require__(8299) - -function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { - return (dispatch) => { - return function Intercept (opts, handler) { - const { maxRedirections = defaultMaxRedirections } = opts - - if (!maxRedirections) { - return dispatch(opts, handler) - } - - const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) - opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. - return dispatch(opts, redirectHandler) - } - } -} - -module.exports = createRedirectInterceptor - - -/***/ }), - -/***/ 2824: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; -const utils_1 = __nccwpck_require__(172); -// C headers -var ERROR; -(function (ERROR) { - ERROR[ERROR["OK"] = 0] = "OK"; - ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; - ERROR[ERROR["STRICT"] = 2] = "STRICT"; - ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; - ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; - ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; - ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; - ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; - ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; - ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; - ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; - ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; - ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; - ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; - ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; - ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; - ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; - ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; - ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; - ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; - ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; - ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; - ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; - ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; - ERROR[ERROR["USER"] = 24] = "USER"; -})(ERROR = exports.ERROR || (exports.ERROR = {})); -var TYPE; -(function (TYPE) { - TYPE[TYPE["BOTH"] = 0] = "BOTH"; - TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; - TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; -})(TYPE = exports.TYPE || (exports.TYPE = {})); -var FLAGS; -(function (FLAGS) { - FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; - FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; - FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; - FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; - FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; - FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; - FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; - FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; - // 1 << 8 is unused - FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; -})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); -var LENIENT_FLAGS; -(function (LENIENT_FLAGS) { - LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; - LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; - LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; -})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); -var METHODS; -(function (METHODS) { - METHODS[METHODS["DELETE"] = 0] = "DELETE"; - METHODS[METHODS["GET"] = 1] = "GET"; - METHODS[METHODS["HEAD"] = 2] = "HEAD"; - METHODS[METHODS["POST"] = 3] = "POST"; - METHODS[METHODS["PUT"] = 4] = "PUT"; - /* pathological */ - METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; - METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; - METHODS[METHODS["TRACE"] = 7] = "TRACE"; - /* WebDAV */ - METHODS[METHODS["COPY"] = 8] = "COPY"; - METHODS[METHODS["LOCK"] = 9] = "LOCK"; - METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; - METHODS[METHODS["MOVE"] = 11] = "MOVE"; - METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; - METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; - METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; - METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; - METHODS[METHODS["BIND"] = 16] = "BIND"; - METHODS[METHODS["REBIND"] = 17] = "REBIND"; - METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; - METHODS[METHODS["ACL"] = 19] = "ACL"; - /* subversion */ - METHODS[METHODS["REPORT"] = 20] = "REPORT"; - METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; - METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; - METHODS[METHODS["MERGE"] = 23] = "MERGE"; - /* upnp */ - METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; - METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; - METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; - METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; - /* RFC-5789 */ - METHODS[METHODS["PATCH"] = 28] = "PATCH"; - METHODS[METHODS["PURGE"] = 29] = "PURGE"; - /* CalDAV */ - METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; - /* RFC-2068, section 19.6.1.2 */ - METHODS[METHODS["LINK"] = 31] = "LINK"; - METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; - /* icecast */ - METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; - /* RFC-7540, section 11.6 */ - METHODS[METHODS["PRI"] = 34] = "PRI"; - /* RFC-2326 RTSP */ - METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; - METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; - METHODS[METHODS["SETUP"] = 37] = "SETUP"; - METHODS[METHODS["PLAY"] = 38] = "PLAY"; - METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; - METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; - METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; - METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; - METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; - METHODS[METHODS["RECORD"] = 44] = "RECORD"; - /* RAOP */ - METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; -})(METHODS = exports.METHODS || (exports.METHODS = {})); -exports.METHODS_HTTP = [ - METHODS.DELETE, - METHODS.GET, - METHODS.HEAD, - METHODS.POST, - METHODS.PUT, - METHODS.CONNECT, - METHODS.OPTIONS, - METHODS.TRACE, - METHODS.COPY, - METHODS.LOCK, - METHODS.MKCOL, - METHODS.MOVE, - METHODS.PROPFIND, - METHODS.PROPPATCH, - METHODS.SEARCH, - METHODS.UNLOCK, - METHODS.BIND, - METHODS.REBIND, - METHODS.UNBIND, - METHODS.ACL, - METHODS.REPORT, - METHODS.MKACTIVITY, - METHODS.CHECKOUT, - METHODS.MERGE, - METHODS['M-SEARCH'], - METHODS.NOTIFY, - METHODS.SUBSCRIBE, - METHODS.UNSUBSCRIBE, - METHODS.PATCH, - METHODS.PURGE, - METHODS.MKCALENDAR, - METHODS.LINK, - METHODS.UNLINK, - METHODS.PRI, - // TODO(indutny): should we allow it with HTTP? - METHODS.SOURCE, -]; -exports.METHODS_ICE = [ - METHODS.SOURCE, -]; -exports.METHODS_RTSP = [ - METHODS.OPTIONS, - METHODS.DESCRIBE, - METHODS.ANNOUNCE, - METHODS.SETUP, - METHODS.PLAY, - METHODS.PAUSE, - METHODS.TEARDOWN, - METHODS.GET_PARAMETER, - METHODS.SET_PARAMETER, - METHODS.REDIRECT, - METHODS.RECORD, - METHODS.FLUSH, - // For AirPlay - METHODS.GET, - METHODS.POST, -]; -exports.METHOD_MAP = utils_1.enumToMap(METHODS); -exports.H_METHOD_MAP = {}; -Object.keys(exports.METHOD_MAP).forEach((key) => { - if (/^H/.test(key)) { - exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; - } -}); -var FINISH; -(function (FINISH) { - FINISH[FINISH["SAFE"] = 0] = "SAFE"; - FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; - FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; -})(FINISH = exports.FINISH || (exports.FINISH = {})); -exports.ALPHA = []; -for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { - // Upper case - exports.ALPHA.push(String.fromCharCode(i)); - // Lower case - exports.ALPHA.push(String.fromCharCode(i + 0x20)); -} -exports.NUM_MAP = { - 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, - 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, -}; -exports.HEX_MAP = { - 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, - 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, - A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, - a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, -}; -exports.NUM = [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', -]; -exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); -exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; -exports.USERINFO_CHARS = exports.ALPHANUM - .concat(exports.MARK) - .concat(['%', ';', ':', '&', '=', '+', '$', ',']); -// TODO(indutny): use RFC -exports.STRICT_URL_CHAR = [ - '!', '"', '$', '%', '&', '\'', - '(', ')', '*', '+', ',', '-', '.', '/', - ':', ';', '<', '=', '>', - '@', '[', '\\', ']', '^', '_', - '`', - '{', '|', '}', '~', -].concat(exports.ALPHANUM); -exports.URL_CHAR = exports.STRICT_URL_CHAR - .concat(['\t', '\f']); -// All characters with 0x80 bit set to 1 -for (let i = 0x80; i <= 0xff; i++) { - exports.URL_CHAR.push(i); -} -exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); -/* Tokens as defined by rfc 2616. Also lowercases them. - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - */ -exports.STRICT_TOKEN = [ - '!', '#', '$', '%', '&', '\'', - '*', '+', '-', '.', - '^', '_', '`', - '|', '~', -].concat(exports.ALPHANUM); -exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); -/* - * Verify that a char is a valid visible (printable) US-ASCII - * character or %x80-FF - */ -exports.HEADER_CHARS = ['\t']; -for (let i = 32; i <= 255; i++) { - if (i !== 127) { - exports.HEADER_CHARS.push(i); - } -} -// ',' = \x44 -exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); -exports.MAJOR = exports.NUM_MAP; -exports.MINOR = exports.MAJOR; -var HEADER_STATE; -(function (HEADER_STATE) { - HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; - HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; - HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; - HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; - HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; - HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; - HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; - HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; - HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; -})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); -exports.SPECIAL_HEADERS = { - 'connection': HEADER_STATE.CONNECTION, - 'content-length': HEADER_STATE.CONTENT_LENGTH, - 'proxy-connection': HEADER_STATE.CONNECTION, - 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, - 'upgrade': HEADER_STATE.UPGRADE, -}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 3870: -/***/ ((module) => { - -module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJs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ADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkB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QAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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FCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAU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YWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' - - -/***/ }), - -/***/ 3434: -/***/ ((module) => { - -module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJs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IAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEB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QAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQID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YWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' - - -/***/ }), - -/***/ 172: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.enumToMap = void 0; -function enumToMap(obj) { - const res = {}; - Object.keys(obj).forEach((key) => { - const value = obj[key]; - if (typeof value === 'number') { - res[key] = value; - } - }); - return res; -} -exports.enumToMap = enumToMap; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 7501: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kClients } = __nccwpck_require__(6443) -const Agent = __nccwpck_require__(9965) -const { - kAgent, - kMockAgentSet, - kMockAgentGet, - kDispatches, - kIsMockActive, - kNetConnect, - kGetNetConnect, - kOptions, - kFactory -} = __nccwpck_require__(1117) -const MockClient = __nccwpck_require__(7365) -const MockPool = __nccwpck_require__(4004) -const { matchValue, buildMockOptions } = __nccwpck_require__(3397) -const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707) -const Dispatcher = __nccwpck_require__(992) -const Pluralizer = __nccwpck_require__(1529) -const PendingInterceptorsFormatter = __nccwpck_require__(6142) - -class FakeWeakRef { - constructor (value) { - this.value = value - } - - deref () { - return this.value - } -} - -class MockAgent extends Dispatcher { - constructor (opts) { - super(opts) - - this[kNetConnect] = true - this[kIsMockActive] = true - - // Instantiate Agent and encapsulate - if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } - const agent = opts && opts.agent ? opts.agent : new Agent(opts) - this[kAgent] = agent - - this[kClients] = agent[kClients] - this[kOptions] = buildMockOptions(opts) - } - - get (origin) { - let dispatcher = this[kMockAgentGet](origin) - - if (!dispatcher) { - dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) - } - return dispatcher - } - - dispatch (opts, handler) { - // Call MockAgent.get to perform additional setup before dispatching as normal - this.get(opts.origin) - return this[kAgent].dispatch(opts, handler) - } - - async close () { - await this[kAgent].close() - this[kClients].clear() - } - - deactivate () { - this[kIsMockActive] = false - } - - activate () { - this[kIsMockActive] = true - } - - enableNetConnect (matcher) { - if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { - if (Array.isArray(this[kNetConnect])) { - this[kNetConnect].push(matcher) - } else { - this[kNetConnect] = [matcher] - } - } else if (typeof matcher === 'undefined') { - this[kNetConnect] = true - } else { - throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') - } - } - - disableNetConnect () { - this[kNetConnect] = false - } - - // This is required to bypass issues caused by using global symbols - see: - // https://github.com/nodejs/undici/issues/1447 - get isMockActive () { - return this[kIsMockActive] - } - - [kMockAgentSet] (origin, dispatcher) { - this[kClients].set(origin, new FakeWeakRef(dispatcher)) - } - - [kFactory] (origin) { - const mockOptions = Object.assign({ agent: this }, this[kOptions]) - return this[kOptions] && this[kOptions].connections === 1 - ? new MockClient(origin, mockOptions) - : new MockPool(origin, mockOptions) - } - - [kMockAgentGet] (origin) { - // First check if we can immediately find it - const ref = this[kClients].get(origin) - if (ref) { - return ref.deref() - } - - // If the origin is not a string create a dummy parent pool and return to user - if (typeof origin !== 'string') { - const dispatcher = this[kFactory]('http://localhost:9999') - this[kMockAgentSet](origin, dispatcher) - return dispatcher - } - - // If we match, create a pool and assign the same dispatches - for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { - const nonExplicitDispatcher = nonExplicitRef.deref() - if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { - const dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) - dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] - return dispatcher - } - } - } - - [kGetNetConnect] () { - return this[kNetConnect] - } - - pendingInterceptors () { - const mockAgentClients = this[kClients] - - return Array.from(mockAgentClients.entries()) - .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) - .filter(({ pending }) => pending) - } - - assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { - const pending = this.pendingInterceptors() - - if (pending.length === 0) { - return - } - - const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) - - throw new UndiciError(` -${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: - -${pendingInterceptorsFormatter.format(pending)} -`.trim()) - } -} - -module.exports = MockAgent - - -/***/ }), - -/***/ 7365: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { promisify } = __nccwpck_require__(9023) -const Client = __nccwpck_require__(6197) -const { buildMockDispatch } = __nccwpck_require__(3397) -const { - kDispatches, - kMockAgent, - kClose, - kOriginalClose, - kOrigin, - kOriginalDispatch, - kConnected -} = __nccwpck_require__(1117) -const { MockInterceptor } = __nccwpck_require__(1511) -const Symbols = __nccwpck_require__(6443) -const { InvalidArgumentError } = __nccwpck_require__(8707) - -/** - * MockClient provides an API that extends the Client to influence the mockDispatches. - */ -class MockClient extends Client { - constructor (origin, opts) { - super(origin, opts) - - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } - - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) - - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] - } - - get [Symbols.kConnected] () { - return this[kConnected] - } - - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) - } - - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) - } -} - -module.exports = MockClient - - -/***/ }), - -/***/ 2429: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { UndiciError } = __nccwpck_require__(8707) - -class MockNotMatchedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, MockNotMatchedError) - this.name = 'MockNotMatchedError' - this.message = message || 'The request does not match any registered mock dispatches' - this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' - } -} - -module.exports = { - MockNotMatchedError -} - - -/***/ }), - -/***/ 1511: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397) -const { - kDispatches, - kDispatchKey, - kDefaultHeaders, - kDefaultTrailers, - kContentLength, - kMockDispatch -} = __nccwpck_require__(1117) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { buildURL } = __nccwpck_require__(3440) - -/** - * Defines the scope API for an interceptor reply - */ -class MockScope { - constructor (mockDispatch) { - this[kMockDispatch] = mockDispatch - } - - /** - * Delay a reply by a set amount in ms. - */ - delay (waitInMs) { - if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { - throw new InvalidArgumentError('waitInMs must be a valid integer > 0') - } - - this[kMockDispatch].delay = waitInMs - return this - } - - /** - * For a defined reply, never mark as consumed. - */ - persist () { - this[kMockDispatch].persist = true - return this - } - - /** - * Allow one to define a reply for a set amount of matching requests. - */ - times (repeatTimes) { - if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { - throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') - } - - this[kMockDispatch].times = repeatTimes - return this - } -} - -/** - * Defines an interceptor for a Mock - */ -class MockInterceptor { - constructor (opts, mockDispatches) { - if (typeof opts !== 'object') { - throw new InvalidArgumentError('opts must be an object') - } - if (typeof opts.path === 'undefined') { - throw new InvalidArgumentError('opts.path must be defined') - } - if (typeof opts.method === 'undefined') { - opts.method = 'GET' - } - // See https://github.com/nodejs/undici/issues/1245 - // As per RFC 3986, clients are not supposed to send URI - // fragments to servers when they retrieve a document, - if (typeof opts.path === 'string') { - if (opts.query) { - opts.path = buildURL(opts.path, opts.query) - } else { - // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 - const parsedURL = new URL(opts.path, 'data://') - opts.path = parsedURL.pathname + parsedURL.search - } - } - if (typeof opts.method === 'string') { - opts.method = opts.method.toUpperCase() - } - - this[kDispatchKey] = buildKey(opts) - this[kDispatches] = mockDispatches - this[kDefaultHeaders] = {} - this[kDefaultTrailers] = {} - this[kContentLength] = false - } - - createMockScopeDispatchData (statusCode, data, responseOptions = {}) { - const responseData = getResponseData(data) - const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} - const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } - const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } - - return { statusCode, data, headers, trailers } - } - - validateReplyParameters (statusCode, data, responseOptions) { - if (typeof statusCode === 'undefined') { - throw new InvalidArgumentError('statusCode must be defined') - } - if (typeof data === 'undefined') { - throw new InvalidArgumentError('data must be defined') - } - if (typeof responseOptions !== 'object') { - throw new InvalidArgumentError('responseOptions must be an object') - } - } - - /** - * Mock an undici request with a defined reply. - */ - reply (replyData) { - // Values of reply aren't available right now as they - // can only be available when the reply callback is invoked. - if (typeof replyData === 'function') { - // We'll first wrap the provided callback in another function, - // this function will properly resolve the data from the callback - // when invoked. - const wrappedDefaultsCallback = (opts) => { - // Our reply options callback contains the parameter for statusCode, data and options. - const resolvedData = replyData(opts) - - // Check if it is in the right format - if (typeof resolvedData !== 'object') { - throw new InvalidArgumentError('reply options callback must return an object') - } - - const { statusCode, data = '', responseOptions = {} } = resolvedData - this.validateReplyParameters(statusCode, data, responseOptions) - // Since the values can be obtained immediately we return them - // from this higher order function that will be resolved later. - return { - ...this.createMockScopeDispatchData(statusCode, data, responseOptions) - } - } - - // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) - return new MockScope(newMockDispatch) - } - - // We can have either one or three parameters, if we get here, - // we should have 1-3 parameters. So we spread the arguments of - // this function to obtain the parameters, since replyData will always - // just be the statusCode. - const [statusCode, data = '', responseOptions = {}] = [...arguments] - this.validateReplyParameters(statusCode, data, responseOptions) - - // Send in-already provided data like usual - const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) - return new MockScope(newMockDispatch) - } - - /** - * Mock an undici request with a defined error. - */ - replyWithError (error) { - if (typeof error === 'undefined') { - throw new InvalidArgumentError('error must be defined') - } - - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) - return new MockScope(newMockDispatch) - } - - /** - * Set default reply headers on the interceptor for subsequent replies - */ - defaultReplyHeaders (headers) { - if (typeof headers === 'undefined') { - throw new InvalidArgumentError('headers must be defined') - } - - this[kDefaultHeaders] = headers - return this - } - - /** - * Set default reply trailers on the interceptor for subsequent replies - */ - defaultReplyTrailers (trailers) { - if (typeof trailers === 'undefined') { - throw new InvalidArgumentError('trailers must be defined') - } - - this[kDefaultTrailers] = trailers - return this - } - - /** - * Set reply content length header for replies on the interceptor - */ - replyContentLength () { - this[kContentLength] = true - return this - } -} - -module.exports.MockInterceptor = MockInterceptor -module.exports.MockScope = MockScope - - -/***/ }), - -/***/ 4004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { promisify } = __nccwpck_require__(9023) -const Pool = __nccwpck_require__(5076) -const { buildMockDispatch } = __nccwpck_require__(3397) -const { - kDispatches, - kMockAgent, - kClose, - kOriginalClose, - kOrigin, - kOriginalDispatch, - kConnected -} = __nccwpck_require__(1117) -const { MockInterceptor } = __nccwpck_require__(1511) -const Symbols = __nccwpck_require__(6443) -const { InvalidArgumentError } = __nccwpck_require__(8707) - -/** - * MockPool provides an API that extends the Pool to influence the mockDispatches. - */ -class MockPool extends Pool { - constructor (origin, opts) { - super(origin, opts) - - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } - - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) - - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] - } - - get [Symbols.kConnected] () { - return this[kConnected] - } - - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) - } - - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) - } -} - -module.exports = MockPool - - -/***/ }), - -/***/ 1117: -/***/ ((module) => { - - - -module.exports = { - kAgent: Symbol('agent'), - kOptions: Symbol('options'), - kFactory: Symbol('factory'), - kDispatches: Symbol('dispatches'), - kDispatchKey: Symbol('dispatch key'), - kDefaultHeaders: Symbol('default headers'), - kDefaultTrailers: Symbol('default trailers'), - kContentLength: Symbol('content length'), - kMockAgent: Symbol('mock agent'), - kMockAgentSet: Symbol('mock agent set'), - kMockAgentGet: Symbol('mock agent get'), - kMockDispatch: Symbol('mock dispatch'), - kClose: Symbol('close'), - kOriginalClose: Symbol('original agent close'), - kOrigin: Symbol('origin'), - kIsMockActive: Symbol('is mock active'), - kNetConnect: Symbol('net connect'), - kGetNetConnect: Symbol('get net connect'), - kConnected: Symbol('connected') -} - - -/***/ }), - -/***/ 3397: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { MockNotMatchedError } = __nccwpck_require__(2429) -const { - kDispatches, - kMockAgent, - kOriginalDispatch, - kOrigin, - kGetNetConnect -} = __nccwpck_require__(1117) -const { buildURL, nop } = __nccwpck_require__(3440) -const { STATUS_CODES } = __nccwpck_require__(8611) -const { - types: { - isPromise - } -} = __nccwpck_require__(9023) - -function matchValue (match, value) { - if (typeof match === 'string') { - return match === value - } - if (match instanceof RegExp) { - return match.test(value) - } - if (typeof match === 'function') { - return match(value) === true - } - return false -} - -function lowerCaseEntries (headers) { - return Object.fromEntries( - Object.entries(headers).map(([headerName, headerValue]) => { - return [headerName.toLocaleLowerCase(), headerValue] - }) - ) -} - -/** - * @param {import('../../index').Headers|string[]|Record} headers - * @param {string} key - */ -function getHeaderByName (headers, key) { - if (Array.isArray(headers)) { - for (let i = 0; i < headers.length; i += 2) { - if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { - return headers[i + 1] - } - } - - return undefined - } else if (typeof headers.get === 'function') { - return headers.get(key) - } else { - return lowerCaseEntries(headers)[key.toLocaleLowerCase()] - } -} - -/** @param {string[]} headers */ -function buildHeadersFromArray (headers) { // fetch HeadersList - const clone = headers.slice() - const entries = [] - for (let index = 0; index < clone.length; index += 2) { - entries.push([clone[index], clone[index + 1]]) - } - return Object.fromEntries(entries) -} - -function matchHeaders (mockDispatch, headers) { - if (typeof mockDispatch.headers === 'function') { - if (Array.isArray(headers)) { // fetch HeadersList - headers = buildHeadersFromArray(headers) - } - return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) - } - if (typeof mockDispatch.headers === 'undefined') { - return true - } - if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { - return false - } - - for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { - const headerValue = getHeaderByName(headers, matchHeaderName) - - if (!matchValue(matchHeaderValue, headerValue)) { - return false - } - } - return true -} - -function safeUrl (path) { - if (typeof path !== 'string') { - return path - } - - const pathSegments = path.split('?') - - if (pathSegments.length !== 2) { - return path - } - - const qp = new URLSearchParams(pathSegments.pop()) - qp.sort() - return [...pathSegments, qp.toString()].join('?') -} - -function matchKey (mockDispatch, { path, method, body, headers }) { - const pathMatch = matchValue(mockDispatch.path, path) - const methodMatch = matchValue(mockDispatch.method, method) - const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true - const headersMatch = matchHeaders(mockDispatch, headers) - return pathMatch && methodMatch && bodyMatch && headersMatch -} - -function getResponseData (data) { - if (Buffer.isBuffer(data)) { - return data - } else if (typeof data === 'object') { - return JSON.stringify(data) - } else { - return data.toString() - } -} - -function getMockDispatch (mockDispatches, key) { - const basePath = key.query ? buildURL(key.path, key.query) : key.path - const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath - - // Match path - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) - } - - // Match method - matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) - } - - // Match body - matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) - } - - // Match headers - matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) - } - - return matchedMockDispatches[0] -} - -function addMockDispatch (mockDispatches, key, data) { - const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } - const replyData = typeof data === 'function' ? { callback: data } : { ...data } - const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } - mockDispatches.push(newMockDispatch) - return newMockDispatch -} - -function deleteMockDispatch (mockDispatches, key) { - const index = mockDispatches.findIndex(dispatch => { - if (!dispatch.consumed) { - return false - } - return matchKey(dispatch, key) - }) - if (index !== -1) { - mockDispatches.splice(index, 1) - } -} - -function buildKey (opts) { - const { path, method, body, headers, query } = opts - return { - path, - method, - body, - headers, - query - } -} - -function generateKeyValues (data) { - return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ - ...keyValuePairs, - Buffer.from(`${key}`), - Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) - ], []) -} - -/** - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status - * @param {number} statusCode - */ -function getStatusText (statusCode) { - return STATUS_CODES[statusCode] || 'unknown' -} - -async function getResponse (body) { - const buffers = [] - for await (const data of body) { - buffers.push(data) - } - return Buffer.concat(buffers).toString('utf8') -} - -/** - * Mock dispatch function used to simulate undici dispatches - */ -function mockDispatch (opts, handler) { - // Get mock dispatch from built key - const key = buildKey(opts) - const mockDispatch = getMockDispatch(this[kDispatches], key) - - mockDispatch.timesInvoked++ - - // Here's where we resolve a callback if a callback is present for the dispatch data. - if (mockDispatch.data.callback) { - mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } - } - - // Parse mockDispatch data - const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch - const { timesInvoked, times } = mockDispatch - - // If it's used up and not persistent, mark as consumed - mockDispatch.consumed = !persist && timesInvoked >= times - mockDispatch.pending = timesInvoked < times - - // If specified, trigger dispatch error - if (error !== null) { - deleteMockDispatch(this[kDispatches], key) - handler.onError(error) - return true - } - - // Handle the request with a delay if necessary - if (typeof delay === 'number' && delay > 0) { - setTimeout(() => { - handleReply(this[kDispatches]) - }, delay) - } else { - handleReply(this[kDispatches]) - } - - function handleReply (mockDispatches, _data = data) { - // fetch's HeadersList is a 1D string array - const optsHeaders = Array.isArray(opts.headers) - ? buildHeadersFromArray(opts.headers) - : opts.headers - const body = typeof _data === 'function' - ? _data({ ...opts, headers: optsHeaders }) - : _data - - // util.types.isPromise is likely needed for jest. - if (isPromise(body)) { - // If handleReply is asynchronous, throwing an error - // in the callback will reject the promise, rather than - // synchronously throw the error, which breaks some tests. - // Rather, we wait for the callback to resolve if it is a - // promise, and then re-run handleReply with the new body. - body.then((newData) => handleReply(mockDispatches, newData)) - return - } - - const responseData = getResponseData(body) - const responseHeaders = generateKeyValues(headers) - const responseTrailers = generateKeyValues(trailers) - - handler.abort = nop - handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) - handler.onData(Buffer.from(responseData)) - handler.onComplete(responseTrailers) - deleteMockDispatch(mockDispatches, key) - } - - function resume () {} - - return true -} - -function buildMockDispatch () { - const agent = this[kMockAgent] - const origin = this[kOrigin] - const originalDispatch = this[kOriginalDispatch] - - return function dispatch (opts, handler) { - if (agent.isMockActive) { - try { - mockDispatch.call(this, opts, handler) - } catch (error) { - if (error instanceof MockNotMatchedError) { - const netConnect = agent[kGetNetConnect]() - if (netConnect === false) { - throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) - } - if (checkNetConnect(netConnect, origin)) { - originalDispatch.call(this, opts, handler) - } else { - throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) - } - } else { - throw error - } - } - } else { - originalDispatch.call(this, opts, handler) - } - } -} - -function checkNetConnect (netConnect, origin) { - const url = new URL(origin) - if (netConnect === true) { - return true - } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { - return true - } - return false -} - -function buildMockOptions (opts) { - if (opts) { - const { agent, ...mockOptions } = opts - return mockOptions - } -} - -module.exports = { - getResponseData, - getMockDispatch, - addMockDispatch, - deleteMockDispatch, - buildKey, - generateKeyValues, - matchValue, - getResponse, - getStatusText, - mockDispatch, - buildMockDispatch, - checkNetConnect, - buildMockOptions, - getHeaderByName -} - - -/***/ }), - -/***/ 6142: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Transform } = __nccwpck_require__(2203) -const { Console } = __nccwpck_require__(4236) - -/** - * Gets the output of `console.table(…)` as a string. - */ -module.exports = class PendingInterceptorsFormatter { - constructor ({ disableColors } = {}) { - this.transform = new Transform({ - transform (chunk, _enc, cb) { - cb(null, chunk) - } - }) - - this.logger = new Console({ - stdout: this.transform, - inspectOptions: { - colors: !disableColors && !process.env.CI - } - }) - } - - format (pendingInterceptors) { - const withPrettyHeaders = pendingInterceptors.map( - ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ - Method: method, - Origin: origin, - Path: path, - 'Status code': statusCode, - Persistent: persist ? '✅' : '❌', - Invocations: timesInvoked, - Remaining: persist ? Infinity : times - timesInvoked - })) - - this.logger.table(withPrettyHeaders) - return this.transform.read().toString() - } -} - - -/***/ }), - -/***/ 1529: -/***/ ((module) => { - - - -const singulars = { - pronoun: 'it', - is: 'is', - was: 'was', - this: 'this' -} - -const plurals = { - pronoun: 'they', - is: 'are', - was: 'were', - this: 'these' -} - -module.exports = class Pluralizer { - constructor (singular, plural) { - this.singular = singular - this.plural = plural - } - - pluralize (count) { - const one = count === 1 - const keys = one ? singulars : plurals - const noun = one ? this.singular : this.plural - return { ...keys, count, noun } - } -} - - -/***/ }), - -/***/ 4869: -/***/ ((module) => { - -/* eslint-disable */ - - - -// Extracted from node/lib/internal/fixed_queue.js - -// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. -const kSize = 2048; -const kMask = kSize - 1; - -// The FixedQueue is implemented as a singly-linked list of fixed-size -// circular buffers. It looks something like this: -// -// head tail -// | | -// v v -// +-----------+ <-----\ +-----------+ <------\ +-----------+ -// | [null] | \----- | next | \------- | next | -// +-----------+ +-----------+ +-----------+ -// | item | <-- bottom | item | <-- bottom | [empty] | -// | item | | item | | [empty] | -// | item | | item | | [empty] | -// | item | | item | | [empty] | -// | item | | item | bottom --> | item | -// | item | | item | | item | -// | ... | | ... | | ... | -// | item | | item | | item | -// | item | | item | | item | -// | [empty] | <-- top | item | | item | -// | [empty] | | item | | item | -// | [empty] | | [empty] | <-- top top --> | [empty] | -// +-----------+ +-----------+ +-----------+ -// -// Or, if there is only one circular buffer, it looks something -// like either of these: -// -// head tail head tail -// | | | | -// v v v v -// +-----------+ +-----------+ -// | [null] | | [null] | -// +-----------+ +-----------+ -// | [empty] | | item | -// | [empty] | | item | -// | item | <-- bottom top --> | [empty] | -// | item | | [empty] | -// | [empty] | <-- top bottom --> | item | -// | [empty] | | item | -// +-----------+ +-----------+ -// -// Adding a value means moving `top` forward by one, removing means -// moving `bottom` forward by one. After reaching the end, the queue -// wraps around. -// -// When `top === bottom` the current queue is empty and when -// `top + 1 === bottom` it's full. This wastes a single space of storage -// but allows much quicker checks. - -class FixedCircularBuffer { - constructor() { - this.bottom = 0; - this.top = 0; - this.list = new Array(kSize); - this.next = null; - } - - isEmpty() { - return this.top === this.bottom; - } - - isFull() { - return ((this.top + 1) & kMask) === this.bottom; - } - - push(data) { - this.list[this.top] = data; - this.top = (this.top + 1) & kMask; - } - - shift() { - const nextItem = this.list[this.bottom]; - if (nextItem === undefined) - return null; - this.list[this.bottom] = undefined; - this.bottom = (this.bottom + 1) & kMask; - return nextItem; - } -} - -module.exports = class FixedQueue { - constructor() { - this.head = this.tail = new FixedCircularBuffer(); - } - - isEmpty() { - return this.head.isEmpty(); - } - - push(data) { - if (this.head.isFull()) { - // Head is full: Creates a new queue, sets the old queue's `.next` to it, - // and sets it as the new main queue. - this.head = this.head.next = new FixedCircularBuffer(); - } - this.head.push(data); - } - - shift() { - const tail = this.tail; - const next = tail.shift(); - if (tail.isEmpty() && tail.next !== null) { - // If there is another queue, it forms the new tail. - this.tail = tail.next; - } - return next; - } -}; - - -/***/ }), - -/***/ 8640: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const DispatcherBase = __nccwpck_require__(1) -const FixedQueue = __nccwpck_require__(4869) -const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443) -const PoolStats = __nccwpck_require__(4622) - -const kClients = Symbol('clients') -const kNeedDrain = Symbol('needDrain') -const kQueue = Symbol('queue') -const kClosedResolve = Symbol('closed resolve') -const kOnDrain = Symbol('onDrain') -const kOnConnect = Symbol('onConnect') -const kOnDisconnect = Symbol('onDisconnect') -const kOnConnectionError = Symbol('onConnectionError') -const kGetDispatcher = Symbol('get dispatcher') -const kAddClient = Symbol('add client') -const kRemoveClient = Symbol('remove client') -const kStats = Symbol('stats') - -class PoolBase extends DispatcherBase { - constructor () { - super() - - this[kQueue] = new FixedQueue() - this[kClients] = [] - this[kQueued] = 0 - - const pool = this - - this[kOnDrain] = function onDrain (origin, targets) { - const queue = pool[kQueue] - - let needDrain = false - - while (!needDrain) { - const item = queue.shift() - if (!item) { - break - } - pool[kQueued]-- - needDrain = !this.dispatch(item.opts, item.handler) - } - - this[kNeedDrain] = needDrain - - if (!this[kNeedDrain] && pool[kNeedDrain]) { - pool[kNeedDrain] = false - pool.emit('drain', origin, [pool, ...targets]) - } - - if (pool[kClosedResolve] && queue.isEmpty()) { - Promise - .all(pool[kClients].map(c => c.close())) - .then(pool[kClosedResolve]) - } - } - - this[kOnConnect] = (origin, targets) => { - pool.emit('connect', origin, [pool, ...targets]) - } - - this[kOnDisconnect] = (origin, targets, err) => { - pool.emit('disconnect', origin, [pool, ...targets], err) - } - - this[kOnConnectionError] = (origin, targets, err) => { - pool.emit('connectionError', origin, [pool, ...targets], err) - } - - this[kStats] = new PoolStats(this) - } - - get [kBusy] () { - return this[kNeedDrain] - } - - get [kConnected] () { - return this[kClients].filter(client => client[kConnected]).length - } - - get [kFree] () { - return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length - } - - get [kPending] () { - let ret = this[kQueued] - for (const { [kPending]: pending } of this[kClients]) { - ret += pending - } - return ret - } - - get [kRunning] () { - let ret = 0 - for (const { [kRunning]: running } of this[kClients]) { - ret += running - } - return ret - } - - get [kSize] () { - let ret = this[kQueued] - for (const { [kSize]: size } of this[kClients]) { - ret += size - } - return ret - } - - get stats () { - return this[kStats] - } - - async [kClose] () { - if (this[kQueue].isEmpty()) { - return Promise.all(this[kClients].map(c => c.close())) - } else { - return new Promise((resolve) => { - this[kClosedResolve] = resolve - }) - } - } - - async [kDestroy] (err) { - while (true) { - const item = this[kQueue].shift() - if (!item) { - break - } - item.handler.onError(err) - } - - return Promise.all(this[kClients].map(c => c.destroy(err))) - } - - [kDispatch] (opts, handler) { - const dispatcher = this[kGetDispatcher]() - - if (!dispatcher) { - this[kNeedDrain] = true - this[kQueue].push({ opts, handler }) - this[kQueued]++ - } else if (!dispatcher.dispatch(opts, handler)) { - dispatcher[kNeedDrain] = true - this[kNeedDrain] = !this[kGetDispatcher]() - } - - return !this[kNeedDrain] - } - - [kAddClient] (client) { - client - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) - - this[kClients].push(client) - - if (this[kNeedDrain]) { - process.nextTick(() => { - if (this[kNeedDrain]) { - this[kOnDrain](client[kUrl], [this, client]) - } - }) - } - - return this - } - - [kRemoveClient] (client) { - client.close(() => { - const idx = this[kClients].indexOf(client) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - }) - - this[kNeedDrain] = this[kClients].some(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - } -} - -module.exports = { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} - - -/***/ }), - -/***/ 4622: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443) -const kPool = Symbol('pool') - -class PoolStats { - constructor (pool) { - this[kPool] = pool - } - - get connected () { - return this[kPool][kConnected] - } - - get free () { - return this[kPool][kFree] - } - - get pending () { - return this[kPool][kPending] - } - - get queued () { - return this[kPool][kQueued] - } - - get running () { - return this[kPool][kRunning] - } - - get size () { - return this[kPool][kSize] - } -} - -module.exports = PoolStats - - -/***/ }), - -/***/ 5076: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kGetDispatcher -} = __nccwpck_require__(8640) -const Client = __nccwpck_require__(6197) -const { - InvalidArgumentError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { kUrl, kInterceptors } = __nccwpck_require__(6443) -const buildConnector = __nccwpck_require__(9136) - -const kOptions = Symbol('options') -const kConnections = Symbol('connections') -const kFactory = Symbol('factory') - -function defaultFactory (origin, opts) { - return new Client(origin, opts) -} - -class Pool extends PoolBase { - constructor (origin, { - connections, - factory = defaultFactory, - connect, - connectTimeout, - tls, - maxCachedSessions, - socketPath, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - allowH2, - ...options - } = {}) { - super() - - if (connections != null && (!Number.isFinite(connections) || connections < 0)) { - throw new InvalidArgumentError('invalid connections') - } - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } - - this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) - ? options.interceptors.Pool - : [] - this[kConnections] = connections || null - this[kUrl] = util.parseOrigin(origin) - this[kOptions] = { ...util.deepClone(options), connect, allowH2 } - this[kOptions].interceptors = options.interceptors - ? { ...options.interceptors } - : undefined - this[kFactory] = factory - - this.on('connectionError', (origin, targets, error) => { - // If a connection error occurs, we remove the client from the pool, - // and emit a connectionError event. They will not be re-used. - // Fixes https://github.com/nodejs/undici/issues/3895 - for (const target of targets) { - // Do not use kRemoveClient here, as it will close the client, - // but the client cannot be closed in this state. - const idx = this[kClients].indexOf(target) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - } - }) - } - - [kGetDispatcher] () { - let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) - - if (dispatcher) { - return dispatcher - } - - if (!this[kConnections] || this[kClients].length < this[kConnections]) { - dispatcher = this[kFactory](this[kUrl], this[kOptions]) - this[kAddClient](dispatcher) - } - - return dispatcher - } -} - -module.exports = Pool - - -/***/ }), - -/***/ 2720: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(6443) -const { URL } = __nccwpck_require__(7016) -const Agent = __nccwpck_require__(9965) -const Pool = __nccwpck_require__(5076) -const DispatcherBase = __nccwpck_require__(1) -const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) -const buildConnector = __nccwpck_require__(9136) - -const kAgent = Symbol('proxy agent') -const kClient = Symbol('proxy client') -const kProxyHeaders = Symbol('proxy headers') -const kRequestTls = Symbol('request tls settings') -const kProxyTls = Symbol('proxy tls settings') -const kConnectEndpoint = Symbol('connect endpoint function') - -function defaultProtocolPort (protocol) { - return protocol === 'https:' ? 443 : 80 -} - -function buildProxyOptions (opts) { - if (typeof opts === 'string') { - opts = { uri: opts } - } - - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') - } - - return { - uri: opts.uri, - protocol: opts.protocol || 'https' - } -} - -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} - -class ProxyAgent extends DispatcherBase { - constructor (opts) { - super(opts) - this[kProxy] = buildProxyOptions(opts) - this[kAgent] = new Agent(opts) - this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) - ? opts.interceptors.ProxyAgent - : [] - - if (typeof opts === 'string') { - opts = { uri: opts } - } - - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') - } - - const { clientFactory = defaultFactory } = opts - - if (typeof clientFactory !== 'function') { - throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') - } - - this[kRequestTls] = opts.requestTls - this[kProxyTls] = opts.proxyTls - this[kProxyHeaders] = opts.headers || {} - - const resolvedUrl = new URL(opts.uri) - const { origin, port, host, username, password } = resolvedUrl - - if (opts.auth && opts.token) { - throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') - } else if (opts.auth) { - /* @deprecated in favour of opts.token */ - this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` - } else if (opts.token) { - this[kProxyHeaders]['proxy-authorization'] = opts.token - } else if (username && password) { - this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` - } - - const connect = buildConnector({ ...opts.proxyTls }) - this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) - this[kClient] = clientFactory(resolvedUrl, { connect }) - this[kAgent] = new Agent({ - ...opts, - connect: async (opts, callback) => { - let requestedHost = opts.host - if (!opts.port) { - requestedHost += `:${defaultProtocolPort(opts.protocol)}` - } - try { - const { socket, statusCode } = await this[kClient].connect({ - origin, - port, - path: requestedHost, - signal: opts.signal, - headers: { - ...this[kProxyHeaders], - host - } - }) - if (statusCode !== 200) { - socket.on('error', () => {}).destroy() - callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) - } - if (opts.protocol !== 'https:') { - callback(null, socket) - return - } - let servername - if (this[kRequestTls]) { - servername = this[kRequestTls].servername - } else { - servername = opts.servername - } - this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) - } catch (err) { - callback(err) - } - } - }) - } - - dispatch (opts, handler) { - const { host } = new URL(opts.origin) - const headers = buildHeaders(opts.headers) - throwIfProxyAuthIsSent(headers) - return this[kAgent].dispatch( - { - ...opts, - headers: { - ...headers, - host - } - }, - handler - ) - } - - async [kClose] () { - await this[kAgent].close() - await this[kClient].close() - } - - async [kDestroy] () { - await this[kAgent].destroy() - await this[kClient].destroy() - } -} - -/** - * @param {string[] | Record} headers - * @returns {Record} - */ -function buildHeaders (headers) { - // When using undici.fetch, the headers list is stored - // as an array. - if (Array.isArray(headers)) { - /** @type {Record} */ - const headersPair = {} - - for (let i = 0; i < headers.length; i += 2) { - headersPair[headers[i]] = headers[i + 1] - } - - return headersPair - } - - return headers -} - -/** - * @param {Record} headers - * - * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers - * Nevertheless, it was changed and to avoid a security vulnerability by end users - * this check was created. - * It should be removed in the next major version for performance reasons - */ -function throwIfProxyAuthIsSent (headers) { - const existProxyAuth = headers && Object.keys(headers) - .find((key) => key.toLowerCase() === 'proxy-authorization') - if (existProxyAuth) { - throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') - } -} - -module.exports = ProxyAgent - - -/***/ }), - -/***/ 8804: -/***/ ((module) => { - - - -let fastNow = Date.now() -let fastNowTimeout - -const fastTimers = [] - -function onTimeout () { - fastNow = Date.now() - - let len = fastTimers.length - let idx = 0 - while (idx < len) { - const timer = fastTimers[idx] - - if (timer.state === 0) { - timer.state = fastNow + timer.delay - } else if (timer.state > 0 && fastNow >= timer.state) { - timer.state = -1 - timer.callback(timer.opaque) - } - - if (timer.state === -1) { - timer.state = -2 - if (idx !== len - 1) { - fastTimers[idx] = fastTimers.pop() - } else { - fastTimers.pop() - } - len -= 1 - } else { - idx += 1 - } - } - - if (fastTimers.length > 0) { - refreshTimeout() - } -} - -function refreshTimeout () { - if (fastNowTimeout && fastNowTimeout.refresh) { - fastNowTimeout.refresh() - } else { - clearTimeout(fastNowTimeout) - fastNowTimeout = setTimeout(onTimeout, 1e3) - if (fastNowTimeout.unref) { - fastNowTimeout.unref() - } - } -} - -class Timeout { - constructor (callback, delay, opaque) { - this.callback = callback - this.delay = delay - this.opaque = opaque - - // -2 not in timer list - // -1 in timer list but inactive - // 0 in timer list waiting for time - // > 0 in timer list waiting for time to expire - this.state = -2 - - this.refresh() - } - - refresh () { - if (this.state === -2) { - fastTimers.push(this) - if (!fastNowTimeout || fastTimers.length === 1) { - refreshTimeout() - } - } - - this.state = 0 - } - - clear () { - this.state = -1 - } -} - -module.exports = { - setTimeout (callback, delay, opaque) { - return delay < 1e3 - ? setTimeout(callback, delay, opaque) - : new Timeout(callback, delay, opaque) - }, - clearTimeout (timeout) { - if (timeout instanceof Timeout) { - timeout.clear() - } else { - clearTimeout(timeout) - } - } -} - - -/***/ }), - -/***/ 8550: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const diagnosticsChannel = __nccwpck_require__(1637) -const { uid, states } = __nccwpck_require__(5913) -const { - kReadyState, - kSentClose, - kByteParser, - kReceivedClose -} = __nccwpck_require__(2933) -const { fireEvent, failWebsocketConnection } = __nccwpck_require__(3574) -const { CloseEvent } = __nccwpck_require__(6255) -const { makeRequest } = __nccwpck_require__(5194) -const { fetching } = __nccwpck_require__(2315) -const { Headers } = __nccwpck_require__(6349) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { kHeadersList } = __nccwpck_require__(6443) - -const channels = {} -channels.open = diagnosticsChannel.channel('undici:websocket:open') -channels.close = diagnosticsChannel.channel('undici:websocket:close') -channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') - -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6982) -} catch { - -} - -/** - * @see https://websockets.spec.whatwg.org/#concept-websocket-establish - * @param {URL} url - * @param {string|string[]} protocols - * @param {import('./websocket').WebSocket} ws - * @param {(response: any) => void} onEstablish - * @param {Partial} options - */ -function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { - // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s - // scheme is "ws", and to "https" otherwise. - const requestURL = url - - requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' - - // 2. Let request be a new request, whose URL is requestURL, client is client, - // service-workers mode is "none", referrer is "no-referrer", mode is - // "websocket", credentials mode is "include", cache mode is "no-store" , - // and redirect mode is "error". - const request = makeRequest({ - urlList: [requestURL], - serviceWorkers: 'none', - referrer: 'no-referrer', - mode: 'websocket', - credentials: 'include', - cache: 'no-store', - redirect: 'error' - }) - - // Note: undici extension, allow setting custom headers. - if (options.headers) { - const headersList = new Headers(options.headers)[kHeadersList] - - request.headersList = headersList - } - - // 3. Append (`Upgrade`, `websocket`) to request’s header list. - // 4. Append (`Connection`, `Upgrade`) to request’s header list. - // Note: both of these are handled by undici currently. - // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 - - // 5. Let keyValue be a nonce consisting of a randomly selected - // 16-byte value that has been forgiving-base64-encoded and - // isomorphic encoded. - const keyValue = crypto.randomBytes(16).toString('base64') - - // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s - // header list. - request.headersList.append('sec-websocket-key', keyValue) - - // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s - // header list. - request.headersList.append('sec-websocket-version', '13') - - // 8. For each protocol in protocols, combine - // (`Sec-WebSocket-Protocol`, protocol) in request’s header - // list. - for (const protocol of protocols) { - request.headersList.append('sec-websocket-protocol', protocol) - } - - // 9. Let permessageDeflate be a user-agent defined - // "permessage-deflate" extension header value. - // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 - // TODO: enable once permessage-deflate is supported - const permessageDeflate = '' // 'permessage-deflate; 15' - - // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to - // request’s header list. - // request.headersList.append('sec-websocket-extensions', permessageDeflate) - - // 11. Fetch request with useParallelQueue set to true, and - // processResponse given response being these steps: - const controller = fetching({ - request, - useParallelQueue: true, - dispatcher: options.dispatcher ?? getGlobalDispatcher(), - processResponse (response) { - // 1. If response is a network error or its status is not 101, - // fail the WebSocket connection. - if (response.type === 'error' || response.status !== 101) { - failWebsocketConnection(ws, 'Received network error or non-101 status code.') - return - } - - // 2. If protocols is not the empty list and extracting header - // list values given `Sec-WebSocket-Protocol` and response’s - // header list results in null, failure, or the empty byte - // sequence, then fail the WebSocket connection. - if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { - failWebsocketConnection(ws, 'Server did not respond with sent protocols.') - return - } - - // 3. Follow the requirements stated step 2 to step 6, inclusive, - // of the last set of steps in section 4.1 of The WebSocket - // Protocol to validate response. This either results in fail - // the WebSocket connection or the WebSocket connection is - // established. - - // 2. If the response lacks an |Upgrade| header field or the |Upgrade| - // header field contains a value that is not an ASCII case- - // insensitive match for the value "websocket", the client MUST - // _Fail the WebSocket Connection_. - if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { - failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') - return - } - - // 3. If the response lacks a |Connection| header field or the - // |Connection| header field doesn't contain a token that is an - // ASCII case-insensitive match for the value "Upgrade", the client - // MUST _Fail the WebSocket Connection_. - if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { - failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') - return - } - - // 4. If the response lacks a |Sec-WebSocket-Accept| header field or - // the |Sec-WebSocket-Accept| contains a value other than the - // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- - // Key| (as a string, not base64-decoded) with the string "258EAFA5- - // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and - // trailing whitespace, the client MUST _Fail the WebSocket - // Connection_. - const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') - const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') - if (secWSAccept !== digest) { - failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') - return - } - - // 5. If the response includes a |Sec-WebSocket-Extensions| header - // field and this header field indicates the use of an extension - // that was not present in the client's handshake (the server has - // indicated an extension not requested by the client), the client - // MUST _Fail the WebSocket Connection_. (The parsing of this - // header field to determine which extensions are requested is - // discussed in Section 9.1.) - const secExtension = response.headersList.get('Sec-WebSocket-Extensions') - - if (secExtension !== null && secExtension !== permessageDeflate) { - failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') - return - } - - // 6. If the response includes a |Sec-WebSocket-Protocol| header field - // and this header field indicates the use of a subprotocol that was - // not present in the client's handshake (the server has indicated a - // subprotocol not requested by the client), the client MUST _Fail - // the WebSocket Connection_. - const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') - - if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { - failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') - return - } - - response.socket.on('data', onSocketData) - response.socket.on('close', onSocketClose) - response.socket.on('error', onSocketError) - - if (channels.open.hasSubscribers) { - channels.open.publish({ - address: response.socket.address(), - protocol: secProtocol, - extensions: secExtension - }) - } - - onEstablish(response) - } - }) - - return controller -} - -/** - * @param {Buffer} chunk - */ -function onSocketData (chunk) { - if (!this.ws[kByteParser].write(chunk)) { - this.pause() - } -} - -/** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 - */ -function onSocketClose () { - const { ws } = this - - // If the TCP connection was closed after the - // WebSocket closing handshake was completed, the WebSocket connection - // is said to have been closed _cleanly_. - const wasClean = ws[kSentClose] && ws[kReceivedClose] - - let code = 1005 - let reason = '' - - const result = ws[kByteParser].closingInfo - - if (result) { - code = result.code ?? 1005 - reason = result.reason - } else if (!ws[kSentClose]) { - // If _The WebSocket - // Connection is Closed_ and no Close control frame was received by the - // endpoint (such as could occur if the underlying transport connection - // is lost), _The WebSocket Connection Close Code_ is considered to be - // 1006. - code = 1006 - } - - // 1. Change the ready state to CLOSED (3). - ws[kReadyState] = states.CLOSED - - // 2. If the user agent was required to fail the WebSocket - // connection, or if the WebSocket connection was closed - // after being flagged as full, fire an event named error - // at the WebSocket object. - // TODO - - // 3. Fire an event named close at the WebSocket object, - // using CloseEvent, with the wasClean attribute - // initialized to true if the connection closed cleanly - // and false otherwise, the code attribute initialized to - // the WebSocket connection close code, and the reason - // attribute initialized to the result of applying UTF-8 - // decode without BOM to the WebSocket connection close - // reason. - fireEvent('close', ws, CloseEvent, { - wasClean, code, reason - }) - - if (channels.close.hasSubscribers) { - channels.close.publish({ - websocket: ws, - code, - reason - }) - } -} - -function onSocketError (error) { - const { ws } = this - - ws[kReadyState] = states.CLOSING - - if (channels.socketError.hasSubscribers) { - channels.socketError.publish(error) - } - - this.destroy() -} - -module.exports = { - establishWebSocketConnection -} - - -/***/ }), - -/***/ 5913: -/***/ ((module) => { - - - -// This is a Globally Unique Identifier unique used -// to validate that the endpoint accepts websocket -// connections. -// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 -const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' - -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} - -const states = { - CONNECTING: 0, - OPEN: 1, - CLOSING: 2, - CLOSED: 3 -} - -const opcodes = { - CONTINUATION: 0x0, - TEXT: 0x1, - BINARY: 0x2, - CLOSE: 0x8, - PING: 0x9, - PONG: 0xA -} - -const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 - -const parserStates = { - INFO: 0, - PAYLOADLENGTH_16: 2, - PAYLOADLENGTH_64: 3, - READ_DATA: 4 -} - -const emptyBuffer = Buffer.allocUnsafe(0) - -module.exports = { - uid, - staticPropertyDescriptors, - states, - opcodes, - maxUnsigned16Bit, - parserStates, - emptyBuffer -} - - -/***/ }), - -/***/ 6255: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const { MessagePort } = __nccwpck_require__(8167) - -/** - * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent - */ -class MessageEvent extends Event { - #eventInit - - constructor (type, eventInitDict = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) - - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.MessageEventInit(eventInitDict) - - super(type, eventInitDict) - - this.#eventInit = eventInitDict - } - - get data () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.data - } - - get origin () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.origin - } - - get lastEventId () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.lastEventId - } - - get source () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.source - } - - get ports () { - webidl.brandCheck(this, MessageEvent) - - if (!Object.isFrozen(this.#eventInit.ports)) { - Object.freeze(this.#eventInit.ports) - } - - return this.#eventInit.ports - } - - initMessageEvent ( - type, - bubbles = false, - cancelable = false, - data = null, - origin = '', - lastEventId = '', - source = null, - ports = [] - ) { - webidl.brandCheck(this, MessageEvent) - - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) - - return new MessageEvent(type, { - bubbles, cancelable, data, origin, lastEventId, source, ports - }) - } -} - -/** - * @see https://websockets.spec.whatwg.org/#the-closeevent-interface - */ -class CloseEvent extends Event { - #eventInit - - constructor (type, eventInitDict = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) - - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.CloseEventInit(eventInitDict) - - super(type, eventInitDict) - - this.#eventInit = eventInitDict - } - - get wasClean () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.wasClean - } - - get code () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.code - } - - get reason () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.reason - } -} - -// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface -class ErrorEvent extends Event { - #eventInit - - constructor (type, eventInitDict) { - webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) - - super(type, eventInitDict) - - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) - - this.#eventInit = eventInitDict - } - - get message () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.message - } - - get filename () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.filename - } - - get lineno () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.lineno - } - - get colno () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.colno - } - - get error () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.error - } -} - -Object.defineProperties(MessageEvent.prototype, { - [Symbol.toStringTag]: { - value: 'MessageEvent', - configurable: true - }, - data: kEnumerableProperty, - origin: kEnumerableProperty, - lastEventId: kEnumerableProperty, - source: kEnumerableProperty, - ports: kEnumerableProperty, - initMessageEvent: kEnumerableProperty -}) - -Object.defineProperties(CloseEvent.prototype, { - [Symbol.toStringTag]: { - value: 'CloseEvent', - configurable: true - }, - reason: kEnumerableProperty, - code: kEnumerableProperty, - wasClean: kEnumerableProperty -}) - -Object.defineProperties(ErrorEvent.prototype, { - [Symbol.toStringTag]: { - value: 'ErrorEvent', - configurable: true - }, - message: kEnumerableProperty, - filename: kEnumerableProperty, - lineno: kEnumerableProperty, - colno: kEnumerableProperty, - error: kEnumerableProperty -}) - -webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.MessagePort -) - -const eventInit = [ - { - key: 'bubbles', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'cancelable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'composed', - converter: webidl.converters.boolean, - defaultValue: false - } -] - -webidl.converters.MessageEventInit = webidl.dictionaryConverter([ - ...eventInit, - { - key: 'data', - converter: webidl.converters.any, - defaultValue: null - }, - { - key: 'origin', - converter: webidl.converters.USVString, - defaultValue: '' - }, - { - key: 'lastEventId', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'source', - // Node doesn't implement WindowProxy or ServiceWorker, so the only - // valid value for source is a MessagePort. - converter: webidl.nullableConverter(webidl.converters.MessagePort), - defaultValue: null - }, - { - key: 'ports', - converter: webidl.converters['sequence'], - get defaultValue () { - return [] - } - } -]) - -webidl.converters.CloseEventInit = webidl.dictionaryConverter([ - ...eventInit, - { - key: 'wasClean', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'code', - converter: webidl.converters['unsigned short'], - defaultValue: 0 - }, - { - key: 'reason', - converter: webidl.converters.USVString, - defaultValue: '' - } -]) - -webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ - ...eventInit, - { - key: 'message', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'filename', - converter: webidl.converters.USVString, - defaultValue: '' - }, - { - key: 'lineno', - converter: webidl.converters['unsigned long'], - defaultValue: 0 - }, - { - key: 'colno', - converter: webidl.converters['unsigned long'], - defaultValue: 0 - }, - { - key: 'error', - converter: webidl.converters.any - } -]) - -module.exports = { - MessageEvent, - CloseEvent, - ErrorEvent -} - - -/***/ }), - -/***/ 1237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { maxUnsigned16Bit } = __nccwpck_require__(5913) - -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6982) -} catch { - -} - -class WebsocketFrameSend { - /** - * @param {Buffer|undefined} data - */ - constructor (data) { - this.frameData = data - this.maskKey = crypto.randomBytes(4) - } - - createFrame (opcode) { - const bodyLength = this.frameData?.byteLength ?? 0 - - /** @type {number} */ - let payloadLength = bodyLength // 0-125 - let offset = 6 - - if (bodyLength > maxUnsigned16Bit) { - offset += 8 // payload length is next 8 bytes - payloadLength = 127 - } else if (bodyLength > 125) { - offset += 2 // payload length is next 2 bytes - payloadLength = 126 - } - - const buffer = Buffer.allocUnsafe(bodyLength + offset) - - // Clear first 2 bytes, everything else is overwritten - buffer[0] = buffer[1] = 0 - buffer[0] |= 0x80 // FIN - buffer[0] = (buffer[0] & 0xF0) + opcode // opcode - - /*! ws. MIT License. Einar Otto Stangvik */ - buffer[offset - 4] = this.maskKey[0] - buffer[offset - 3] = this.maskKey[1] - buffer[offset - 2] = this.maskKey[2] - buffer[offset - 1] = this.maskKey[3] - - buffer[1] = payloadLength - - if (payloadLength === 126) { - buffer.writeUInt16BE(bodyLength, 2) - } else if (payloadLength === 127) { - // Clear extended payload length - buffer[2] = buffer[3] = 0 - buffer.writeUIntBE(bodyLength, 4, 6) - } - - buffer[1] |= 0x80 // MASK - - // mask body - for (let i = 0; i < bodyLength; i++) { - buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] - } - - return buffer - } -} - -module.exports = { - WebsocketFrameSend -} - - -/***/ }), - -/***/ 3171: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Writable } = __nccwpck_require__(2203) -const diagnosticsChannel = __nccwpck_require__(1637) -const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(5913) -const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(2933) -const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(3574) -const { WebsocketFrameSend } = __nccwpck_require__(1237) - -// This code was influenced by ws released under the MIT license. -// Copyright (c) 2011 Einar Otto Stangvik -// Copyright (c) 2013 Arnout Kazemier and contributors -// Copyright (c) 2016 Luigi Pinca and contributors - -const channels = {} -channels.ping = diagnosticsChannel.channel('undici:websocket:ping') -channels.pong = diagnosticsChannel.channel('undici:websocket:pong') - -class ByteParser extends Writable { - #buffers = [] - #byteOffset = 0 - - #state = parserStates.INFO - - #info = {} - #fragments = [] - - constructor (ws) { - super() - - this.ws = ws - } - - /** - * @param {Buffer} chunk - * @param {() => void} callback - */ - _write (chunk, _, callback) { - this.#buffers.push(chunk) - this.#byteOffset += chunk.length - - this.run(callback) - } - - /** - * Runs whenever a new chunk is received. - * Callback is called whenever there are no more chunks buffering, - * or not enough bytes are buffered to parse. - */ - run (callback) { - while (true) { - if (this.#state === parserStates.INFO) { - // If there aren't enough bytes to parse the payload length, etc. - if (this.#byteOffset < 2) { - return callback() - } - - const buffer = this.consume(2) - - this.#info.fin = (buffer[0] & 0x80) !== 0 - this.#info.opcode = buffer[0] & 0x0F - - // If we receive a fragmented message, we use the type of the first - // frame to parse the full message as binary/text, when it's terminated - this.#info.originalOpcode ??= this.#info.opcode - - this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION - - if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { - // Only text and binary frames can be fragmented - failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') - return - } - - const payloadLength = buffer[1] & 0x7F - - if (payloadLength <= 125) { - this.#info.payloadLength = payloadLength - this.#state = parserStates.READ_DATA - } else if (payloadLength === 126) { - this.#state = parserStates.PAYLOADLENGTH_16 - } else if (payloadLength === 127) { - this.#state = parserStates.PAYLOADLENGTH_64 - } - - if (this.#info.fragmented && payloadLength > 125) { - // A fragmented frame can't be fragmented itself - failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') - return - } else if ( - (this.#info.opcode === opcodes.PING || - this.#info.opcode === opcodes.PONG || - this.#info.opcode === opcodes.CLOSE) && - payloadLength > 125 - ) { - // Control frames can have a payload length of 125 bytes MAX - failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') - return - } else if (this.#info.opcode === opcodes.CLOSE) { - if (payloadLength === 1) { - failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') - return - } - - const body = this.consume(payloadLength) - - this.#info.closeInfo = this.parseCloseBody(false, body) - - if (!this.ws[kSentClose]) { - // If an endpoint receives a Close frame and did not previously send a - // Close frame, the endpoint MUST send a Close frame in response. (When - // sending a Close frame in response, the endpoint typically echos the - // status code it received.) - const body = Buffer.allocUnsafe(2) - body.writeUInt16BE(this.#info.closeInfo.code, 0) - const closeFrame = new WebsocketFrameSend(body) - - this.ws[kResponse].socket.write( - closeFrame.createFrame(opcodes.CLOSE), - (err) => { - if (!err) { - this.ws[kSentClose] = true - } - } - ) - } - - // Upon either sending or receiving a Close control frame, it is said - // that _The WebSocket Closing Handshake is Started_ and that the - // WebSocket connection is in the CLOSING state. - this.ws[kReadyState] = states.CLOSING - this.ws[kReceivedClose] = true - - this.end() - - return - } else if (this.#info.opcode === opcodes.PING) { - // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in - // response, unless it already received a Close frame. - // A Pong frame sent in response to a Ping frame must have identical - // "Application data" - - const body = this.consume(payloadLength) - - if (!this.ws[kReceivedClose]) { - const frame = new WebsocketFrameSend(body) - - this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) - - if (channels.ping.hasSubscribers) { - channels.ping.publish({ - payload: body - }) - } - } - - this.#state = parserStates.INFO - - if (this.#byteOffset > 0) { - continue - } else { - callback() - return - } - } else if (this.#info.opcode === opcodes.PONG) { - // A Pong frame MAY be sent unsolicited. This serves as a - // unidirectional heartbeat. A response to an unsolicited Pong frame is - // not expected. - - const body = this.consume(payloadLength) - - if (channels.pong.hasSubscribers) { - channels.pong.publish({ - payload: body - }) - } - - if (this.#byteOffset > 0) { - continue - } else { - callback() - return - } - } - } else if (this.#state === parserStates.PAYLOADLENGTH_16) { - if (this.#byteOffset < 2) { - return callback() - } - - const buffer = this.consume(2) - - this.#info.payloadLength = buffer.readUInt16BE(0) - this.#state = parserStates.READ_DATA - } else if (this.#state === parserStates.PAYLOADLENGTH_64) { - if (this.#byteOffset < 8) { - return callback() - } - - const buffer = this.consume(8) - const upper = buffer.readUInt32BE(0) - - // 2^31 is the maxinimum bytes an arraybuffer can contain - // on 32-bit systems. Although, on 64-bit systems, this is - // 2^53-1 bytes. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length - // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 - // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e - if (upper > 2 ** 31 - 1) { - failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') - return - } - - const lower = buffer.readUInt32BE(4) - - this.#info.payloadLength = (upper << 8) + lower - this.#state = parserStates.READ_DATA - } else if (this.#state === parserStates.READ_DATA) { - if (this.#byteOffset < this.#info.payloadLength) { - // If there is still more data in this chunk that needs to be read - return callback() - } else if (this.#byteOffset >= this.#info.payloadLength) { - // If the server sent multiple frames in a single chunk - - const body = this.consume(this.#info.payloadLength) - - this.#fragments.push(body) - - // If the frame is unfragmented, or a fragmented frame was terminated, - // a message was received - if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { - const fullMessage = Buffer.concat(this.#fragments) - - websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) - - this.#info = {} - this.#fragments.length = 0 - } - - this.#state = parserStates.INFO - } - } - - if (this.#byteOffset > 0) { - continue - } else { - callback() - break - } - } - } - - /** - * Take n bytes from the buffered Buffers - * @param {number} n - * @returns {Buffer|null} - */ - consume (n) { - if (n > this.#byteOffset) { - return null - } else if (n === 0) { - return emptyBuffer - } - - if (this.#buffers[0].length === n) { - this.#byteOffset -= this.#buffers[0].length - return this.#buffers.shift() - } - - const buffer = Buffer.allocUnsafe(n) - let offset = 0 - - while (offset !== n) { - const next = this.#buffers[0] - const { length } = next - - if (length + offset === n) { - buffer.set(this.#buffers.shift(), offset) - break - } else if (length + offset > n) { - buffer.set(next.subarray(0, n - offset), offset) - this.#buffers[0] = next.subarray(n - offset) - break - } else { - buffer.set(this.#buffers.shift(), offset) - offset += next.length - } - } - - this.#byteOffset -= n - - return buffer - } - - parseCloseBody (onlyCode, data) { - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 - /** @type {number|undefined} */ - let code - - if (data.length >= 2) { - // _The WebSocket Connection Close Code_ is - // defined as the status code (Section 7.4) contained in the first Close - // control frame received by the application - code = data.readUInt16BE(0) - } - - if (onlyCode) { - if (!isValidStatusCode(code)) { - return null - } - - return { code } - } - - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 - /** @type {Buffer} */ - let reason = data.subarray(2) - - // Remove BOM - if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { - reason = reason.subarray(3) - } - - if (code !== undefined && !isValidStatusCode(code)) { - return null - } - - try { - // TODO: optimize this - reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) - } catch { - return null - } - - return { code, reason } - } - - get closingInfo () { - return this.#info.closeInfo - } -} - -module.exports = { - ByteParser -} - - -/***/ }), - -/***/ 2933: -/***/ ((module) => { - - - -module.exports = { - kWebSocketURL: Symbol('url'), - kReadyState: Symbol('ready state'), - kController: Symbol('controller'), - kResponse: Symbol('response'), - kBinaryType: Symbol('binary type'), - kSentClose: Symbol('sent close'), - kReceivedClose: Symbol('received close'), - kByteParser: Symbol('byte parser') -} - - -/***/ }), - -/***/ 3574: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(2933) -const { states, opcodes } = __nccwpck_require__(5913) -const { MessageEvent, ErrorEvent } = __nccwpck_require__(6255) - -/* globals Blob */ - -/** - * @param {import('./websocket').WebSocket} ws - */ -function isEstablished (ws) { - // If the server's response is validated as provided for above, it is - // said that _The WebSocket Connection is Established_ and that the - // WebSocket Connection is in the OPEN state. - return ws[kReadyState] === states.OPEN -} - -/** - * @param {import('./websocket').WebSocket} ws - */ -function isClosing (ws) { - // Upon either sending or receiving a Close control frame, it is said - // that _The WebSocket Closing Handshake is Started_ and that the - // WebSocket connection is in the CLOSING state. - return ws[kReadyState] === states.CLOSING -} - -/** - * @param {import('./websocket').WebSocket} ws - */ -function isClosed (ws) { - return ws[kReadyState] === states.CLOSED -} - -/** - * @see https://dom.spec.whatwg.org/#concept-event-fire - * @param {string} e - * @param {EventTarget} target - * @param {EventInit | undefined} eventInitDict - */ -function fireEvent (e, target, eventConstructor = Event, eventInitDict) { - // 1. If eventConstructor is not given, then let eventConstructor be Event. - - // 2. Let event be the result of creating an event given eventConstructor, - // in the relevant realm of target. - // 3. Initialize event’s type attribute to e. - const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap - - // 4. Initialize any other IDL attributes of event as described in the - // invocation of this algorithm. - - // 5. Return the result of dispatching event at target, with legacy target - // override flag set if set. - target.dispatchEvent(event) -} - -/** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - * @param {import('./websocket').WebSocket} ws - * @param {number} type Opcode - * @param {Buffer} data application data - */ -function websocketMessageReceived (ws, type, data) { - // 1. If ready state is not OPEN (1), then return. - if (ws[kReadyState] !== states.OPEN) { - return - } - - // 2. Let dataForEvent be determined by switching on type and binary type: - let dataForEvent - - if (type === opcodes.TEXT) { - // -> type indicates that the data is Text - // a new DOMString containing data - try { - dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) - } catch { - failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') - return - } - } else if (type === opcodes.BINARY) { - if (ws[kBinaryType] === 'blob') { - // -> type indicates that the data is Binary and binary type is "blob" - // a new Blob object, created in the relevant Realm of the WebSocket - // object, that represents data as its raw data - dataForEvent = new Blob([data]) - } else { - // -> type indicates that the data is Binary and binary type is "arraybuffer" - // a new ArrayBuffer object, created in the relevant Realm of the - // WebSocket object, whose contents are data - dataForEvent = new Uint8Array(data).buffer - } - } - - // 3. Fire an event named message at the WebSocket object, using MessageEvent, - // with the origin attribute initialized to the serialization of the WebSocket - // object’s url's origin, and the data attribute initialized to dataForEvent. - fireEvent('message', ws, MessageEvent, { - origin: ws[kWebSocketURL].origin, - data: dataForEvent - }) -} - -/** - * @see https://datatracker.ietf.org/doc/html/rfc6455 - * @see https://datatracker.ietf.org/doc/html/rfc2616 - * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 - * @param {string} protocol - */ -function isValidSubprotocol (protocol) { - // If present, this value indicates one - // or more comma-separated subprotocol the client wishes to speak, - // ordered by preference. The elements that comprise this value - // MUST be non-empty strings with characters in the range U+0021 to - // U+007E not including separator characters as defined in - // [RFC2616] and MUST all be unique strings. - if (protocol.length === 0) { - return false - } - - for (const char of protocol) { - const code = char.charCodeAt(0) - - if ( - code < 0x21 || - code > 0x7E || - char === '(' || - char === ')' || - char === '<' || - char === '>' || - char === '@' || - char === ',' || - char === ';' || - char === ':' || - char === '\\' || - char === '"' || - char === '/' || - char === '[' || - char === ']' || - char === '?' || - char === '=' || - char === '{' || - char === '}' || - code === 32 || // SP - code === 9 // HT - ) { - return false - } - } - - return true -} - -/** - * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 - * @param {number} code - */ -function isValidStatusCode (code) { - if (code >= 1000 && code < 1015) { - return ( - code !== 1004 && // reserved - code !== 1005 && // "MUST NOT be set as a status code" - code !== 1006 // "MUST NOT be set as a status code" - ) - } - - return code >= 3000 && code <= 4999 -} - -/** - * @param {import('./websocket').WebSocket} ws - * @param {string|undefined} reason - */ -function failWebsocketConnection (ws, reason) { - const { [kController]: controller, [kResponse]: response } = ws - - controller.abort() - - if (response?.socket && !response.socket.destroyed) { - response.socket.destroy() - } - - if (reason) { - fireEvent('error', ws, ErrorEvent, { - error: new Error(reason) - }) - } -} - -module.exports = { - isEstablished, - isClosing, - isClosed, - fireEvent, - isValidSubprotocol, - isValidStatusCode, - failWebsocketConnection, - websocketMessageReceived -} - - -/***/ }), - -/***/ 5171: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) -const { DOMException } = __nccwpck_require__(7326) -const { URLSerializer } = __nccwpck_require__(4322) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(5913) -const { - kWebSocketURL, - kReadyState, - kController, - kBinaryType, - kResponse, - kSentClose, - kByteParser -} = __nccwpck_require__(2933) -const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(3574) -const { establishWebSocketConnection } = __nccwpck_require__(8550) -const { WebsocketFrameSend } = __nccwpck_require__(1237) -const { ByteParser } = __nccwpck_require__(3171) -const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { types } = __nccwpck_require__(9023) - -let experimentalWarned = false - -// https://websockets.spec.whatwg.org/#interface-definition -class WebSocket extends EventTarget { - #events = { - open: null, - error: null, - close: null, - message: null - } - - #bufferedAmount = 0 - #protocol = '' - #extensions = '' - - /** - * @param {string} url - * @param {string|string[]} protocols - */ - constructor (url, protocols = []) { - super() - - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) - - if (!experimentalWarned) { - experimentalWarned = true - process.emitWarning('WebSockets are experimental, expect them to change at any time.', { - code: 'UNDICI-WS' - }) - } - - const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) - - url = webidl.converters.USVString(url) - protocols = options.protocols - - // 1. Let baseURL be this's relevant settings object's API base URL. - const baseURL = getGlobalOrigin() - - // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. - let urlRecord - - try { - urlRecord = new URL(url, baseURL) - } catch (e) { - // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. - throw new DOMException(e, 'SyntaxError') - } - - // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". - if (urlRecord.protocol === 'http:') { - urlRecord.protocol = 'ws:' - } else if (urlRecord.protocol === 'https:') { - // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". - urlRecord.protocol = 'wss:' - } - - // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. - if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { - throw new DOMException( - `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, - 'SyntaxError' - ) - } - - // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" - // DOMException. - if (urlRecord.hash || urlRecord.href.endsWith('#')) { - throw new DOMException('Got fragment', 'SyntaxError') - } - - // 8. If protocols is a string, set protocols to a sequence consisting - // of just that string. - if (typeof protocols === 'string') { - protocols = [protocols] - } - - // 9. If any of the values in protocols occur more than once or otherwise - // fail to match the requirements for elements that comprise the value - // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket - // protocol, then throw a "SyntaxError" DOMException. - if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { - throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') - } - - if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { - throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') - } - - // 10. Set this's url to urlRecord. - this[kWebSocketURL] = new URL(urlRecord.href) - - // 11. Let client be this's relevant settings object. - - // 12. Run this step in parallel: - - // 1. Establish a WebSocket connection given urlRecord, protocols, - // and client. - this[kController] = establishWebSocketConnection( - urlRecord, - protocols, - this, - (response) => this.#onConnectionEstablished(response), - options - ) - - // Each WebSocket object has an associated ready state, which is a - // number representing the state of the connection. Initially it must - // be CONNECTING (0). - this[kReadyState] = WebSocket.CONNECTING - - // The extensions attribute must initially return the empty string. - - // The protocol attribute must initially return the empty string. - - // Each WebSocket object has an associated binary type, which is a - // BinaryType. Initially it must be "blob". - this[kBinaryType] = 'blob' - } - - /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-close - * @param {number|undefined} code - * @param {string|undefined} reason - */ - close (code = undefined, reason = undefined) { - webidl.brandCheck(this, WebSocket) - - if (code !== undefined) { - code = webidl.converters['unsigned short'](code, { clamp: true }) - } - - if (reason !== undefined) { - reason = webidl.converters.USVString(reason) - } - - // 1. If code is present, but is neither an integer equal to 1000 nor an - // integer in the range 3000 to 4999, inclusive, throw an - // "InvalidAccessError" DOMException. - if (code !== undefined) { - if (code !== 1000 && (code < 3000 || code > 4999)) { - throw new DOMException('invalid code', 'InvalidAccessError') - } - } - - let reasonByteLength = 0 - - // 2. If reason is present, then run these substeps: - if (reason !== undefined) { - // 1. Let reasonBytes be the result of encoding reason. - // 2. If reasonBytes is longer than 123 bytes, then throw a - // "SyntaxError" DOMException. - reasonByteLength = Buffer.byteLength(reason) - - if (reasonByteLength > 123) { - throw new DOMException( - `Reason must be less than 123 bytes; received ${reasonByteLength}`, - 'SyntaxError' - ) - } - } - - // 3. Run the first matching steps from the following list: - if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { - // If this's ready state is CLOSING (2) or CLOSED (3) - // Do nothing. - } else if (!isEstablished(this)) { - // If the WebSocket connection is not yet established - // Fail the WebSocket connection and set this's ready state - // to CLOSING (2). - failWebsocketConnection(this, 'Connection was closed before it was established.') - this[kReadyState] = WebSocket.CLOSING - } else if (!isClosing(this)) { - // If the WebSocket closing handshake has not yet been started - // Start the WebSocket closing handshake and set this's ready - // state to CLOSING (2). - // - If neither code nor reason is present, the WebSocket Close - // message must not have a body. - // - If code is present, then the status code to use in the - // WebSocket Close message must be the integer given by code. - // - If reason is also present, then reasonBytes must be - // provided in the Close message after the status code. - - const frame = new WebsocketFrameSend() - - // If neither code nor reason is present, the WebSocket Close - // message must not have a body. - - // If code is present, then the status code to use in the - // WebSocket Close message must be the integer given by code. - if (code !== undefined && reason === undefined) { - frame.frameData = Buffer.allocUnsafe(2) - frame.frameData.writeUInt16BE(code, 0) - } else if (code !== undefined && reason !== undefined) { - // If reason is also present, then reasonBytes must be - // provided in the Close message after the status code. - frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) - frame.frameData.writeUInt16BE(code, 0) - // the body MAY contain UTF-8-encoded data with value /reason/ - frame.frameData.write(reason, 2, 'utf-8') - } else { - frame.frameData = emptyBuffer - } - - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket - - socket.write(frame.createFrame(opcodes.CLOSE), (err) => { - if (!err) { - this[kSentClose] = true - } - }) - - // Upon either sending or receiving a Close control frame, it is said - // that _The WebSocket Closing Handshake is Started_ and that the - // WebSocket connection is in the CLOSING state. - this[kReadyState] = states.CLOSING - } else { - // Otherwise - // Set this's ready state to CLOSING (2). - this[kReadyState] = WebSocket.CLOSING - } - } - - /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-send - * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data - */ - send (data) { - webidl.brandCheck(this, WebSocket) - - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) - - data = webidl.converters.WebSocketSendData(data) - - // 1. If this's ready state is CONNECTING, then throw an - // "InvalidStateError" DOMException. - if (this[kReadyState] === WebSocket.CONNECTING) { - throw new DOMException('Sent before connected.', 'InvalidStateError') - } - - // 2. Run the appropriate set of steps from the following list: - // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 - // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 - - if (!isEstablished(this) || isClosing(this)) { - return - } - - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket - - // If data is a string - if (typeof data === 'string') { - // If the WebSocket connection is established and the WebSocket - // closing handshake has not yet started, then the user agent - // must send a WebSocket Message comprised of the data argument - // using a text frame opcode; if the data cannot be sent, e.g. - // because it would need to be buffered but the buffer is full, - // the user agent must flag the WebSocket as full and then close - // the WebSocket connection. Any invocation of this method with a - // string argument that does not throw an exception must increase - // the bufferedAmount attribute by the number of bytes needed to - // express the argument as UTF-8. - - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.TEXT) - - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - } else if (types.isArrayBuffer(data)) { - // If the WebSocket connection is established, and the WebSocket - // closing handshake has not yet started, then the user agent must - // send a WebSocket Message comprised of data using a binary frame - // opcode; if the data cannot be sent, e.g. because it would need - // to be buffered but the buffer is full, the user agent must flag - // the WebSocket as full and then close the WebSocket connection. - // The data to be sent is the data stored in the buffer described - // by the ArrayBuffer object. Any invocation of this method with an - // ArrayBuffer argument that does not throw an exception must - // increase the bufferedAmount attribute by the length of the - // ArrayBuffer in bytes. - - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.BINARY) - - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - } else if (ArrayBuffer.isView(data)) { - // If the WebSocket connection is established, and the WebSocket - // closing handshake has not yet started, then the user agent must - // send a WebSocket Message comprised of data using a binary frame - // opcode; if the data cannot be sent, e.g. because it would need to - // be buffered but the buffer is full, the user agent must flag the - // WebSocket as full and then close the WebSocket connection. The - // data to be sent is the data stored in the section of the buffer - // described by the ArrayBuffer object that data references. Any - // invocation of this method with this kind of argument that does - // not throw an exception must increase the bufferedAmount attribute - // by the length of data’s buffer in bytes. - - const ab = Buffer.from(data, data.byteOffset, data.byteLength) - - const frame = new WebsocketFrameSend(ab) - const buffer = frame.createFrame(opcodes.BINARY) - - this.#bufferedAmount += ab.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= ab.byteLength - }) - } else if (isBlobLike(data)) { - // If the WebSocket connection is established, and the WebSocket - // closing handshake has not yet started, then the user agent must - // send a WebSocket Message comprised of data using a binary frame - // opcode; if the data cannot be sent, e.g. because it would need to - // be buffered but the buffer is full, the user agent must flag the - // WebSocket as full and then close the WebSocket connection. The data - // to be sent is the raw data represented by the Blob object. Any - // invocation of this method with a Blob argument that does not throw - // an exception must increase the bufferedAmount attribute by the size - // of the Blob object’s raw data, in bytes. - - const frame = new WebsocketFrameSend() - - data.arrayBuffer().then((ab) => { - const value = Buffer.from(ab) - frame.frameData = value - const buffer = frame.createFrame(opcodes.BINARY) - - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - }) - } - } - - get readyState () { - webidl.brandCheck(this, WebSocket) - - // The readyState getter steps are to return this's ready state. - return this[kReadyState] - } - - get bufferedAmount () { - webidl.brandCheck(this, WebSocket) - - return this.#bufferedAmount - } - - get url () { - webidl.brandCheck(this, WebSocket) - - // The url getter steps are to return this's url, serialized. - return URLSerializer(this[kWebSocketURL]) - } - - get extensions () { - webidl.brandCheck(this, WebSocket) - - return this.#extensions - } - - get protocol () { - webidl.brandCheck(this, WebSocket) - - return this.#protocol - } - - get onopen () { - webidl.brandCheck(this, WebSocket) - - return this.#events.open - } - - set onopen (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.open) { - this.removeEventListener('open', this.#events.open) - } - - if (typeof fn === 'function') { - this.#events.open = fn - this.addEventListener('open', fn) - } else { - this.#events.open = null - } - } - - get onerror () { - webidl.brandCheck(this, WebSocket) - - return this.#events.error - } - - set onerror (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.error) { - this.removeEventListener('error', this.#events.error) - } - - if (typeof fn === 'function') { - this.#events.error = fn - this.addEventListener('error', fn) - } else { - this.#events.error = null - } - } - - get onclose () { - webidl.brandCheck(this, WebSocket) - - return this.#events.close - } - - set onclose (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.close) { - this.removeEventListener('close', this.#events.close) - } - - if (typeof fn === 'function') { - this.#events.close = fn - this.addEventListener('close', fn) - } else { - this.#events.close = null - } - } - - get onmessage () { - webidl.brandCheck(this, WebSocket) - - return this.#events.message - } - - set onmessage (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.message) { - this.removeEventListener('message', this.#events.message) - } - - if (typeof fn === 'function') { - this.#events.message = fn - this.addEventListener('message', fn) - } else { - this.#events.message = null - } - } - - get binaryType () { - webidl.brandCheck(this, WebSocket) - - return this[kBinaryType] - } - - set binaryType (type) { - webidl.brandCheck(this, WebSocket) - - if (type !== 'blob' && type !== 'arraybuffer') { - this[kBinaryType] = 'blob' - } else { - this[kBinaryType] = type - } - } - - /** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - */ - #onConnectionEstablished (response) { - // processResponse is called when the "response’s header list has been received and initialized." - // once this happens, the connection is open - this[kResponse] = response - - const parser = new ByteParser(this) - parser.on('drain', function onParserDrain () { - this.ws[kResponse].socket.resume() - }) - - response.socket.ws = this - this[kByteParser] = parser - - // 1. Change the ready state to OPEN (1). - this[kReadyState] = states.OPEN - - // 2. Change the extensions attribute’s value to the extensions in use, if - // it is not the null value. - // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 - const extensions = response.headersList.get('sec-websocket-extensions') - - if (extensions !== null) { - this.#extensions = extensions - } - - // 3. Change the protocol attribute’s value to the subprotocol in use, if - // it is not the null value. - // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 - const protocol = response.headersList.get('sec-websocket-protocol') - - if (protocol !== null) { - this.#protocol = protocol - } - - // 4. Fire an event named open at the WebSocket object. - fireEvent('open', this) - } -} - -// https://websockets.spec.whatwg.org/#dom-websocket-connecting -WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING -// https://websockets.spec.whatwg.org/#dom-websocket-open -WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN -// https://websockets.spec.whatwg.org/#dom-websocket-closing -WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING -// https://websockets.spec.whatwg.org/#dom-websocket-closed -WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED - -Object.defineProperties(WebSocket.prototype, { - CONNECTING: staticPropertyDescriptors, - OPEN: staticPropertyDescriptors, - CLOSING: staticPropertyDescriptors, - CLOSED: staticPropertyDescriptors, - url: kEnumerableProperty, - readyState: kEnumerableProperty, - bufferedAmount: kEnumerableProperty, - onopen: kEnumerableProperty, - onerror: kEnumerableProperty, - onclose: kEnumerableProperty, - close: kEnumerableProperty, - onmessage: kEnumerableProperty, - binaryType: kEnumerableProperty, - send: kEnumerableProperty, - extensions: kEnumerableProperty, - protocol: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'WebSocket', - writable: false, - enumerable: false, - configurable: true - } -}) - -Object.defineProperties(WebSocket, { - CONNECTING: staticPropertyDescriptors, - OPEN: staticPropertyDescriptors, - CLOSING: staticPropertyDescriptors, - CLOSED: staticPropertyDescriptors -}) - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.DOMString -) - -webidl.converters['DOMString or sequence'] = function (V) { - if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { - return webidl.converters['sequence'](V) - } - - return webidl.converters.DOMString(V) -} - -// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 -webidl.converters.WebSocketInit = webidl.dictionaryConverter([ - { - key: 'protocols', - converter: webidl.converters['DOMString or sequence'], - get defaultValue () { - return [] - } - }, - { - key: 'dispatcher', - converter: (V) => V, - get defaultValue () { - return getGlobalDispatcher() - } - }, - { - key: 'headers', - converter: webidl.nullableConverter(webidl.converters.HeadersInit) - } -]) - -webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { - if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { - return webidl.converters.WebSocketInit(V) - } - - return { protocols: webidl.converters['DOMString or sequence'](V) } -} - -webidl.converters.WebSocketSendData = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } - - if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { - return webidl.converters.BufferSource(V) - } - } - - return webidl.converters.USVString(V) -} - -module.exports = { - WebSocket -} - - -/***/ }), - -/***/ 3843: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - - if (typeof process === "object" && process.version !== undefined) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - - return ""; -} - -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 8264: -/***/ ((module) => { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), - -/***/ 2613: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); - -/***/ }), - -/***/ 290: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); - -/***/ }), - -/***/ 181: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); - -/***/ }), - -/***/ 5317: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); - -/***/ }), - -/***/ 4236: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); - -/***/ }), - -/***/ 6982: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); - -/***/ }), - -/***/ 1637: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); - -/***/ }), - -/***/ 4434: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); - -/***/ }), - -/***/ 9896: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); - -/***/ }), - -/***/ 8611: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); - -/***/ }), - -/***/ 5675: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); - -/***/ }), - -/***/ 5692: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); - -/***/ }), - -/***/ 9278: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); - -/***/ }), - -/***/ 7598: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); - -/***/ }), - -/***/ 8474: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); - -/***/ }), - -/***/ 7075: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); - -/***/ }), - -/***/ 7975: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); - -/***/ }), - -/***/ 857: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); - -/***/ }), - -/***/ 6928: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); - -/***/ }), - -/***/ 2987: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); - -/***/ }), - -/***/ 3480: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); - -/***/ }), - -/***/ 2203: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); - -/***/ }), - -/***/ 3774: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); - -/***/ }), - -/***/ 3193: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); - -/***/ }), - -/***/ 3557: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); - -/***/ }), - -/***/ 4756: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); - -/***/ }), - -/***/ 7016: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); - -/***/ }), - -/***/ 9023: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); - -/***/ }), - -/***/ 8253: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); - -/***/ }), - -/***/ 8167: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); - -/***/ }), - -/***/ 3106: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); - -/***/ }), - -/***/ 7182: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const inherits = (__nccwpck_require__(7975).inherits) - -const StreamSearch = __nccwpck_require__(4136) - -const PartStream = __nccwpck_require__(612) -const HeaderParser = __nccwpck_require__(2271) - -const DASH = 45 -const B_ONEDASH = Buffer.from('-') -const B_CRLF = Buffer.from('\r\n') -const EMPTY_FN = function () {} - -function Dicer (cfg) { - if (!(this instanceof Dicer)) { return new Dicer(cfg) } - WritableStream.call(this, cfg) - - if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - - if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - - this._headerFirst = cfg.headerFirst - - this._dashes = 0 - this._parts = 0 - this._finished = false - this._realFinish = false - this._isPreamble = true - this._justMatched = false - this._firstWrite = true - this._inHeader = true - this._part = undefined - this._cb = undefined - this._ignoreData = false - this._partOpts = { highWaterMark: cfg.partHwm } - this._pause = false - - const self = this - this._hparser = new HeaderParser(cfg) - this._hparser.on('header', function (header) { - self._inHeader = false - self._part.emit('header', header) - }) -} -inherits(Dicer, WritableStream) - -Dicer.prototype.emit = function (ev) { - if (ev === 'finish' && !this._realFinish) { - if (!this._finished) { - const self = this - process.nextTick(function () { - self.emit('error', new Error('Unexpected end of multipart data')) - if (self._part && !self._ignoreData) { - const type = (self._isPreamble ? 'Preamble' : 'Part') - self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) - self._part.push(null) - process.nextTick(function () { - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - return - } - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - } - } else { WritableStream.prototype.emit.apply(this, arguments) } -} - -Dicer.prototype._write = function (data, encoding, cb) { - // ignore unexpected data (e.g. extra trailer data after finished) - if (!this._hparser && !this._bparser) { return cb() } - - if (this._headerFirst && this._isPreamble) { - if (!this._part) { - this._part = new PartStream(this._partOpts) - if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } - } - const r = this._hparser.push(data) - if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } - } - - // allows for "easier" testing - if (this._firstWrite) { - this._bparser.push(B_CRLF) - this._firstWrite = false - } - - this._bparser.push(data) - - if (this._pause) { this._cb = cb } else { cb() } -} - -Dicer.prototype.reset = function () { - this._part = undefined - this._bparser = undefined - this._hparser = undefined -} - -Dicer.prototype.setBoundary = function (boundary) { - const self = this - this._bparser = new StreamSearch('\r\n--' + boundary) - this._bparser.on('info', function (isMatch, data, start, end) { - self._oninfo(isMatch, data, start, end) - }) -} - -Dicer.prototype._ignore = function () { - if (this._part && !this._ignoreData) { - this._ignoreData = true - this._part.on('error', EMPTY_FN) - // we must perform some kind of read on the stream even though we are - // ignoring the data, otherwise node's Readable stream will not emit 'end' - // after pushing null to the stream - this._part.resume() - } -} - -Dicer.prototype._oninfo = function (isMatch, data, start, end) { - let buf; const self = this; let i = 0; let r; let shouldWriteMore = true - - if (!this._part && this._justMatched && data) { - while (this._dashes < 2 && (start + i) < end) { - if (data[start + i] === DASH) { - ++i - ++this._dashes - } else { - if (this._dashes) { buf = B_ONEDASH } - this._dashes = 0 - break - } - } - if (this._dashes === 2) { - if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } - this.reset() - this._finished = true - // no more parts will be added - if (self._parts === 0) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } - } - if (this._dashes) { return } - } - if (this._justMatched) { this._justMatched = false } - if (!this._part) { - this._part = new PartStream(this._partOpts) - this._part._read = function (n) { - self._unpause() - } - if (this._isPreamble && this.listenerCount('preamble') !== 0) { - this.emit('preamble', this._part) - } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { - this.emit('part', this._part) - } else { - this._ignore() - } - if (!this._isPreamble) { this._inHeader = true } - } - if (data && start < end && !this._ignoreData) { - if (this._isPreamble || !this._inHeader) { - if (buf) { shouldWriteMore = this._part.push(buf) } - shouldWriteMore = this._part.push(data.slice(start, end)) - if (!shouldWriteMore) { this._pause = true } - } else if (!this._isPreamble && this._inHeader) { - if (buf) { this._hparser.push(buf) } - r = this._hparser.push(data.slice(start, end)) - if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } - } - } - if (isMatch) { - this._hparser.reset() - if (this._isPreamble) { this._isPreamble = false } else { - if (start !== end) { - ++this._parts - this._part.on('end', function () { - if (--self._parts === 0) { - if (self._finished) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } else { - self._unpause() - } - } - }) - } - } - this._part.push(null) - this._part = undefined - this._ignoreData = false - this._justMatched = true - this._dashes = 0 - } -} - -Dicer.prototype._unpause = function () { - if (!this._pause) { return } - - this._pause = false - if (this._cb) { - const cb = this._cb - this._cb = undefined - cb() - } -} - -module.exports = Dicer - - -/***/ }), - -/***/ 2271: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) -const getLimit = __nccwpck_require__(2393) - -const StreamSearch = __nccwpck_require__(4136) - -const B_DCRLF = Buffer.from('\r\n\r\n') -const RE_CRLF = /\r\n/g -const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex - -function HeaderParser (cfg) { - EventEmitter.call(this) - - cfg = cfg || {} - const self = this - this.nread = 0 - this.maxed = false - this.npairs = 0 - this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) - this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) - this.buffer = '' - this.header = {} - this.finished = false - this.ss = new StreamSearch(B_DCRLF) - this.ss.on('info', function (isMatch, data, start, end) { - if (data && !self.maxed) { - if (self.nread + end - start >= self.maxHeaderSize) { - end = self.maxHeaderSize - self.nread + start - self.nread = self.maxHeaderSize - self.maxed = true - } else { self.nread += (end - start) } - - self.buffer += data.toString('binary', start, end) - } - if (isMatch) { self._finish() } - }) -} -inherits(HeaderParser, EventEmitter) - -HeaderParser.prototype.push = function (data) { - const r = this.ss.push(data) - if (this.finished) { return r } -} - -HeaderParser.prototype.reset = function () { - this.finished = false - this.buffer = '' - this.header = {} - this.ss.reset() -} - -HeaderParser.prototype._finish = function () { - if (this.buffer) { this._parseHeader() } - this.ss.matches = this.ss.maxMatches - const header = this.header - this.header = {} - this.buffer = '' - this.finished = true - this.nread = this.npairs = 0 - this.maxed = false - this.emit('header', header) -} - -HeaderParser.prototype._parseHeader = function () { - if (this.npairs === this.maxHeaderPairs) { return } - - const lines = this.buffer.split(RE_CRLF) - const len = lines.length - let m, h - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (lines[i].length === 0) { continue } - if (lines[i][0] === '\t' || lines[i][0] === ' ') { - // folded header content - // RFC2822 says to just remove the CRLF and not the whitespace following - // it, so we follow the RFC and include the leading whitespace ... - if (h) { - this.header[h][this.header[h].length - 1] += lines[i] - continue - } - } - - const posColon = lines[i].indexOf(':') - if ( - posColon === -1 || - posColon === 0 - ) { - return - } - m = RE_HDR.exec(lines[i]) - h = m[1].toLowerCase() - this.header[h] = this.header[h] || [] - this.header[h].push((m[2] || '')) - if (++this.npairs === this.maxHeaderPairs) { break } - } -} - -module.exports = HeaderParser - - -/***/ }), - -/***/ 612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const inherits = (__nccwpck_require__(7975).inherits) -const ReadableStream = (__nccwpck_require__(7075).Readable) - -function PartStream (opts) { - ReadableStream.call(this, opts) -} -inherits(PartStream, ReadableStream) - -PartStream.prototype._read = function (n) {} - -module.exports = PartStream - - -/***/ }), - -/***/ 4136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -/** - * Copyright Brian White. All rights reserved. - * - * @see https://github.com/mscdex/streamsearch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation - * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool - */ -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) - -function SBMH (needle) { - if (typeof needle === 'string') { - needle = Buffer.from(needle) - } - - if (!Buffer.isBuffer(needle)) { - throw new TypeError('The needle has to be a String or a Buffer.') - } - - const needleLength = needle.length - - if (needleLength === 0) { - throw new Error('The needle cannot be an empty String/Buffer.') - } - - if (needleLength > 256) { - throw new Error('The needle cannot have a length bigger than 256.') - } - - this.maxMatches = Infinity - this.matches = 0 - - this._occ = new Array(256) - .fill(needleLength) // Initialize occurrence table. - this._lookbehind_size = 0 - this._needle = needle - this._bufpos = 0 - - this._lookbehind = Buffer.alloc(needleLength) - - // Populate occurrence table with analysis of the needle, - // ignoring last letter. - for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var - this._occ[needle[i]] = needleLength - 1 - i - } -} -inherits(SBMH, EventEmitter) - -SBMH.prototype.reset = function () { - this._lookbehind_size = 0 - this.matches = 0 - this._bufpos = 0 -} - -SBMH.prototype.push = function (chunk, pos) { - if (!Buffer.isBuffer(chunk)) { - chunk = Buffer.from(chunk, 'binary') - } - const chlen = chunk.length - this._bufpos = pos || 0 - let r - while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } - return r -} - -SBMH.prototype._sbmh_feed = function (data) { - const len = data.length - const needle = this._needle - const needleLength = needle.length - const lastNeedleChar = needle[needleLength - 1] - - // Positive: points to a position in `data` - // pos == 3 points to data[3] - // Negative: points to a position in the lookbehind buffer - // pos == -2 points to lookbehind[lookbehind_size - 2] - let pos = -this._lookbehind_size - let ch - - if (pos < 0) { - // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool - // search with character lookup code that considers both the - // lookbehind buffer and the current round's haystack data. - // - // Loop until - // there is a match. - // or until - // we've moved past the position that requires the - // lookbehind buffer. In this case we switch to the - // optimized loop. - // or until - // the character to look at lies outside the haystack. - while (pos < 0 && pos <= len - needleLength) { - ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - - if ( - ch === lastNeedleChar && - this._sbmh_memcmp(data, pos, needleLength - 1) - ) { - this._lookbehind_size = 0 - ++this.matches - this.emit('info', true) - - return (this._bufpos = pos + needleLength) - } - pos += this._occ[ch] - } - - // No match. - - if (pos < 0) { - // There's too few data for Boyer-Moore-Horspool to run, - // so let's use a different algorithm to skip as much as - // we can. - // Forward pos until - // the trailing part of lookbehind + data - // looks like the beginning of the needle - // or until - // pos == 0 - while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } - } - - if (pos >= 0) { - // Discard lookbehind buffer. - this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) - this._lookbehind_size = 0 - } else { - // Cut off part of the lookbehind buffer that has - // been processed and append the entire haystack - // into it. - const bytesToCutOff = this._lookbehind_size + pos - if (bytesToCutOff > 0) { - // The cut off data is guaranteed not to contain the needle. - this.emit('info', false, this._lookbehind, 0, bytesToCutOff) - } - - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) - this._lookbehind_size -= bytesToCutOff - - data.copy(this._lookbehind, this._lookbehind_size) - this._lookbehind_size += len - - this._bufpos = len - return len - } - } - - pos += (pos >= 0) * this._bufpos - - // Lookbehind buffer is now empty. We only need to check if the - // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) - ++this.matches - if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength - } - - // There was no match. If there's trailing haystack data that we cannot - // match yet using the Boyer-Moore-Horspool algorithm (because the trailing - // data is less than the needle size) then match using a modified - // algorithm that starts matching from the beginning instead of the end. - // Whatever trailing data is left after running this algorithm is added to - // the lookbehind buffer. - while ( - pos < len && - ( - data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) - ) - ) { - ++pos - } - if (pos < len) { - data.copy(this._lookbehind, 0, pos, pos + (len - pos)) - this._lookbehind_size = len - pos - } - - // Everything until pos is guaranteed not to contain needle data. - if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - - this._bufpos = len - return len -} - -SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) - ? this._lookbehind[this._lookbehind_size + pos] - : data[pos] -} - -SBMH.prototype._sbmh_memcmp = function (data, pos, len) { - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } - } - return true -} - -module.exports = SBMH - - -/***/ }), - -/***/ 9581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const { inherits } = __nccwpck_require__(7975) -const Dicer = __nccwpck_require__(7182) - -const MultipartParser = __nccwpck_require__(1192) -const UrlencodedParser = __nccwpck_require__(855) -const parseParams = __nccwpck_require__(8929) - -function Busboy (opts) { - if (!(this instanceof Busboy)) { return new Busboy(opts) } - - if (typeof opts !== 'object') { - throw new TypeError('Busboy expected an options-Object.') - } - if (typeof opts.headers !== 'object') { - throw new TypeError('Busboy expected an options-Object with headers-attribute.') - } - if (typeof opts.headers['content-type'] !== 'string') { - throw new TypeError('Missing Content-Type-header.') - } - - const { - headers, - ...streamOptions - } = opts - - this.opts = { - autoDestroy: false, - ...streamOptions - } - WritableStream.call(this, this.opts) - - this._done = false - this._parser = this.getParserByHeaders(headers) - this._finished = false -} -inherits(Busboy, WritableStream) - -Busboy.prototype.emit = function (ev) { - if (ev === 'finish') { - if (!this._done) { - this._parser?.end() - return - } else if (this._finished) { - return - } - this._finished = true - } - WritableStream.prototype.emit.apply(this, arguments) -} - -Busboy.prototype.getParserByHeaders = function (headers) { - const parsed = parseParams(headers['content-type']) - - const cfg = { - defCharset: this.opts.defCharset, - fileHwm: this.opts.fileHwm, - headers, - highWaterMark: this.opts.highWaterMark, - isPartAFile: this.opts.isPartAFile, - limits: this.opts.limits, - parsedConType: parsed, - preservePath: this.opts.preservePath - } - - if (MultipartParser.detect.test(parsed[0])) { - return new MultipartParser(this, cfg) - } - if (UrlencodedParser.detect.test(parsed[0])) { - return new UrlencodedParser(this, cfg) - } - throw new Error('Unsupported Content-Type.') -} - -Busboy.prototype._write = function (chunk, encoding, cb) { - this._parser.write(chunk, cb) -} - -module.exports = Busboy -module.exports["default"] = Busboy -module.exports.Busboy = Busboy - -module.exports.Dicer = Dicer - - -/***/ }), - -/***/ 1192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// TODO: -// * support 1 nested multipart level -// (see second multipart example here: -// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) -// * support limits.fieldNameSize -// -- this will require modifications to utils.parseParams - -const { Readable } = __nccwpck_require__(7075) -const { inherits } = __nccwpck_require__(7975) - -const Dicer = __nccwpck_require__(7182) - -const parseParams = __nccwpck_require__(8929) -const decodeText = __nccwpck_require__(2747) -const basename = __nccwpck_require__(692) -const getLimit = __nccwpck_require__(2393) - -const RE_BOUNDARY = /^boundary$/i -const RE_FIELD = /^form-data$/i -const RE_CHARSET = /^charset$/i -const RE_FILENAME = /^filename$/i -const RE_NAME = /^name$/i - -Multipart.detect = /^multipart\/form-data/i -function Multipart (boy, cfg) { - let i - let len - const self = this - let boundary - const limits = cfg.limits - const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) - const parsedConType = cfg.parsedConType || [] - const defCharset = cfg.defCharset || 'utf8' - const preservePath = cfg.preservePath - const fileOpts = { highWaterMark: cfg.fileHwm } - - for (i = 0, len = parsedConType.length; i < len; ++i) { - if (Array.isArray(parsedConType[i]) && - RE_BOUNDARY.test(parsedConType[i][0])) { - boundary = parsedConType[i][1] - break - } - } - - function checkFinished () { - if (nends === 0 && finished && !boy._done) { - finished = false - self.end() - } - } - - if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - - const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) - const filesLimit = getLimit(limits, 'files', Infinity) - const fieldsLimit = getLimit(limits, 'fields', Infinity) - const partsLimit = getLimit(limits, 'parts', Infinity) - const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) - const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) - - let nfiles = 0 - let nfields = 0 - let nends = 0 - let curFile - let curField - let finished = false - - this._needDrain = false - this._pause = false - this._cb = undefined - this._nparts = 0 - this._boy = boy - - const parserCfg = { - boundary, - maxHeaderPairs: headerPairsLimit, - maxHeaderSize: headerSizeLimit, - partHwm: fileOpts.highWaterMark, - highWaterMark: cfg.highWaterMark - } - - this.parser = new Dicer(parserCfg) - this.parser.on('drain', function () { - self._needDrain = false - if (self._cb && !self._pause) { - const cb = self._cb - self._cb = undefined - cb() - } - }).on('part', function onPart (part) { - if (++self._nparts > partsLimit) { - self.parser.removeListener('part', onPart) - self.parser.on('part', skipPart) - boy.hitPartsLimit = true - boy.emit('partsLimit') - return skipPart(part) - } - - // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let - // us emit 'end' early since we know the part has ended if we are already - // seeing the next part - if (curField) { - const field = curField - field.emit('end') - field.removeAllListeners('end') - } - - part.on('header', function (header) { - let contype - let fieldname - let parsed - let charset - let encoding - let filename - let nsize = 0 - - if (header['content-type']) { - parsed = parseParams(header['content-type'][0]) - if (parsed[0]) { - contype = parsed[0].toLowerCase() - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_CHARSET.test(parsed[i][0])) { - charset = parsed[i][1].toLowerCase() - break - } - } - } - } - - if (contype === undefined) { contype = 'text/plain' } - if (charset === undefined) { charset = defCharset } - - if (header['content-disposition']) { - parsed = parseParams(header['content-disposition'][0]) - if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_NAME.test(parsed[i][0])) { - fieldname = parsed[i][1] - } else if (RE_FILENAME.test(parsed[i][0])) { - filename = parsed[i][1] - if (!preservePath) { filename = basename(filename) } - } - } - } else { return skipPart(part) } - - if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - - let onData, - onEnd - - if (isPartAFile(fieldname, contype, filename)) { - // file/binary field - if (nfiles === filesLimit) { - if (!boy.hitFilesLimit) { - boy.hitFilesLimit = true - boy.emit('filesLimit') - } - return skipPart(part) - } - - ++nfiles - - if (boy.listenerCount('file') === 0) { - self.parser._ignore() - return - } - - ++nends - const file = new FileStream(fileOpts) - curFile = file - file.on('end', function () { - --nends - self._pause = false - checkFinished() - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - }) - file._read = function (n) { - if (!self._pause) { return } - self._pause = false - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - } - boy.emit('file', fieldname, file, filename, encoding, contype) - - onData = function (data) { - if ((nsize += data.length) > fileSizeLimit) { - const extralen = fileSizeLimit - nsize + data.length - if (extralen > 0) { file.push(data.slice(0, extralen)) } - file.truncated = true - file.bytesRead = fileSizeLimit - part.removeAllListeners('data') - file.emit('limit') - return - } else if (!file.push(data)) { self._pause = true } - - file.bytesRead = nsize - } - - onEnd = function () { - curFile = undefined - file.push(null) - } - } else { - // non-file field - if (nfields === fieldsLimit) { - if (!boy.hitFieldsLimit) { - boy.hitFieldsLimit = true - boy.emit('fieldsLimit') - } - return skipPart(part) - } - - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part - - onData = function (data) { - if ((nsize += data.length) > fieldSizeLimit) { - const extralen = (fieldSizeLimit - (nsize - data.length)) - buffer += data.toString('binary', 0, extralen) - truncated = true - part.removeAllListeners('data') - } else { buffer += data.toString('binary') } - } - - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() - } - } - - /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become - broken. Streams2/streams3 is a huge black box of confusion, but - somehow overriding the sync state seems to fix things again (and still - seems to work for previous node versions). - */ - part._readableState.sync = false - - part.on('data', onData) - part.on('end', onEnd) - }).on('error', function (err) { - if (curFile) { curFile.emit('error', err) } - }) - }).on('error', function (err) { - boy.emit('error', err) - }).on('finish', function () { - finished = true - checkFinished() - }) -} - -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb - } -} - -Multipart.prototype.end = function () { - const self = this - - if (self.parser.writable) { - self.parser.end() - } else if (!self._boy._done) { - process.nextTick(function () { - self._boy._done = true - self._boy.emit('finish') - }) - } -} - -function skipPart (part) { - part.resume() -} - -function FileStream (opts) { - Readable.call(this, opts) - - this.bytesRead = 0 - - this.truncated = false -} - -inherits(FileStream, Readable) - -FileStream.prototype._read = function (n) {} - -module.exports = Multipart - - -/***/ }), - -/***/ 855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Decoder = __nccwpck_require__(1496) -const decodeText = __nccwpck_require__(2747) -const getLimit = __nccwpck_require__(2393) - -const RE_CHARSET = /^charset$/i - -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy - - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) - - let charset - for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var - if (Array.isArray(parsedConType[i]) && - RE_CHARSET.test(parsedConType[i][0])) { - charset = parsedConType[i][1].toLowerCase() - break - } - } - - if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - - this.decoder = new Decoder() - this.charset = charset - this._fields = 0 - this._state = 'key' - this._checkingBytes = true - this._bytesKey = 0 - this._bytesVal = 0 - this._key = '' - this._val = '' - this._keyTrunc = false - this._valTrunc = false - this._hitLimit = false -} - -UrlEncoded.prototype.write = function (data, cb) { - if (this._fields === this.fieldsLimit) { - if (!this.boy.hitFieldsLimit) { - this.boy.hitFieldsLimit = true - this.boy.emit('fieldsLimit') - } - return cb() - } - - let idxeq; let idxamp; let i; let p = 0; const len = data.length - - while (p < len) { - if (this._state === 'key') { - idxeq = idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x3D/* = */) { - idxeq = i - break - } else if (data[i] === 0x26/* & */) { - idxamp = i - break - } - if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesKey } - } - - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' - - this._hitLimit = false - this._checkingBytes = true - this._val = '' - this._bytesVal = 0 - this._valTrunc = false - this.decoder.reset() - - p = idxeq + 1 - } else if (idxamp !== undefined) { - // key with no assignment - ++this._fields - let key; const keyTrunc = this._keyTrunc - if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) - } - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._keyTrunc = true - } - } else { - if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } - p = len - } - } else { - idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x26/* & */) { - idxamp = i - break - } - if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesVal } - } - - if (idxamp !== undefined) { - ++this._fields - if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - this._state = 'key' - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._val === '' && this.fieldSizeLimit === 0) || - (this._bytesVal = this._val.length) === this.fieldSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._valTrunc = true - } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } - } - } - cb() -} - -UrlEncoded.prototype.end = function () { - if (this.boy._done) { return } - - if (this._state === 'key' && this._key.length > 0) { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - '', - this._keyTrunc, - false) - } else if (this._state === 'val') { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - } - this.boy._done = true - this.boy.emit('finish') -} - -module.exports = UrlEncoded - - -/***/ }), - -/***/ 1496: -/***/ ((module) => { - - - -const RE_PLUS = /\+/g - -const HEX = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -] - -function Decoder () { - this.buffer = undefined -} -Decoder.prototype.write = function (str) { - // Replace '+' with ' ' before decoding - str = str.replace(RE_PLUS, ' ') - let res = '' - let i = 0; let p = 0; const len = str.length - for (; i < len; ++i) { - if (this.buffer !== undefined) { - if (!HEX[str.charCodeAt(i)]) { - res += '%' + this.buffer - this.buffer = undefined - --i // retry character - } else { - this.buffer += str[i] - ++p - if (this.buffer.length === 2) { - res += String.fromCharCode(parseInt(this.buffer, 16)) - this.buffer = undefined - } - } - } else if (str[i] === '%') { - if (i > p) { - res += str.substring(p, i) - p = i - } - this.buffer = '' - ++p - } - } - if (p < len && this.buffer === undefined) { res += str.substring(p) } - return res -} -Decoder.prototype.reset = function () { - this.buffer = undefined -} - -module.exports = Decoder - - -/***/ }), - -/***/ 692: -/***/ ((module) => { - - - -module.exports = function basename (path) { - if (typeof path !== 'string') { return '' } - for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var - switch (path.charCodeAt(i)) { - case 0x2F: // '/' - case 0x5C: // '\' - path = path.slice(i + 1) - return (path === '..' || path === '.' ? '' : path) - } - } - return (path === '..' || path === '.' ? '' : path) -} - - -/***/ }), - -/***/ 2747: -/***/ (function(module) { - - - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue - } - return decoders.other.bind(charset) - } - } -} - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - return data - } - return data.latin1Slice(0, data.length) - }, - - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} - } - return typeof data === 'string' - ? data - : data.toString() - } -} - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text -} - -module.exports = decodeText - - -/***/ }), - -/***/ 2393: -/***/ ((module) => { - - - -module.exports = function getLimit (limits, name, defaultLimit) { - if ( - !limits || - limits[name] === undefined || - limits[name] === null - ) { return defaultLimit } - - if ( - typeof limits[name] !== 'number' || - isNaN(limits[name]) - ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - - return limits[name] -} - - -/***/ }), - -/***/ 8929: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(2747) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' -} - -function encodedReplacer (match) { - return EncodedLookup[match] -} - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } - } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res -} - -module.exports = parseParams - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __nccwpck_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __nccwpck_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; - -// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var lib_core = __nccwpck_require__(7484); -// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js -var github = __nccwpck_require__(3228); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js -//#region rolldown:runtime -var __defProp = Object.defineProperty; -var __export = (target, all) => { - for (var name in all) __defProp(target, name, { - get: all[name], - enumerable: true - }); -}; - -//#endregion - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js -//#region src/singletons/async_local_storage/globals.ts -const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); -const setGlobalAsyncLocalStorageInstance = (instance) => { - globalThis[TRACING_ALS_KEY] = instance; -}; -const globals_getGlobalAsyncLocalStorageInstance = () => { - return globalThis[TRACING_ALS_KEY]; -}; - -//#endregion - -//# sourceMappingURL=globals.js.map -// EXTERNAL MODULE: ./node_modules/decamelize/index.js -var decamelize = __nccwpck_require__(8203); -// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/camelcase/index.js -var camelcase = __nccwpck_require__(5769); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/map_keys.js - - - -//#region src/load/map_keys.ts -function keyToJson(key, map) { - return map?.[key] || decamelize(key); -} -function keyFromJson(key, map) { - return map?.[key] || camelcase(key); -} -function mapKeys(fields, mapper, map) { - const mapped = {}; - for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key]; - return mapped; -} - -//#endregion - -//# sourceMappingURL=map_keys.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/serializable.js - - - -//#region src/load/serializable.ts -var serializable_exports = {}; -__export(serializable_exports, { - Serializable: () => Serializable, - get_lc_unique_name: () => get_lc_unique_name -}); -function shallowCopy(obj) { - return Array.isArray(obj) ? [...obj] : { ...obj }; -} -function replaceSecrets(root, secretsMap) { - const result = shallowCopy(root); - for (const [path, secretId] of Object.entries(secretsMap)) { - const [last, ...partsReverse] = path.split(".").reverse(); - let current = result; - for (const part of partsReverse.reverse()) { - if (current[part] === void 0) break; - current[part] = shallowCopy(current[part]); - current = current[part]; - } - if (current[last] !== void 0) current[last] = { - lc: 1, - type: "secret", - id: [secretId] - }; - } - return result; -} -/** -* Get a unique name for the module, rather than parent class implementations. -* Should not be subclassed, subclass lc_name above instead. -*/ -function get_lc_unique_name(serializableClass) { - const parentClass = Object.getPrototypeOf(serializableClass); - const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); - if (lcNameIsSubclassed) return serializableClass.lc_name(); - else return serializableClass.name; -} -var Serializable = class Serializable { - lc_serializable = false; - lc_kwargs; - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; - } - /** - * A map of secrets, which will be omitted from serialization. - * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". - * Values are the secret ids, which will be used when deserializing. - */ - get lc_secrets() { - return void 0; - } - /** - * A map of additional attributes to merge with constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the attribute values, which will be serialized. - * These attributes need to be accepted by the constructor as arguments. - */ - get lc_attributes() { - return void 0; - } - /** - * A map of aliases for constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the alias that will replace the key in serialization. - * This is used to eg. make argument names match Python. - */ - get lc_aliases() { - return void 0; - } - /** - * A manual list of keys that should be serialized. - * If not overridden, all fields passed into the constructor will be serialized. - */ - get lc_serializable_keys() { - return void 0; - } - constructor(kwargs, ..._args) { - if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); - else this.lc_kwargs = kwargs ?? {}; - } - toJSON() { - if (!this.lc_serializable) return this.toJSONNotImplemented(); - if (this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented(); - const aliases = {}; - const secrets = {}; - const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { - acc[key] = key in this ? this[key] : this.lc_kwargs[key]; - return acc; - }, {}); - for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { - Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); - Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); - Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); - } - Object.keys(secrets).forEach((keyPath) => { - let read = this; - let write = kwargs; - const [last, ...partsReverse] = keyPath.split(".").reverse(); - for (const key of partsReverse.reverse()) { - if (!(key in read) || read[key] === void 0) return; - if (!(key in write) || write[key] === void 0) { - if (typeof read[key] === "object" && read[key] != null) write[key] = {}; - else if (Array.isArray(read[key])) write[key] = []; - } - read = read[key]; - write = write[key]; - } - if (last in read && read[last] !== void 0) write[last] = write[last] || read[last]; - }); - return { - lc: 1, - type: "constructor", - id: this.lc_id, - kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases) - }; - } - toJSONNotImplemented() { - return { - lc: 1, - type: "not_implemented", - id: this.lc_id - }; - } -}; - -//#endregion - -//# sourceMappingURL=serializable.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/data.js -//#region src/messages/content/data.ts -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isDataContentBlock(content_block) { - return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id"); -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isURLContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "url" && "url" in content_block && typeof content_block.url === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isBase64ContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "base64" && "data" in content_block && typeof content_block.data === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isPlainTextContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "text" && "text" in content_block && typeof content_block.text === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isIDContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "id" && "id" in content_block && typeof content_block.id === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function convertToOpenAIImageBlock(content_block) { - if (isDataContentBlock(content_block)) { - if (content_block.source_type === "url") return { - type: "image_url", - image_url: { url: content_block.url } - }; - if (content_block.source_type === "base64") { - if (!content_block.mime_type) throw new Error("mime_type key is required for base64 data."); - const mime_type = content_block.mime_type; - return { - type: "image_url", - image_url: { url: `data:${mime_type};base64,${content_block.data}` } - }; - } - } - throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); -} -/** -* Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters. -* -* @param mime_type - The mime type to parse. -* @returns An object containing the type, subtype, and parameters. -* -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function parseMimeType(mime_type) { - const parts = mime_type.split(";")[0].split("/"); - if (parts.length !== 2) throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); - const type = parts[0].trim(); - const subtype = parts[1].trim(); - if (type === "" || subtype === "") throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); - const parameters = {}; - for (const parameterKvp of mime_type.split(";").slice(1)) { - const parameterParts = parameterKvp.split("="); - if (parameterParts.length !== 2) throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); - const key = parameterParts[0].trim(); - const value = parameterParts[1].trim(); - if (key === "") throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); - parameters[key] = value; - } - return { - type, - subtype, - parameters - }; -} -/** -* Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string. -* -* @param dataUrl - The base64 data URL to parse. -* @param asTypedArray - Whether to return the data as a typed array. -* @returns The parsed data and mime type, or undefined if the data URL is invalid. -* -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) { - const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); - let mime_type; - if (formatMatch) { - mime_type = formatMatch[1].toLowerCase(); - const data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2]; - return { - mime_type, - data - }; - } - return void 0; -} -/** -* Convert from a standard data content block to a provider's proprietary data content block format. -* -* Don't override this method. Instead, override the more specific conversion methods and use this -* method unmodified. -* -* @param block - The standard data content block to convert. -* @returns The provider data content block. -* @throws An error if the standard data content block type is not supported. -* -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function convertToProviderContentBlock(block, converter) { - if (block.type === "text") { - if (!converter.fromStandardTextBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); - return converter.fromStandardTextBlock(block); - } - if (block.type === "image") { - if (!converter.fromStandardImageBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); - return converter.fromStandardImageBlock(block); - } - if (block.type === "audio") { - if (!converter.fromStandardAudioBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); - return converter.fromStandardAudioBlock(block); - } - if (block.type === "file") { - if (!converter.fromStandardFileBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); - return converter.fromStandardFileBlock(block); - } - throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); -} - -//#endregion - -//# sourceMappingURL=data.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/utils.js -//#region src/messages/block_translators/utils.ts -function _isContentBlock(block, type) { - return _isObject(block) && block.type === type; -} -function _isObject(value) { - return typeof value === "object" && value !== null; -} -function _isArray(value) { - return Array.isArray(value); -} -function _isString(value) { - return typeof value === "string"; -} -function _isNumber(value) { - return typeof value === "number"; -} -function _isBytesArray(value) { - return value instanceof Uint8Array; -} -function safeParseJson(value) { - try { - return JSON.parse(value); - } catch { - return void 0; - } -} -const iife = (fn) => fn(); - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/anthropic.js - - -//#region src/messages/block_translators/anthropic.ts -function convertAnthropicAnnotation(citation) { - if (citation.type === "char_location" && _isString(citation.document_title) && _isNumber(citation.start_char_index) && _isNumber(citation.end_char_index) && _isString(citation.cited_text)) { - const { document_title, start_char_index, end_char_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "char", - title: document_title ?? void 0, - startIndex: start_char_index, - endIndex: end_char_index, - citedText: cited_text - }; - } - if (citation.type === "page_location" && _isString(citation.document_title) && _isNumber(citation.start_page_number) && _isNumber(citation.end_page_number) && _isString(citation.cited_text)) { - const { document_title, start_page_number, end_page_number, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "page", - title: document_title ?? void 0, - startIndex: start_page_number, - endIndex: end_page_number, - citedText: cited_text - }; - } - if (citation.type === "content_block_location" && _isString(citation.document_title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { - const { document_title, start_block_index, end_block_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "block", - title: document_title ?? void 0, - startIndex: start_block_index, - endIndex: end_block_index, - citedText: cited_text - }; - } - if (citation.type === "web_search_result_location" && _isString(citation.url) && _isString(citation.title) && _isString(citation.encrypted_index) && _isString(citation.cited_text)) { - const { url, title, encrypted_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "url", - url, - title, - startIndex: Number(encrypted_index), - endIndex: Number(encrypted_index), - citedText: cited_text - }; - } - if (citation.type === "search_result_location" && _isString(citation.source) && _isString(citation.title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { - const { source, title, start_block_index, end_block_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "search", - url: source, - title: title ?? void 0, - startIndex: start_block_index, - endIndex: end_block_index, - citedText: cited_text - }; - } - return void 0; -} -/** -* Converts an Anthropic content block to a standard V1 content block. -* -* This function handles the conversion of Anthropic-specific content blocks -* (document and image blocks) to the standardized V1 format. It supports -* various source types including base64 data, URLs, file IDs, and text data. -* -* @param block - The Anthropic content block to convert -* @returns A standard V1 content block if conversion is successful, undefined otherwise -* -* @example -* ```typescript -* const anthropicBlock = { -* type: "image", -* source: { -* type: "base64", -* media_type: "image/png", -* data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" -* } -* }; -* -* const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock); -* // Returns: { type: "image", mimeType: "image/png", data: "..." } -* ``` -*/ -function convertToV1FromAnthropicContentBlock(block) { - if (_isContentBlock(block, "document") && _isObject(block.source) && "type" in block.source) { - if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { - type: "file", - mimeType: block.source.media_type, - data: block.source.data - }; - else if (block.source.type === "url" && _isString(block.source.url)) return { - type: "file", - url: block.source.url - }; - else if (block.source.type === "file" && _isString(block.source.file_id)) return { - type: "file", - fileId: block.source.file_id - }; - else if (block.source.type === "text" && _isString(block.source.data)) return { - type: "file", - mimeType: String(block.source.media_type ?? "text/plain"), - data: block.source.data - }; - } else if (_isContentBlock(block, "image") && _isObject(block.source) && "type" in block.source) { - if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { - type: "image", - mimeType: block.source.media_type, - data: block.source.data - }; - else if (block.source.type === "url" && _isString(block.source.url)) return { - type: "image", - url: block.source.url - }; - else if (block.source.type === "file" && _isString(block.source.file_id)) return { - type: "image", - fileId: block.source.file_id - }; - } - return void 0; -} -/** -* Converts an array of content blocks from Anthropic format to v1 standard format. -* -* This function processes each content block in the input array, attempting to convert -* Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.) -* to the standardized v1 content block format. If a block cannot be converted, it is -* passed through as-is with a type assertion to ContentBlock.Standard. -* -* @param content - Array of content blocks in Anthropic format to be converted -* @returns Array of content blocks in v1 standard format -*/ -function convertToV1FromAnthropicInput(content) { - function* iterateContent() { - for (const block of content) { - const stdBlock = convertToV1FromAnthropicContentBlock(block); - if (stdBlock) yield stdBlock; - else yield block; - } - } - return Array.from(iterateContent()); -} -/** -* Converts an Anthropic AI message to an array of v1 standard content blocks. -* -* This function processes an AI message containing Anthropic-specific content blocks -* and converts them to the standardized v1 content block format. -* -* @param message - The AI message containing Anthropic-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const message = new AIMessage([ -* { type: "text", text: "Hello world" }, -* { type: "thinking", text: "Let me think about this..." }, -* { type: "tool_use", id: "123", name: "calculator", input: { a: 1, b: 2 } } -* ]); -* -* const standardBlocks = convertToV1FromAnthropicMessage(message); -* // Returns: -* // [ -* // { type: "text", text: "Hello world" }, -* // { type: "reasoning", reasoning: "Let me think about this..." }, -* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } } -* // ] -* ``` -*/ -function convertToV1FromAnthropicMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "text") && _isString(block.text)) { - const { text, citations,...rest } = block; - if (_isArray(citations) && citations.length) { - const _citations = citations.reduce((acc, item) => { - const citation = convertAnthropicAnnotation(item); - if (citation) return [...acc, citation]; - return acc; - }, []); - yield { - ...rest, - type: "text", - text, - annotations: _citations - }; - continue; - } else { - yield { - ...rest, - type: "text", - text - }; - continue; - } - } else if (_isContentBlock(block, "thinking") && _isString(block.thinking)) { - const { thinking, signature,...rest } = block; - yield { - ...rest, - type: "reasoning", - reasoning: thinking, - signature - }; - continue; - } else if (_isContentBlock(block, "redacted_thinking")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "tool_use") && _isString(block.name) && _isString(block.id)) { - yield { - type: "tool_call", - id: block.id, - name: block.name, - args: block.input - }; - continue; - } else if (_isContentBlock(block, "input_json_delta")) { - if (_isAIMessageChunk(message) && message.tool_call_chunks?.length) { - const tool_call_chunk = message.tool_call_chunks[0]; - yield { - type: "tool_call_chunk", - id: tool_call_chunk.id, - name: tool_call_chunk.name, - args: tool_call_chunk.args, - index: tool_call_chunk.index - }; - continue; - } - } else if (_isContentBlock(block, "server_tool_use") && _isString(block.name) && _isString(block.id)) { - const { name, id } = block; - if (name === "web_search") { - const query = iife(() => { - if (typeof block.input === "string") return block.input; - else if (_isObject(block.input) && _isString(block.input.query)) return block.input.query; - else if (_isString(block.partial_json)) { - const json = safeParseJson(block.partial_json); - if (json?.query) return json.query; - } - return ""; - }); - yield { - id, - type: "server_tool_call", - name: "web_search", - args: { query } - }; - continue; - } else if (block.name === "code_execution") { - const code = iife(() => { - if (typeof block.input === "string") return block.input; - else if (_isObject(block.input) && _isString(block.input.code)) return block.input.code; - else if (_isString(block.partial_json)) { - const json = safeParseJson(block.partial_json); - if (json?.code) return json.code; - } - return ""; - }); - yield { - id, - type: "server_tool_call", - name: "code_execution", - args: { code } - }; - continue; - } - } else if (_isContentBlock(block, "web_search_tool_result") && _isString(block.tool_use_id) && _isArray(block.content)) { - const { content: content$1, tool_use_id } = block; - const urls = content$1.reduce((acc, content$2) => { - if (_isContentBlock(content$2, "web_search_result")) return [...acc, content$2.url]; - return acc; - }, []); - yield { - type: "server_tool_call_result", - name: "web_search", - toolCallId: tool_use_id, - status: "success", - output: { urls } - }; - continue; - } else if (_isContentBlock(block, "code_execution_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { - yield { - type: "server_tool_call_result", - name: "code_execution", - toolCallId: block.tool_use_id, - status: "success", - output: block.content - }; - continue; - } else if (_isContentBlock(block, "mcp_tool_use")) { - yield { - id: block.id, - type: "server_tool_call", - name: "mcp_tool_use", - args: block.input - }; - continue; - } else if (_isContentBlock(block, "mcp_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { - yield { - type: "server_tool_call_result", - name: "mcp_tool_use", - toolCallId: block.tool_use_id, - status: "success", - output: block.content - }; - continue; - } else if (_isContentBlock(block, "container_upload")) { - yield { - type: "server_tool_call", - name: "container_upload", - args: block.input - }; - continue; - } else if (_isContentBlock(block, "search_result")) { - yield { - id: block.id, - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "tool_result")) { - yield { - id: block.id, - type: "non_standard", - value: block - }; - continue; - } else { - const stdBlock = convertToV1FromAnthropicContentBlock(block); - if (stdBlock) { - yield stdBlock; - continue; - } - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatAnthropicTranslator = { - translateContent: convertToV1FromAnthropicMessage, - translateContentChunk: convertToV1FromAnthropicMessage -}; -function _isAIMessageChunk(message) { - return typeof message?._getType === "function" && typeof message.concat === "function" && message._getType() === "ai"; -} - -//#endregion - -//# sourceMappingURL=anthropic.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/data.js - - - -//#region src/messages/block_translators/data.ts -function convertToV1FromDataContentBlock(block) { - if (isURLContentBlock(block)) return { - type: block.type, - mimeType: block.mime_type, - url: block.url, - metadata: block.metadata - }; - if (isBase64ContentBlock(block)) return { - type: block.type, - mimeType: block.mime_type ?? "application/octet-stream", - data: block.data, - metadata: block.metadata - }; - if (isIDContentBlock(block)) return { - type: block.type, - mimeType: block.mime_type, - fileId: block.id, - metadata: block.metadata - }; - return block; -} -function convertToV1FromDataContent(content) { - return content.map(convertToV1FromDataContentBlock); -} -function isOpenAIDataBlock(block) { - if (_isContentBlock(block, "image_url") && _isObject(block.image_url)) return true; - if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio)) return true; - if (_isContentBlock(block, "file") && _isObject(block.file)) return true; - return false; -} -function convertToV1FromOpenAIDataBlock(block) { - if (_isContentBlock(block, "image_url") && _isObject(block.image_url) && _isString(block.image_url.url)) { - const parsed = parseBase64DataUrl({ dataUrl: block.image_url.url }); - if (parsed) return { - type: "image", - mimeType: parsed.mime_type, - data: parsed.data - }; - else return { - type: "image", - url: block.image_url.url - }; - } else if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio) && _isString(block.input_audio.data) && _isString(block.input_audio.format)) return { - type: "audio", - data: block.input_audio.data, - mimeType: `audio/${block.input_audio.format}` - }; - else if (_isContentBlock(block, "file") && _isObject(block.file) && _isString(block.file.data)) { - const parsed = parseBase64DataUrl({ dataUrl: block.file.data }); - if (parsed) return { - type: "file", - data: parsed.data, - mimeType: parsed.mime_type - }; - else if (_isString(block.file.file_id)) return { - type: "file", - fileId: block.file.file_id - }; - } - return block; -} - -//#endregion - -//# sourceMappingURL=data.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/openai.js - - - -//#region src/messages/block_translators/openai.ts -/** -* Converts a ChatOpenAICompletions message to an array of v1 standard content blocks. -* -* This function processes an AI message from ChatOpenAICompletions API format -* and converts it to the standardized v1 content block format. It handles both -* string content and structured content blocks, as well as tool calls. -* -* @param message - The AI message containing ChatOpenAICompletions formatted content -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const message = new AIMessage("Hello world"); -* const standardBlocks = convertToV1FromChatCompletions(message); -* // Returns: [{ type: "text", text: "Hello world" }] -* ``` -* -* @example -* ```typescript -* const message = new AIMessage([ -* { type: "text", text: "Hello" }, -* { type: "image_url", image_url: { url: "https://example.com/image.png" } } -* ]); -* message.tool_calls = [ -* { id: "call_123", name: "calculator", args: { a: 1, b: 2 } } -* ]; -* -* const standardBlocks = convertToV1FromChatCompletions(message); -* // Returns: -* // [ -* // { type: "text", text: "Hello" }, -* // { type: "image", url: "https://example.com/image.png" }, -* // { type: "tool_call", id: "call_123", name: "calculator", args: { a: 1, b: 2 } } -* // ] -* ``` -*/ -function convertToV1FromChatCompletions(message) { - const blocks = []; - if (typeof message.content === "string") blocks.push({ - type: "text", - text: message.content - }); - else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); - for (const toolCall of message.tool_calls ?? []) blocks.push({ - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }); - return blocks; -} -/** -* Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks. -* -* This function processes an AI message chunk from OpenAI's chat completions API and converts -* it to the standardized v1 content block format. It handles both string and array content, -* as well as tool calls that may be present in the chunk. -* -* @param message - The AI message chunk containing OpenAI-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const chunk = new AIMessage("Hello"); -* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); -* // Returns: [{ type: "text", text: "Hello" }] -* ``` -* -* @example -* ```typescript -* const chunk = new AIMessage([ -* { type: "text", text: "Processing..." } -* ]); -* chunk.tool_calls = [ -* { id: "call_456", name: "search", args: { query: "test" } } -* ]; -* -* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); -* // Returns: -* // [ -* // { type: "text", text: "Processing..." }, -* // { type: "tool_call", id: "call_456", name: "search", args: { query: "test" } } -* // ] -* ``` -*/ -function convertToV1FromChatCompletionsChunk(message) { - const blocks = []; - if (typeof message.content === "string") blocks.push({ - type: "text", - text: message.content - }); - else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); - for (const toolCall of message.tool_calls ?? []) blocks.push({ - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }); - return blocks; -} -/** -* Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks. -* -* This function processes content blocks from OpenAI's Chat Completions API format -* and converts them to the standardized v1 content block format. It handles both -* OpenAI-specific data blocks (which require conversion) and standard blocks -* (which are passed through with type assertion). -* -* @param blocks - Array of content blocks in ChatOpenAICompletions format -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const openaiBlocks = [ -* { type: "text", text: "Hello world" }, -* { type: "image_url", image_url: { url: "https://example.com/image.png" } } -* ]; -* -* const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks); -* // Returns: -* // [ -* // { type: "text", text: "Hello world" }, -* // { type: "image", url: "https://example.com/image.png" } -* // ] -* ``` -*/ -function convertToV1FromChatCompletionsInput(blocks) { - const convertedBlocks = []; - for (const block of blocks) if (isOpenAIDataBlock(block)) convertedBlocks.push(convertToV1FromOpenAIDataBlock(block)); - else convertedBlocks.push(block); - return convertedBlocks; -} -function convertResponsesAnnotation(annotation) { - if (annotation.type === "url_citation") { - const { url, title, start_index, end_index } = annotation; - return { - type: "citation", - url, - title, - startIndex: start_index, - endIndex: end_index - }; - } - if (annotation.type === "file_citation") { - const { file_id, filename, index } = annotation; - return { - type: "citation", - title: filename, - startIndex: index, - endIndex: index, - fileId: file_id - }; - } - return annotation; -} -/** -* Converts a ChatOpenAIResponses message to an array of v1 standard content blocks. -* -* This function processes an AI message containing OpenAI Responses-specific content blocks -* and converts them to the standardized v1 content block format. It handles reasoning summaries, -* text content with annotations, tool calls, and various tool outputs including code interpreter, -* web search, file search, computer calls, and MCP-related blocks. -* -* @param message - The AI message containing OpenAI Responses-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const message = new AIMessage({ -* content: [{ type: "text", text: "Hello world", annotations: [] }], -* tool_calls: [{ id: "123", name: "calculator", args: { a: 1, b: 2 } }], -* additional_kwargs: { -* reasoning: { summary: [{ text: "Let me calculate this..." }] }, -* tool_outputs: [ -* { -* type: "code_interpreter_call", -* code: "print('hello')", -* outputs: [{ type: "logs", logs: "hello" }] -* } -* ] -* } -* }); -* -* const standardBlocks = convertToV1FromResponses(message); -* // Returns: -* // [ -* // { type: "reasoning", reasoning: "Let me calculate this..." }, -* // { type: "text", text: "Hello world", annotations: [] }, -* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } }, -* // { type: "code_interpreter_call", code: "print('hello')" }, -* // { type: "code_interpreter_result", output: [{ type: "code_interpreter_output", returnCode: 0, stdout: "hello" }] } -* // ] -* ``` -*/ -function convertToV1FromResponses(message) { - function* iterateContent() { - if (_isObject(message.additional_kwargs?.reasoning) && _isArray(message.additional_kwargs.reasoning.summary)) { - const summary = message.additional_kwargs.reasoning.summary.reduce((acc, item) => { - if (_isObject(item) && _isString(item.text)) return `${acc}${item.text}`; - return acc; - }, ""); - yield { - type: "reasoning", - reasoning: summary - }; - } - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) if (_isContentBlock(block, "text")) { - const { text, annotations,...rest } = block; - if (Array.isArray(annotations)) yield { - ...rest, - type: "text", - text: String(text), - annotations: annotations.map(convertResponsesAnnotation) - }; - else yield { - ...rest, - type: "text", - text: String(text) - }; - } - for (const toolCall of message.tool_calls ?? []) yield { - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }; - if (_isObject(message.additional_kwargs) && _isArray(message.additional_kwargs.tool_outputs)) for (const toolOutput of message.additional_kwargs.tool_outputs) { - if (_isContentBlock(toolOutput, "web_search_call")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "web_search", - args: { query: toolOutput.query } - }; - continue; - } else if (_isContentBlock(toolOutput, "file_search_call")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "file_search", - args: { query: toolOutput.query } - }; - continue; - } else if (_isContentBlock(toolOutput, "computer_call")) { - yield { - type: "non_standard", - value: toolOutput - }; - continue; - } else if (_isContentBlock(toolOutput, "code_interpreter_call")) { - if (_isString(toolOutput.code)) yield { - id: toolOutput.id, - type: "server_tool_call", - name: "code_interpreter", - args: { code: toolOutput.code } - }; - if (_isArray(toolOutput.outputs)) { - const returnCode = iife(() => { - if (toolOutput.status === "in_progress") return void 0; - if (toolOutput.status === "completed") return 0; - if (toolOutput.status === "incomplete") return 127; - if (toolOutput.status === "interpreting") return void 0; - if (toolOutput.status === "failed") return 1; - return void 0; - }); - for (const output of toolOutput.outputs) if (_isContentBlock(output, "logs")) { - yield { - type: "server_tool_call_result", - toolCallId: toolOutput.id ?? "", - status: "success", - output: { - type: "code_interpreter_output", - returnCode: returnCode ?? 0, - stderr: [0, void 0].includes(returnCode) ? void 0 : String(output.logs), - stdout: [0, void 0].includes(returnCode) ? String(output.logs) : void 0 - } - }; - continue; - } - } - continue; - } else if (_isContentBlock(toolOutput, "mcp_call")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "mcp_call", - args: toolOutput.input - }; - continue; - } else if (_isContentBlock(toolOutput, "mcp_list_tools")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "mcp_list_tools", - args: toolOutput.input - }; - continue; - } else if (_isContentBlock(toolOutput, "mcp_approval_request")) { - yield { - type: "non_standard", - value: toolOutput - }; - continue; - } else if (_isContentBlock(toolOutput, "image_generation_call")) { - yield { - type: "non_standard", - value: toolOutput - }; - continue; - } - if (_isObject(toolOutput)) yield { - type: "non_standard", - value: toolOutput - }; - } - } - return Array.from(iterateContent()); -} -/** -* Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks. -* -* This function processes an AI message chunk containing OpenAI-specific content blocks -* and converts them to the standardized v1 content block format. It handles both the -* regular message content and tool call chunks that are specific to streaming responses. -* -* @param message - The AI message chunk containing OpenAI-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const messageChunk = new AIMessageChunk({ -* content: [{ type: "text", text: "Hello" }], -* tool_call_chunks: [ -* { id: "call_123", name: "calculator", args: '{"a": 1' } -* ] -* }); -* -* const standardBlocks = convertToV1FromResponsesChunk(messageChunk); -* // Returns: -* // [ -* // { type: "text", text: "Hello" }, -* // { type: "tool_call_chunk", id: "call_123", name: "calculator", args: '{"a": 1' } -* // ] -* ``` -*/ -function convertToV1FromResponsesChunk(message) { - function* iterateContent() { - yield* convertToV1FromResponses(message); - for (const toolCallChunk of message.tool_call_chunks ?? []) yield { - type: "tool_call_chunk", - id: toolCallChunk.id, - name: toolCallChunk.name, - args: toolCallChunk.args - }; - } - return Array.from(iterateContent()); -} -const ChatOpenAITranslator = { - translateContent: (message) => { - if (typeof message.content === "string") return convertToV1FromChatCompletions(message); - return convertToV1FromResponses(message); - }, - translateContentChunk: (message) => { - if (typeof message.content === "string") return convertToV1FromChatCompletionsChunk(message); - return convertToV1FromResponsesChunk(message); - } -}; - -//#endregion - -//# sourceMappingURL=openai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/message.js -//#region src/messages/message.ts -/** -* Type guard to check if a value is a valid Message object. -* -* @param message - The value to check -* @returns true if the value is a valid Message object, false otherwise -*/ -function isMessage(message) { - return typeof message === "object" && message !== null && "type" in message && "content" in message && (typeof message.content === "string" || Array.isArray(message.content)); -} - -//#endregion - -//# sourceMappingURL=message.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/format.js -//#region src/messages/format.ts -function convertToFormattedString(message, format = "pretty") { - if (format === "pretty") return convertToPrettyString(message); - return JSON.stringify(message); -} -function convertToPrettyString(message) { - const lines = []; - const title = ` ${message.type.charAt(0).toUpperCase() + message.type.slice(1)} Message `; - const sepLen = Math.floor((80 - title.length) / 2); - const sep = "=".repeat(sepLen); - const secondSep = title.length % 2 === 0 ? sep : `${sep}=`; - lines.push(`${sep}${title}${secondSep}`); - if (message.type === "ai") { - const aiMessage = message; - if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) { - lines.push("Tool Calls:"); - for (const tc of aiMessage.tool_calls) { - lines.push(` ${tc.name} (${tc.id})`); - lines.push(` Call ID: ${tc.id}`); - lines.push(" Args:"); - for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${value}`); - } - } - } - if (message.type === "tool") { - const toolMessage = message; - if (toolMessage.name) lines.push(`Name: ${toolMessage.name}`); - } - if (typeof message.content === "string" && message.content.trim()) { - if (lines.length > 1) lines.push(""); - lines.push(message.content); - } - return lines.join("\n"); -} - -//#endregion - -//# sourceMappingURL=format.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/base.js - - - - - - - - -//#region src/messages/base.ts -/** @internal */ -const MESSAGE_SYMBOL = Symbol.for("langchain.message"); -function mergeContent(firstContent, secondContent) { - if (typeof firstContent === "string") { - if (firstContent === "") return secondContent; - if (typeof secondContent === "string") return firstContent + secondContent; - else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) return [{ - type: "text", - source_type: "text", - text: firstContent - }, ...secondContent]; - else return [{ - type: "text", - text: firstContent - }, ...secondContent]; - } else if (Array.isArray(secondContent)) return _mergeLists(firstContent, secondContent) ?? [...firstContent, ...secondContent]; - else if (secondContent === "") return firstContent; - else if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) return [...firstContent, { - type: "file", - source_type: "text", - text: secondContent - }]; - else return [...firstContent, { - type: "text", - text: secondContent - }]; -} -/** -* 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else -* it will return 'success'. -* -* @param {"success" | "error" | undefined} left The existing value to 'merge' with the new value. -* @param {"success" | "error" | undefined} right The new value to 'merge' with the existing value -* @returns {"success" | "error"} The 'merged' value. -*/ -function _mergeStatus(left, right) { - if (left === "error" || right === "error") return "error"; - return "success"; -} -function stringifyWithDepthLimit(obj, depthLimit) { - function helper(obj$1, currentDepth) { - if (typeof obj$1 !== "object" || obj$1 === null || obj$1 === void 0) return obj$1; - if (currentDepth >= depthLimit) { - if (Array.isArray(obj$1)) return "[Array]"; - return "[Object]"; - } - if (Array.isArray(obj$1)) return obj$1.map((item) => helper(item, currentDepth + 1)); - const result = {}; - for (const key of Object.keys(obj$1)) result[key] = helper(obj$1[key], currentDepth + 1); - return result; - } - return JSON.stringify(helper(obj, 0), null, 2); -} -/** -* Base class for all types of messages in a conversation. It includes -* properties like `content`, `name`, and `additional_kwargs`. It also -* includes methods like `toDict()` and `_getType()`. -*/ -var BaseMessage = class extends Serializable { - lc_namespace = ["langchain_core", "messages"]; - lc_serializable = true; - get lc_aliases() { - return { - additional_kwargs: "additional_kwargs", - response_metadata: "response_metadata" - }; - } - [MESSAGE_SYMBOL] = true; - id; - name; - content; - additional_kwargs; - response_metadata; - /** - * @deprecated Use .getType() instead or import the proper typeguard. - * For example: - * - * ```ts - * import { isAIMessage } from "@langchain/core/messages"; - * - * const message = new AIMessage("Hello!"); - * isAIMessage(message); // true - * ``` - */ - _getType() { - return this.type; - } - /** - * @deprecated Use .type instead - * The type of the message. - */ - getType() { - return this._getType(); - } - constructor(arg) { - const fields = typeof arg === "string" || Array.isArray(arg) ? { content: arg } : arg; - if (!fields.additional_kwargs) fields.additional_kwargs = {}; - if (!fields.response_metadata) fields.response_metadata = {}; - super(fields); - this.name = fields.name; - if (fields.content === void 0 && fields.contentBlocks !== void 0) { - this.content = fields.contentBlocks; - this.response_metadata = { - output_version: "v1", - ...fields.response_metadata - }; - } else if (fields.content !== void 0) { - this.content = fields.content ?? []; - this.response_metadata = fields.response_metadata; - } else { - this.content = []; - this.response_metadata = fields.response_metadata; - } - this.additional_kwargs = fields.additional_kwargs; - this.id = fields.id; - } - /** Get text content of the message. */ - get text() { - if (typeof this.content === "string") return this.content; - if (!Array.isArray(this.content)) return ""; - return this.content.map((c) => { - if (typeof c === "string") return c; - if (c.type === "text") return c.text; - return ""; - }).join(""); - } - get contentBlocks() { - const blocks = typeof this.content === "string" ? [{ - type: "text", - text: this.content - }] : this.content; - const parsingSteps = [ - convertToV1FromDataContent, - convertToV1FromChatCompletionsInput, - convertToV1FromAnthropicInput - ]; - const parsedBlocks = parsingSteps.reduce((blocks$1, step) => step(blocks$1), blocks); - return parsedBlocks; - } - toDict() { - return { - type: this.getType(), - data: this.toJSON().kwargs - }; - } - static lc_name() { - return "BaseMessage"; - } - get _printableFields() { - return { - id: this.id, - content: this.content, - name: this.name, - additional_kwargs: this.additional_kwargs, - response_metadata: this.response_metadata - }; - } - static isInstance(obj) { - return typeof obj === "object" && obj !== null && MESSAGE_SYMBOL in obj && obj[MESSAGE_SYMBOL] === true && isMessage(obj); - } - _updateId(value) { - this.id = value; - this.lc_kwargs.id = value; - } - get [Symbol.toStringTag]() { - return this.constructor.lc_name(); - } - [Symbol.for("nodejs.util.inspect.custom")](depth) { - if (depth === null) return this; - const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); - return `${this.constructor.lc_name()} ${printable}`; - } - toFormattedString(format = "pretty") { - return convertToFormattedString(this, format); - } -}; -function isOpenAIToolCallArray(value) { - return Array.isArray(value) && value.every((v) => typeof v.index === "number"); -} -function _mergeDicts(left = {}, right = {}) { - const merged = { ...left }; - for (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value; - else if (value == null) continue; - else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); - else if (typeof merged[key] === "string") if (key === "type") continue; - else if ([ - "id", - "name", - "output_version", - "model_provider" - ].includes(key)) merged[key] = value; - else merged[key] += value; - else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value); - else if (Array.isArray(merged[key])) merged[key] = _mergeLists(merged[key], value); - else if (merged[key] === value) continue; - else console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); - return merged; -} -function _mergeLists(left, right) { - if (left === void 0 && right === void 0) return void 0; - else if (left === void 0 || right === void 0) return left || right; - else { - const merged = [...left]; - for (const item of right) if (typeof item === "object" && item !== null && "index" in item && typeof item.index === "number") { - const toMerge = merged.findIndex((leftItem) => { - const isObject = typeof leftItem === "object"; - const indiciesMatch = "index" in leftItem && leftItem.index === item.index; - const idsMatch = "id" in leftItem && "id" in item && leftItem?.id === item?.id; - const eitherItemMissingID = !("id" in leftItem) || !leftItem?.id || !("id" in item) || !item?.id; - return isObject && indiciesMatch && (idsMatch || eitherItemMissingID); - }); - if (toMerge !== -1 && typeof merged[toMerge] === "object" && merged[toMerge] !== null) merged[toMerge] = _mergeDicts(merged[toMerge], item); - else merged.push(item); - } else if (typeof item === "object" && item !== null && "text" in item && item.text === "") continue; - else merged.push(item); - return merged; - } -} -function _mergeObj(left, right) { - if (!left && !right) throw new Error("Cannot merge two undefined objects."); - if (!left || !right) return left || right; - else if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`); - else if (typeof left === "string" && typeof right === "string") return left + right; - else if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right); - else if (typeof left === "object" && typeof right === "object") return _mergeDicts(left, right); - else if (left === right) return left; - else throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`); -} -/** -* Represents a chunk of a message, which can be concatenated with other -* message chunks. It includes a method `_merge_kwargs_dict()` for merging -* additional keyword arguments from another `BaseMessageChunk` into this -* one. It also overrides the `__add__()` method to support concatenation -* of `BaseMessageChunk` instances. -*/ -var BaseMessageChunk = class extends BaseMessage { - static isInstance(obj) { - return super.isInstance(obj) && "concat" in obj && typeof obj.concat === "function"; - } -}; -function _isMessageFieldWithRole(x) { - return typeof x.role === "string"; -} -/** -* @deprecated Use {@link BaseMessage.isInstance} instead -*/ -function isBaseMessage(messageLike) { - return typeof messageLike?._getType === "function"; -} -/** -* @deprecated Use {@link BaseMessageChunk.isInstance} instead -*/ -function isBaseMessageChunk(messageLike) { - return isBaseMessage(messageLike) && typeof messageLike.concat === "function"; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/tool.js - - - -//#region src/messages/tool.ts -var tool_exports = {}; -__export(tool_exports, { - ToolMessage: () => ToolMessage, - ToolMessageChunk: () => ToolMessageChunk, - defaultToolCallParser: () => defaultToolCallParser, - isDirectToolOutput: () => isDirectToolOutput, - isToolMessage: () => isToolMessage, - isToolMessageChunk: () => isToolMessageChunk -}); -function isDirectToolOutput(x) { - return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true; -} -/** -* Represents a tool message in a conversation. -*/ -var ToolMessage = class extends BaseMessage { - static lc_name() { - return "ToolMessage"; - } - get lc_aliases() { - return { tool_call_id: "tool_call_id" }; - } - lc_direct_tool_output = true; - type = "tool"; - /** - * Status of the tool invocation. - * @version 0.2.19 - */ - status; - tool_call_id; - metadata; - /** - * Artifact of the Tool execution which is not meant to be sent to the model. - * - * Should only be specified if it is different from the message content, e.g. if only - * a subset of the full tool output is being passed as message content but the full - * output is needed in other parts of the code. - */ - artifact; - constructor(fields, tool_call_id, name) { - const toolMessageFields = typeof fields === "string" || Array.isArray(fields) ? { - content: fields, - name, - tool_call_id - } : fields; - super(toolMessageFields); - this.tool_call_id = toolMessageFields.tool_call_id; - this.artifact = toolMessageFields.artifact; - this.status = toolMessageFields.status; - this.metadata = toolMessageFields.metadata; - } - static isInstance(message) { - return super.isInstance(message) && message.type === "tool"; - } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact - }; - } -}; -/** -* Represents a chunk of a tool message, which can be concatenated -* with other tool message chunks. -*/ -var ToolMessageChunk = class extends BaseMessageChunk { - type = "tool"; - tool_call_id; - /** - * Status of the tool invocation. - * @version 0.2.19 - */ - status; - /** - * Artifact of the Tool execution which is not meant to be sent to the model. - * - * Should only be specified if it is different from the message content, e.g. if only - * a subset of the full tool output is being passed as message content but the full - * output is needed in other parts of the code. - */ - artifact; - constructor(fields) { - super(fields); - this.tool_call_id = fields.tool_call_id; - this.artifact = fields.artifact; - this.status = fields.status; - } - static lc_name() { - return "ToolMessageChunk"; - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - artifact: _mergeObj(this.artifact, chunk.artifact), - tool_call_id: this.tool_call_id, - id: this.id ?? chunk.id, - status: _mergeStatus(this.status, chunk.status) - }); - } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact - }; - } -}; -function defaultToolCallParser(rawToolCalls) { - const toolCalls = []; - const invalidToolCalls = []; - for (const toolCall of rawToolCalls) if (!toolCall.function) continue; - else { - const functionName = toolCall.function.name; - try { - const functionArgs = JSON.parse(toolCall.function.arguments); - toolCalls.push({ - name: functionName || "", - args: functionArgs || {}, - id: toolCall.id - }); - } catch { - invalidToolCalls.push({ - name: functionName, - args: toolCall.function.arguments, - id: toolCall.id, - error: "Malformed args." - }); - } - } - return [toolCalls, invalidToolCalls]; -} -/** -* @deprecated Use {@link ToolMessage.isInstance} instead -*/ -function isToolMessage(x) { - return typeof x === "object" && x !== null && "getType" in x && typeof x.getType === "function" && x.getType() === "tool"; -} -/** -* @deprecated Use {@link ToolMessageChunk.isInstance} instead -*/ -function isToolMessageChunk(x) { - return x._getType() === "tool"; -} - -//#endregion - -//# sourceMappingURL=tool.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json.js -//#region src/utils/json.ts -function parseJsonMarkdown(s, parser = parsePartialJson) { - s = s.trim(); - const firstFenceIndex = s.indexOf("```"); - if (firstFenceIndex === -1) return parser(s); - let contentAfterFence = s.substring(firstFenceIndex + 3); - if (contentAfterFence.startsWith("json\n")) contentAfterFence = contentAfterFence.substring(5); - else if (contentAfterFence.startsWith("json")) contentAfterFence = contentAfterFence.substring(4); - else if (contentAfterFence.startsWith("\n")) contentAfterFence = contentAfterFence.substring(1); - const closingFenceIndex = contentAfterFence.indexOf("```"); - let finalContent = contentAfterFence; - if (closingFenceIndex !== -1) finalContent = contentAfterFence.substring(0, closingFenceIndex); - return parser(finalContent.trim()); -} -function parsePartialJson(s) { - if (typeof s === "undefined") return null; - try { - return JSON.parse(s); - } catch {} - let new_s = ""; - const stack = []; - let isInsideString = false; - let escaped = false; - for (let char of s) { - if (isInsideString) if (char === "\"" && !escaped) isInsideString = false; - else if (char === "\n" && !escaped) char = "\\n"; - else if (char === "\\") escaped = !escaped; - else escaped = false; - else if (char === "\"") { - isInsideString = true; - escaped = false; - } else if (char === "{") stack.push("}"); - else if (char === "[") stack.push("]"); - else if (char === "}" || char === "]") if (stack && stack[stack.length - 1] === char) stack.pop(); - else return null; - new_s += char; - } - if (isInsideString) new_s += "\""; - for (let i = stack.length - 1; i >= 0; i -= 1) new_s += stack[i]; - try { - return JSON.parse(new_s); - } catch { - return null; - } -} - -//#endregion - -//# sourceMappingURL=json.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js - - -//#region src/messages/block_translators/bedrock_converse.ts -function convertFileFormatToMimeType(format) { - switch (format) { - case "csv": return "text/csv"; - case "doc": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - case "html": return "text/html"; - case "md": return "text/markdown"; - case "pdf": return "application/pdf"; - case "txt": return "text/plain"; - case "xls": return "application/vnd.ms-excel"; - case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - case "gif": return "image/gif"; - case "jpeg": return "image/jpeg"; - case "jpg": return "image/jpeg"; - case "png": return "image/png"; - case "webp": return "image/webp"; - case "flv": return "video/flv"; - case "mkv": return "video/mkv"; - case "mov": return "video/mov"; - case "mp4": return "video/mp4"; - case "mpeg": return "video/mpeg"; - case "mpg": return "video/mpg"; - case "three_gp": return "video/three_gp"; - case "webm": return "video/webm"; - case "wmv": return "video/wmv"; - default: return "application/octet-stream"; - } -} -function convertConverseDocumentBlock(block) { - if (_isObject(block.document) && _isObject(block.document.source)) { - const format = _isObject(block.document) && _isString(block.document.format) ? block.document.format : ""; - const mimeType = convertFileFormatToMimeType(format); - if (_isObject(block.document.source)) { - if (_isObject(block.document.source.s3Location) && _isString(block.document.source.s3Location.uri)) return { - type: "file", - mimeType, - fileId: block.document.source.s3Location.uri - }; - if (_isBytesArray(block.document.source.bytes)) return { - type: "file", - mimeType, - data: block.document.source.bytes - }; - if (_isString(block.document.source.text)) return { - type: "file", - mimeType, - data: Buffer.from(block.document.source.text).toString("base64") - }; - if (_isArray(block.document.source.content)) { - const data = block.document.source.content.reduce((acc, item) => { - if (_isObject(item) && _isString(item.text)) return acc + item.text; - return acc; - }, ""); - return { - type: "file", - mimeType, - data - }; - } - } - } - return { - type: "non_standard", - value: block - }; -} -function convertConverseImageBlock(block) { - if (_isContentBlock(block, "image") && _isObject(block.image)) { - const format = _isObject(block.image) && _isString(block.image.format) ? block.image.format : ""; - const mimeType = convertFileFormatToMimeType(format); - if (_isObject(block.image.source)) { - if (_isObject(block.image.source.s3Location) && _isString(block.image.source.s3Location.uri)) return { - type: "image", - mimeType, - fileId: block.image.source.s3Location.uri - }; - if (_isBytesArray(block.image.source.bytes)) return { - type: "image", - mimeType, - data: block.image.source.bytes - }; - } - } - return { - type: "non_standard", - value: block - }; -} -function convertConverseVideoBlock(block) { - if (_isContentBlock(block, "video") && _isObject(block.video)) { - const format = _isObject(block.video) && _isString(block.video.format) ? block.video.format : ""; - const mimeType = convertFileFormatToMimeType(format); - if (_isObject(block.video.source)) { - if (_isObject(block.video.source.s3Location) && _isString(block.video.source.s3Location.uri)) return { - type: "video", - mimeType, - fileId: block.video.source.s3Location.uri - }; - if (_isBytesArray(block.video.source.bytes)) return { - type: "video", - mimeType, - data: block.video.source.bytes - }; - } - } - return { - type: "non_standard", - value: block - }; -} -function convertToV1FromChatBedrockConverseMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "cache_point")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "citations_content") && _isObject(block.citationsContent)) { - const text = _isArray(block.citationsContent.content) ? block.citationsContent.content.reduce((acc, item) => { - if (_isObject(item) && _isString(item.text)) return acc + item.text; - return acc; - }, "") : ""; - const annotations = _isArray(block.citationsContent.citations) ? block.citationsContent.citations.reduce((acc, item) => { - if (_isObject(item)) { - const citedText = _isArray(item.sourceContent) ? item.sourceContent.reduce((acc$1, item$1) => { - if (_isObject(item$1) && _isString(item$1.text)) return acc$1 + item$1.text; - return acc$1; - }, "") : ""; - const properties = iife(() => { - if (_isObject(item.location)) { - const location = item.location.documentChar || item.location.documentPage || item.location.documentChunk; - if (_isObject(location)) return { - source: _isNumber(location.documentIndex) ? location.documentIndex.toString() : void 0, - startIndex: _isNumber(location.start) ? location.start : void 0, - endIndex: _isNumber(location.end) ? location.end : void 0 - }; - } - return {}; - }); - acc.push({ - type: "citation", - citedText, - ...properties - }); - } - return acc; - }, []) : []; - yield { - type: "text", - text, - annotations - }; - continue; - } else if (_isContentBlock(block, "document") && _isObject(block.document)) { - yield convertConverseDocumentBlock(block); - continue; - } else if (_isContentBlock(block, "guard_content")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "image") && _isObject(block.image)) { - yield convertConverseImageBlock(block); - continue; - } else if (_isContentBlock(block, "reasoning_content") && _isString(block.reasoningText)) { - yield { - type: "reasoning", - reasoning: block.reasoningText - }; - continue; - } else if (_isContentBlock(block, "text") && _isString(block.text)) { - yield { - type: "text", - text: block.text - }; - continue; - } else if (_isContentBlock(block, "tool_result")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "tool_call")) continue; - else if (_isContentBlock(block, "video") && _isObject(block.video)) { - yield convertConverseVideoBlock(block); - continue; - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatBedrockConverseTranslator = { - translateContent: convertToV1FromChatBedrockConverseMessage, - translateContentChunk: convertToV1FromChatBedrockConverseMessage -}; - -//#endregion - -//# sourceMappingURL=bedrock_converse.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/google_genai.js - - -//#region src/messages/block_translators/google_genai.ts -function convertToV1FromChatGoogleMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "text") && _isString(block.text)) { - yield { - type: "text", - text: block.text - }; - continue; - } else if (_isContentBlock(block, "inlineData") && _isObject(block.inlineData) && _isString(block.inlineData.mimeType) && _isString(block.inlineData.data)) { - yield { - type: "file", - mimeType: block.inlineData.mimeType, - data: block.inlineData.data - }; - continue; - } else if (_isContentBlock(block, "functionCall") && _isObject(block.functionCall) && _isString(block.functionCall.name) && _isObject(block.functionCall.args)) { - yield { - type: "tool_call", - id: message.id, - name: block.functionCall.name, - args: block.functionCall.args - }; - continue; - } else if (_isContentBlock(block, "functionResponse")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "fileData") && _isObject(block.fileData) && _isString(block.fileData.mimeType) && _isString(block.fileData.fileUri)) { - yield { - type: "file", - mimeType: block.fileData.mimeType, - fileId: block.fileData.fileUri - }; - continue; - } else if (_isContentBlock(block, "executableCode")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "codeExecutionResult")) { - yield { - type: "non_standard", - value: block - }; - continue; - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatGoogleGenAITranslator = { - translateContent: convertToV1FromChatGoogleMessage, - translateContentChunk: convertToV1FromChatGoogleMessage -}; - -//#endregion - -//# sourceMappingURL=google_genai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js - - -//#region src/messages/block_translators/google_vertexai.ts -function convertToV1FromChatVertexMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "reasoning") && _isString(block.reasoning)) { - const signature = iife(() => { - const reasoningIndex = content.indexOf(block); - if (_isArray(message.additional_kwargs?.signatures) && reasoningIndex >= 0) return message.additional_kwargs.signatures.at(reasoningIndex); - return void 0; - }); - if (_isString(signature)) yield { - type: "reasoning", - reasoning: block.reasoning, - signature - }; - else yield { - type: "reasoning", - reasoning: block.reasoning - }; - continue; - } else if (_isContentBlock(block, "text") && _isString(block.text)) { - yield { - type: "text", - text: block.text - }; - continue; - } else if (_isContentBlock(block, "image_url")) { - if (_isString(block.image_url)) if (block.image_url.startsWith("data:")) { - const dataUrlRegex = /^data:([^;]+);base64,(.+)$/; - const match = block.image_url.match(dataUrlRegex); - if (match) yield { - type: "image", - data: match[2], - mimeType: match[1] - }; - else yield { - type: "image", - url: block.image_url - }; - } else yield { - type: "image", - url: block.image_url - }; - continue; - } else if (_isContentBlock(block, "media") && _isString(block.mimeType) && _isString(block.data)) { - yield { - type: "file", - mimeType: block.mimeType, - data: block.data - }; - continue; - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatVertexTranslator = { - translateContent: convertToV1FromChatVertexMessage, - translateContentChunk: convertToV1FromChatVertexMessage -}; - -//#endregion - -//# sourceMappingURL=google_vertexai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/index.js - - - - - - -//#region src/messages/block_translators/index.ts -globalThis.lc_block_translators_registry ??= new Map([ - ["anthropic", ChatAnthropicTranslator], - ["bedrock-converse", ChatBedrockConverseTranslator], - ["google-genai", ChatGoogleGenAITranslator], - ["google-vertexai", ChatVertexTranslator], - ["openai", ChatOpenAITranslator] -]); -function getTranslator(modelProvider) { - return globalThis.lc_block_translators_registry.get(modelProvider); -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/metadata.js - - -//#region src/messages/metadata.ts -function mergeResponseMetadata(a, b) { - const output = _mergeDicts(a ?? {}, b ?? {}); - return output; -} -function mergeModalitiesTokenDetails(a, b) { - const output = {}; - if (a?.audio !== void 0 || b?.audio !== void 0) output.audio = (a?.audio ?? 0) + (b?.audio ?? 0); - if (a?.image !== void 0 || b?.image !== void 0) output.image = (a?.image ?? 0) + (b?.image ?? 0); - if (a?.video !== void 0 || b?.video !== void 0) output.video = (a?.video ?? 0) + (b?.video ?? 0); - if (a?.document !== void 0 || b?.document !== void 0) output.document = (a?.document ?? 0) + (b?.document ?? 0); - if (a?.text !== void 0 || b?.text !== void 0) output.text = (a?.text ?? 0) + (b?.text ?? 0); - return output; -} -function mergeInputTokenDetails(a, b) { - const output = { ...mergeModalitiesTokenDetails(a, b) }; - if (a?.cache_read !== void 0 || b?.cache_read !== void 0) output.cache_read = (a?.cache_read ?? 0) + (b?.cache_read ?? 0); - if (a?.cache_creation !== void 0 || b?.cache_creation !== void 0) output.cache_creation = (a?.cache_creation ?? 0) + (b?.cache_creation ?? 0); - return output; -} -function mergeOutputTokenDetails(a, b) { - const output = { ...mergeModalitiesTokenDetails(a, b) }; - if (a?.reasoning !== void 0 || b?.reasoning !== void 0) output.reasoning = (a?.reasoning ?? 0) + (b?.reasoning ?? 0); - return output; -} -function mergeUsageMetadata(a, b) { - return { - input_tokens: (a?.input_tokens ?? 0) + (b?.input_tokens ?? 0), - output_tokens: (a?.output_tokens ?? 0) + (b?.output_tokens ?? 0), - total_tokens: (a?.total_tokens ?? 0) + (b?.total_tokens ?? 0), - input_token_details: mergeInputTokenDetails(a?.input_token_details, b?.input_token_details), - output_token_details: mergeOutputTokenDetails(a?.output_token_details, b?.output_token_details) - }; -} - -//#endregion - -//# sourceMappingURL=metadata.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/ai.js - - - - - - -//#region src/messages/ai.ts -var AIMessage = class extends BaseMessage { - type = "ai"; - tool_calls = []; - invalid_tool_calls = []; - usage_metadata; - get lc_aliases() { - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls" - }; - } - constructor(fields) { - let initParams; - if (typeof fields === "string" || Array.isArray(fields)) initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - additional_kwargs: {} - }; - else { - initParams = fields; - const rawToolCalls = initParams.additional_kwargs?.tool_calls; - const toolCalls = initParams.tool_calls; - if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) console.warn([ - "New LangChain packages are available that more efficiently handle", - "tool calling.\n\nPlease upgrade your packages to versions that set", - "message tool calls. e.g., `pnpm install @langchain/anthropic`,", - "pnpm install @langchain/openai`, etc." - ].join(" ")); - try { - if (!(rawToolCalls == null) && toolCalls === void 0) { - const [toolCalls$1, invalidToolCalls] = defaultToolCallParser(rawToolCalls); - initParams.tool_calls = toolCalls$1 ?? []; - initParams.invalid_tool_calls = invalidToolCalls ?? []; - } else { - initParams.tool_calls = initParams.tool_calls ?? []; - initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; - } - } catch { - initParams.tool_calls = []; - initParams.invalid_tool_calls = []; - } - if (initParams.response_metadata !== void 0 && "output_version" in initParams.response_metadata && initParams.response_metadata.output_version === "v1") { - initParams.contentBlocks = initParams.content; - initParams.content = void 0; - } - if (initParams.contentBlocks !== void 0) { - initParams.contentBlocks.push(...initParams.tool_calls.map((toolCall) => ({ - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }))); - const missingToolCalls = initParams.contentBlocks.filter((block) => block.type === "tool_call").filter((block) => !initParams.tool_calls?.some((toolCall) => toolCall.id === block.id && toolCall.name === block.name)); - if (missingToolCalls.length > 0) initParams.tool_calls = missingToolCalls.map((block) => ({ - type: "tool_call", - id: block.id, - name: block.name, - args: block.args - })); - } - } - super(initParams); - if (typeof initParams !== "string") { - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; - } - this.usage_metadata = initParams.usage_metadata; - } - static lc_name() { - return "AIMessage"; - } - get contentBlocks() { - if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; - if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { - const translator = getTranslator(this.response_metadata.model_provider); - if (translator) return translator.translateContent(this); - } - const blocks = super.contentBlocks; - if (this.tool_calls) { - const missingToolCalls = this.tool_calls.filter((block) => !blocks.some((b) => b.id === block.id && b.name === block.name)); - blocks.push(...missingToolCalls.map((block) => ({ - ...block, - type: "tool_call", - id: block.id, - name: block.name, - args: block.args - }))); - } - return blocks; - } - get _printableFields() { - return { - ...super._printableFields, - tool_calls: this.tool_calls, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata - }; - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "ai"; - } -}; -/** -* @deprecated Use {@link AIMessage.isInstance} instead -*/ -function isAIMessage(x) { - return x._getType() === "ai"; -} -/** -* @deprecated Use {@link AIMessageChunk.isInstance} instead -*/ -function isAIMessageChunk(x) { - return x._getType() === "ai"; -} -/** -* Represents a chunk of an AI message, which can be concatenated with -* other AI message chunks. -*/ -var AIMessageChunk = class extends BaseMessageChunk { - type = "ai"; - tool_calls = []; - invalid_tool_calls = []; - tool_call_chunks = []; - usage_metadata; - constructor(fields) { - let initParams; - if (typeof fields === "string" || Array.isArray(fields)) initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - tool_call_chunks: [] - }; - else if (fields.tool_call_chunks === void 0 || fields.tool_call_chunks.length === 0) initParams = { - ...fields, - tool_calls: fields.tool_calls ?? [], - invalid_tool_calls: [], - tool_call_chunks: [], - usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 - }; - else { - const toolCallChunks = fields.tool_call_chunks ?? []; - const groupedToolCallChunks = toolCallChunks.reduce((acc, chunk) => { - const matchedChunkIndex = acc.findIndex(([match]) => { - if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index; - if ("id" in chunk && chunk.id) return chunk.id === match.id; - if ("index" in chunk && chunk.index !== void 0) return chunk.index === match.index; - return false; - }); - if (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk); - else acc.push([chunk]); - return acc; - }, []); - const toolCalls = []; - const invalidToolCalls = []; - for (const chunks of groupedToolCallChunks) { - let parsedArgs = null; - const name = chunks[0]?.name ?? ""; - const joinedArgs = chunks.map((c) => c.args || "").join(""); - const argsStr = joinedArgs.length ? joinedArgs : "{}"; - const id = chunks[0]?.id; - try { - parsedArgs = parsePartialJson(argsStr); - if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args."); - toolCalls.push({ - name, - args: parsedArgs, - id, - type: "tool_call" - }); - } catch { - invalidToolCalls.push({ - name, - args: argsStr, - id, - error: "Malformed args.", - type: "invalid_tool_call" - }); - } - } - initParams = { - ...fields, - tool_calls: toolCalls, - invalid_tool_calls: invalidToolCalls, - usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 - }; - } - super(initParams); - this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks; - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; - this.usage_metadata = initParams.usage_metadata; - } - get lc_aliases() { - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls", - tool_call_chunks: "tool_call_chunks" - }; - } - static lc_name() { - return "AIMessageChunk"; - } - get contentBlocks() { - if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; - if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { - const translator = getTranslator(this.response_metadata.model_provider); - if (translator) return translator.translateContent(this); - } - const blocks = super.contentBlocks; - if (this.tool_calls) { - if (typeof this.content !== "string") { - const contentToolCalls = this.content.filter((block) => block.type === "tool_call").map((block) => block.id); - for (const toolCall of this.tool_calls) if (toolCall.id && !contentToolCalls.includes(toolCall.id)) blocks.push({ - ...toolCall, - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }); - } - } - return blocks; - } - get _printableFields() { - return { - ...super._printableFields, - tool_calls: this.tool_calls, - tool_call_chunks: this.tool_call_chunks, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata - }; - } - concat(chunk) { - const combinedFields = { - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: mergeResponseMetadata(this.response_metadata, chunk.response_metadata), - tool_call_chunks: [], - id: this.id ?? chunk.id - }; - if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) { - const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); - if (rawToolCalls !== void 0 && rawToolCalls.length > 0) combinedFields.tool_call_chunks = rawToolCalls; - } - if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) combinedFields.usage_metadata = mergeUsageMetadata(this.usage_metadata, chunk.usage_metadata); - const Cls = this.constructor; - return new Cls(combinedFields); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "ai"; - } -}; - -//#endregion - -//# sourceMappingURL=ai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/chat.js - - -//#region src/messages/chat.ts -/** -* Represents a chat message in a conversation. -*/ -var ChatMessage = class ChatMessage extends BaseMessage { - static lc_name() { - return "ChatMessage"; - } - type = "generic"; - role; - static _chatMessageClass() { - return ChatMessage; - } - constructor(fields, role) { - if (typeof fields === "string" || Array.isArray(fields)) fields = { - content: fields, - role - }; - super(fields); - this.role = fields.role; - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "generic"; - } - get _printableFields() { - return { - ...super._printableFields, - role: this.role - }; - } -}; -/** -* Represents a chunk of a chat message, which can be concatenated with -* other chat message chunks. -*/ -var ChatMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "ChatMessageChunk"; - } - type = "generic"; - role; - constructor(fields, role) { - if (typeof fields === "string" || Array.isArray(fields)) fields = { - content: fields, - role - }; - super(fields); - this.role = fields.role; - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - role: this.role, - id: this.id ?? chunk.id - }); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "generic"; - } - get _printableFields() { - return { - ...super._printableFields, - role: this.role - }; - } -}; -/** -* @deprecated Use {@link ChatMessage.isInstance} instead -*/ -function isChatMessage(x) { - return x._getType() === "generic"; -} -/** -* @deprecated Use {@link ChatMessageChunk.isInstance} instead -*/ -function isChatMessageChunk(x) { - return x._getType() === "generic"; -} - -//#endregion - -//# sourceMappingURL=chat.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/function.js - - -//#region src/messages/function.ts -/** -* Represents a function message in a conversation. -*/ -var FunctionMessage = class extends BaseMessage { - static lc_name() { - return "FunctionMessage"; - } - type = "function"; - name; - constructor(fields) { - super(fields); - this.name = fields.name; - } -}; -/** -* Represents a chunk of a function message, which can be concatenated -* with other function message chunks. -*/ -var FunctionMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "FunctionMessageChunk"; - } - type = "function"; - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - name: this.name ?? "", - id: this.id ?? chunk.id - }); - } -}; -function isFunctionMessage(x) { - return x._getType() === "function"; -} -function isFunctionMessageChunk(x) { - return x._getType() === "function"; -} - -//#endregion - -//# sourceMappingURL=function.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/human.js - - -//#region src/messages/human.ts -/** -* Represents a human message in a conversation. -*/ -var HumanMessage = class extends BaseMessage { - static lc_name() { - return "HumanMessage"; - } - type = "human"; - constructor(fields) { - super(fields); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "human"; - } -}; -/** -* Represents a chunk of a human message, which can be concatenated with -* other human message chunks. -*/ -var HumanMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "HumanMessageChunk"; - } - type = "human"; - constructor(fields) { - super(fields); - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id - }); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "human"; - } -}; -/** -* @deprecated Use {@link HumanMessage.isInstance} instead -*/ -function isHumanMessage(x) { - return x.getType() === "human"; -} -/** -* @deprecated Use {@link HumanMessageChunk.isInstance} instead -*/ -function isHumanMessageChunk(x) { - return x.getType() === "human"; -} - -//#endregion - -//# sourceMappingURL=human.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/system.js - - -//#region src/messages/system.ts -/** -* Represents a system message in a conversation. -*/ -var SystemMessage = class extends BaseMessage { - static lc_name() { - return "SystemMessage"; - } - type = "system"; - constructor(fields) { - super(fields); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "system"; - } -}; -/** -* Represents a chunk of a system message, which can be concatenated with -* other system message chunks. -*/ -var SystemMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "SystemMessageChunk"; - } - type = "system"; - constructor(fields) { - super(fields); - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id - }); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "system"; - } -}; -/** -* @deprecated Use {@link SystemMessage.isInstance} instead -*/ -function isSystemMessage(x) { - return x._getType() === "system"; -} -/** -* @deprecated Use {@link SystemMessageChunk.isInstance} instead -*/ -function isSystemMessageChunk(x) { - return x._getType() === "system"; -} - -//#endregion - -//# sourceMappingURL=system.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/errors/index.js -//#region src/errors/index.ts -function addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`; - return error; -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/utils.js -//#region src/tools/utils.ts -function _isToolCall(toolCall) { - return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call"); -} -function _configHasToolCallId(config) { - return !!(config && typeof config === "object" && "toolCall" in config && config.toolCall != null && typeof config.toolCall === "object" && "id" in config.toolCall && typeof config.toolCall.id === "string"); -} -/** -* Custom error class used to handle exceptions related to tool input parsing. -* It extends the built-in `Error` class and adds an optional `output` -* property that can hold the output that caused the exception. -*/ -var ToolInputParsingException = class extends Error { - output; - constructor(message, output) { - super(message); - this.output = output; - } -}; - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js - - -//#region src/messages/modifier.ts -/** -* Message responsible for deleting other messages. -*/ -var RemoveMessage = class extends BaseMessage { - type = "remove"; - /** - * The ID of the message to remove. - */ - id; - constructor(fields) { - super({ - ...fields, - content: [] - }); - this.id = fields.id; - } - get _printableFields() { - return { - ...super._printableFields, - id: this.id - }; - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "remove"; - } -}; - -//#endregion - -//# sourceMappingURL=modifier.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/utils.js - - - - - - - - - - - -//#region src/messages/utils.ts -/** -* Immediately-invoked function expression. -* -* @param fn - The function to execute -* @returns The result of the function -*/ -const utils_iife = (fn) => fn(); -function _coerceToolCall(toolCall) { - if (_isToolCall(toolCall)) return toolCall; - else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") return { - id: toolCall.id, - args: JSON.parse(toolCall.function.arguments), - name: toolCall.function.name, - type: "tool_call" - }; - else return toolCall; -} -function isSerializedConstructor(x) { - return typeof x === "object" && x != null && x.lc === 1 && Array.isArray(x.id) && x.kwargs != null && typeof x.kwargs === "object"; -} -function _constructMessageFromParams(params) { - let type; - let rest; - if (isSerializedConstructor(params)) { - const className = params.id.at(-1); - if (className === "HumanMessage" || className === "HumanMessageChunk") type = "user"; - else if (className === "AIMessage" || className === "AIMessageChunk") type = "assistant"; - else if (className === "SystemMessage" || className === "SystemMessageChunk") type = "system"; - else if (className === "FunctionMessage" || className === "FunctionMessageChunk") type = "function"; - else if (className === "ToolMessage" || className === "ToolMessageChunk") type = "tool"; - else type = "unknown"; - rest = params.kwargs; - } else { - const { type: extractedType,...otherParams } = params; - type = extractedType; - rest = otherParams; - } - if (type === "human" || type === "user") return new HumanMessage(rest); - else if (type === "ai" || type === "assistant") { - const { tool_calls: rawToolCalls,...other } = rest; - if (!Array.isArray(rawToolCalls)) return new AIMessage(rest); - const tool_calls = rawToolCalls.map(_coerceToolCall); - return new AIMessage({ - ...other, - tool_calls - }); - } else if (type === "system") return new SystemMessage(rest); - else if (type === "developer") return new SystemMessage({ - ...rest, - additional_kwargs: { - ...rest.additional_kwargs, - __openai_role__: "developer" - } - }); - else if (type === "tool" && "tool_call_id" in rest) return new ToolMessage({ - ...rest, - content: rest.content, - tool_call_id: rest.tool_call_id, - name: rest.name - }); - else if (type === "remove" && "id" in rest && typeof rest.id === "string") return new RemoveMessage({ - ...rest, - id: rest.id - }); - else { - const error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); - throw error; - } -} -function utils_coerceMessageLikeToMessage(messageLike) { - if (typeof messageLike === "string") return new HumanMessage(messageLike); - else if (isBaseMessage(messageLike)) return messageLike; - if (Array.isArray(messageLike)) { - const [type, content] = messageLike; - return _constructMessageFromParams({ - type, - content - }); - } else if (_isMessageFieldWithRole(messageLike)) { - const { role: type,...rest } = messageLike; - return _constructMessageFromParams({ - ...rest, - type - }); - } else return _constructMessageFromParams(messageLike); -} -/** -* This function is used by memory classes to get a string representation -* of the chat message history, based on the message content and role. -*/ -function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { - const string_messages = []; - for (const m of messages) { - let role; - if (m._getType() === "human") role = humanPrefix; - else if (m._getType() === "ai") role = aiPrefix; - else if (m._getType() === "system") role = "System"; - else if (m._getType() === "tool") role = "Tool"; - else if (m._getType() === "generic") role = m.role; - else throw new Error(`Got unsupported message type: ${m._getType()}`); - const nameStr = m.name ? `${m.name}, ` : ""; - const readableContent = typeof m.content === "string" ? m.content : JSON.stringify(m.content, null, 2); - string_messages.push(`${role}: ${nameStr}${readableContent}`); - } - return string_messages.join("\n"); -} -/** -* Maps messages from an older format (V1) to the current `StoredMessage` -* format. If the message is already in the `StoredMessage` format, it is -* returned as is. Otherwise, it transforms the V1 message into a -* `StoredMessage`. This function is important for maintaining -* compatibility with older message formats. -*/ -function mapV1MessageToStoredMessage(message) { - if (message.data !== void 0) return message; - else { - const v1Message = message; - return { - type: v1Message.type, - data: { - content: v1Message.text, - role: v1Message.role, - name: void 0, - tool_call_id: void 0 - } - }; - } -} -function mapStoredMessageToChatMessage(message) { - const storedMessage = mapV1MessageToStoredMessage(message); - switch (storedMessage.type) { - case "human": return new HumanMessage(storedMessage.data); - case "ai": return new AIMessage(storedMessage.data); - case "system": return new SystemMessage(storedMessage.data); - case "function": - if (storedMessage.data.name === void 0) throw new Error("Name must be defined for function messages"); - return new FunctionMessage(storedMessage.data); - case "tool": - if (storedMessage.data.tool_call_id === void 0) throw new Error("Tool call ID must be defined for tool messages"); - return new ToolMessage(storedMessage.data); - case "generic": - if (storedMessage.data.role === void 0) throw new Error("Role must be defined for chat messages"); - return new ChatMessage(storedMessage.data); - default: throw new Error(`Got unexpected type: ${storedMessage.type}`); - } -} -/** -* Transforms an array of `StoredMessage` instances into an array of -* `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage` -* function to ensure all messages are in the `StoredMessage` format, then -* creates new instances of the appropriate `BaseMessage` subclass based -* on the type of each message. This function is used to prepare stored -* messages for use in a chat context. -*/ -function mapStoredMessagesToChatMessages(messages) { - return messages.map(mapStoredMessageToChatMessage); -} -/** -* Transforms an array of `BaseMessage` instances into an array of -* `StoredMessage` instances. It does this by calling the `toDict` method -* on each `BaseMessage`, which returns a `StoredMessage`. This function -* is used to prepare chat messages for storage. -*/ -function mapChatMessagesToStoredMessages(messages) { - return messages.map((message) => message.toDict()); -} -function convertToChunk(message) { - const type = message._getType(); - if (type === "human") return new HumanMessageChunk({ ...message }); - else if (type === "ai") { - let aiChunkFields = { ...message }; - if ("tool_calls" in aiChunkFields) aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: void 0, - args: JSON.stringify(tc.args) - })) - }; - return new AIMessageChunk({ ...aiChunkFields }); - } else if (type === "system") return new SystemMessageChunk({ ...message }); - else if (type === "function") return new FunctionMessageChunk({ ...message }); - else if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message }); - else throw new Error("Unknown message type."); -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js - - -//#region src/utils/env.ts -var env_exports = {}; -__export(env_exports, { - getEnv: () => getEnv, - getEnvironmentVariable: () => getEnvironmentVariable, - getRuntimeEnvironment: () => getRuntimeEnvironment, - isBrowser: () => isBrowser, - isDeno: () => isDeno, - isJsDom: () => isJsDom, - isNode: () => isNode, - isWebWorker: () => isWebWorker -}); -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); -const isDeno = () => typeof Deno !== "undefined"; -const isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); -const getEnv = () => { - let env; - if (isBrowser()) env = "browser"; - else if (isNode()) env = "node"; - else if (isWebWorker()) env = "webworker"; - else if (isJsDom()) env = "jsdom"; - else if (isDeno()) env = "deno"; - else env = "other"; - return env; -}; -let runtimeEnvironment; -function getRuntimeEnvironment() { - if (runtimeEnvironment === void 0) { - const env = getEnv(); - runtimeEnvironment = { - library: "langchain-js", - runtime: env - }; - } - return runtimeEnvironment; -} -function getEnvironmentVariable(name) { - try { - if (typeof process !== "undefined") return process.env?.[name]; - else if (isDeno()) return Deno?.env.get(name); - else return void 0; - } catch { - return void 0; - } -} - -//#endregion - -//# sourceMappingURL=env.js.map -// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/uuid/dist/index.js -var dist = __nccwpck_require__(3563); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/node_modules/uuid/wrapper.mjs - -const v1 = dist.v1; -const v1ToV6 = dist/* v1ToV6 */.bV; -const v3 = dist.v3; -const v4 = dist.v4; -const v5 = dist.v5; -const v6 = dist.v6; -const v6ToV1 = dist/* v6ToV1 */.JE; -const v7 = dist.v7; -const NIL = dist/* NIL */.wD; -const MAX = dist/* MAX */.Zu; -const version = dist/* version */.rE; -const wrapper_validate = dist/* validate */.tf; -const stringify = dist/* stringify */.As; -const parse = dist/* parse */.qg; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js - - - - - -//#region src/callbacks/base.ts -var base_exports = {}; -__export(base_exports, { - BaseCallbackHandler: () => BaseCallbackHandler, - callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming, - isBaseCallbackHandler: () => isBaseCallbackHandler -}); -/** -* Abstract class that provides a set of optional methods that can be -* overridden in derived classes to handle various events during the -* execution of a LangChain application. -*/ -var BaseCallbackHandlerMethodsClass = class {}; -function callbackHandlerPrefersStreaming(x) { - return "lc_prefer_streaming" in x && x.lc_prefer_streaming; -} -/** -* Abstract base class for creating callback handlers in the LangChain -* framework. It provides a set of optional methods that can be overridden -* in derived classes to handle various events during the execution of a -* LangChain application. -*/ -var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { - lc_serializable = false; - get lc_namespace() { - return [ - "langchain_core", - "callbacks", - this.name - ]; - } - get lc_secrets() { - return void 0; - } - get lc_attributes() { - return void 0; - } - get lc_aliases() { - return void 0; - } - get lc_serializable_keys() { - return void 0; - } - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; - } - lc_kwargs; - ignoreLLM = false; - ignoreChain = false; - ignoreAgent = false; - ignoreRetriever = false; - ignoreCustomEvent = false; - raiseError = false; - awaitHandlers = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"; - constructor(input) { - super(); - this.lc_kwargs = input || {}; - if (input) { - this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; - this.ignoreChain = input.ignoreChain ?? this.ignoreChain; - this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; - this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; - this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; - this.raiseError = input.raiseError ?? this.raiseError; - this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers); - } - } - copy() { - return new this.constructor(this); - } - toJSON() { - return Serializable.prototype.toJSON.call(this); - } - toJSONNotImplemented() { - return Serializable.prototype.toJSONNotImplemented.call(this); - } - static fromMethods(methods) { - class Handler extends BaseCallbackHandler { - name = v4(); - constructor() { - super(); - Object.assign(this, methods); - } - } - return new Handler(); - } -}; -const isBaseCallbackHandler = (x) => { - const callbackHandler = x; - return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; -}; - -//#endregion - -//# sourceMappingURL=base.js.map -// EXTERNAL MODULE: ./node_modules/langsmith/node_modules/uuid/dist/index.js -var uuid_dist = __nccwpck_require__(157); -;// CONCATENATED MODULE: ./node_modules/langsmith/node_modules/uuid/wrapper.mjs - -const wrapper_v1 = uuid_dist.v1; -const wrapper_v1ToV6 = uuid_dist/* v1ToV6 */.bV; -const wrapper_v3 = uuid_dist.v3; -const wrapper_v4 = uuid_dist.v4; -const wrapper_v5 = uuid_dist.v5; -const wrapper_v6 = uuid_dist.v6; -const wrapper_v6ToV1 = uuid_dist/* v6ToV1 */.JE; -const wrapper_v7 = uuid_dist.v7; -const wrapper_NIL = uuid_dist/* NIL */.wD; -const wrapper_MAX = uuid_dist/* MAX */.Zu; -const wrapper_version = uuid_dist/* version */.rE; -const uuid_wrapper_validate = uuid_dist/* validate */.tf; -const wrapper_stringify = uuid_dist/* stringify */.As; -const wrapper_parse = uuid_dist/* parse */.qg; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/constants.js -// OpenTelemetry GenAI semantic convention attribute names -const GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; -const GEN_AI_SYSTEM = "gen_ai.system"; -const GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; -const GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; -const GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; -const GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; -const GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; -const GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; -const GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; -const GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; -const GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; -const GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; -const GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; -const GENAI_PROMPT = "gen_ai.prompt"; -const GENAI_COMPLETION = "gen_ai.completion"; -const GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; -const GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; -const GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; -const GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; -const GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; -const GEN_AI_RESPONSE_ID = "gen_ai.response.id"; -const GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; -const GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; -const GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; -const GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; -// LangSmith custom attributes -const LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; -const LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; -const LANGSMITH_RUN_TYPE = "langsmith.span.kind"; -const LANGSMITH_NAME = "langsmith.trace.name"; -const LANGSMITH_METADATA = "langsmith.metadata"; -const LANGSMITH_TAGS = "langsmith.span.tags"; -const LANGSMITH_RUNTIME = "langsmith.span.runtime"; -const LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; -const LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; -const LANGSMITH_RUN_ID = "langsmith.span.id"; -const LANGSMITH_TRACE_ID = "langsmith.trace.id"; -const LANGSMITH_DOTTED_ORDER = "langsmith.span.dotted_order"; -const LANGSMITH_PARENT_RUN_ID = "langsmith.span.parent_id"; -const LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; -const LANGSMITH_REFERENCE_EXAMPLE_ID = "langsmith.reference_example_id"; -const LANGSMITH_TRACEABLE = "langsmith.traceable"; -const LANGSMITH_IS_ROOT = "langsmith.is_root"; -const LANGSMITH_TRACEABLE_PARENT_OTEL_SPAN_ID = "langsmith.traceable_parent_otel_span_id"; -// GenAI event names -const GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"; -const GEN_AI_USER_MESSAGE = "gen_ai.user.message"; -const GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"; -const GEN_AI_CHOICE = "gen_ai.choice"; -const AI_SDK_LLM_OPERATIONS = (/* unused pure expression or super */ null && ([ - "ai.generateText.doGenerate", - "ai.streamText.doStream", - "ai.generateObject.doGenerate", - "ai.streamObject.doStream", -])); -const AI_SDK_TOOL_OPERATIONS = (/* unused pure expression or super */ null && (["ai.toolCall"])); - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js - -// Wrap the default fetch call due to issues with illegal invocations -// in some environments: -// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err -// @ts-expect-error Broad typing to support a range of fetch implementations -const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); -const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); -/** - * Overrides the fetch implementation used for LangSmith calls. - * You should use this if you need to use an implementation of fetch - * other than the default global (e.g. for dealing with proxies). - * @param fetch The new fetch functino to use. - */ -const overrideFetchImplementation = (fetch) => { - globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; -}; -const clearFetchImplementation = () => { - delete globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; -}; -const _globalFetchImplementationIsNodeFetch = () => { - const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; - if (!fetchImpl) - return false; - // Check if the implementation has node-fetch specific properties - return (typeof fetchImpl === "function" && - "Headers" in fetchImpl && - "Request" in fetchImpl && - "Response" in fetchImpl); -}; -/** - * @internal - */ -const _getFetchImplementation = (debug) => { - return async (...args) => { - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - const [url, options] = args; - console.log(`→ ${options?.method || "GET"} ${url}`); - } - const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? - DEFAULT_FETCH_IMPLEMENTATION)(...args); - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - console.log(`← ${res.status} ${res.statusText} ${res.url}`); - } - return res; - }; -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/project.js - -const getDefaultProjectName = () => { - return (getLangSmithEnvironmentVariable("PROJECT") ?? - env_getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default"); -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js - - - - -// Update using yarn bump-version -const __version__ = "0.3.79"; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js -// Inlined from https://github.com/flexdinesh/browser-or-node - -let globalEnv; -const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const env_isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const env_isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const env_isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !env_isDeno(); -const env_getEnv = () => { - if (globalEnv) { - return globalEnv; - } - // @ts-expect-error Bun types are not imported due to conflicts with Node types - if (typeof Bun !== "undefined") { - globalEnv = "bun"; - } - else if (env_isBrowser()) { - globalEnv = "browser"; - } - else if (env_isNode()) { - globalEnv = "node"; - } - else if (env_isWebWorker()) { - globalEnv = "webworker"; - } - else if (env_isJsDom()) { - globalEnv = "jsdom"; - } - else if (env_isDeno()) { - globalEnv = "deno"; - } - else { - globalEnv = "other"; - } - return globalEnv; -}; -let env_runtimeEnvironment; -function env_getRuntimeEnvironment() { - if (env_runtimeEnvironment === undefined) { - const env = env_getEnv(); - const releaseEnv = getShas(); - env_runtimeEnvironment = { - library: "langsmith", - runtime: env, - sdk: "langsmith-js", - sdk_version: __version__, - ...releaseEnv, - }; - } - return env_runtimeEnvironment; -} -/** - * Retrieves the LangSmith-specific metadata from the current runtime environment. - * - * @returns {Record} - * - A record of LangSmith-specific metadata environment variables. - */ -function getLangSmithEnvVarsMetadata() { - const allEnvVars = getLangSmithEnvironmentVariables(); - const envVars = {}; - const excluded = [ - "LANGCHAIN_API_KEY", - "LANGCHAIN_ENDPOINT", - "LANGCHAIN_TRACING_V2", - "LANGCHAIN_PROJECT", - "LANGCHAIN_SESSION", - "LANGSMITH_API_KEY", - "LANGSMITH_ENDPOINT", - "LANGSMITH_TRACING_V2", - "LANGSMITH_PROJECT", - "LANGSMITH_SESSION", - ]; - for (const [key, value] of Object.entries(allEnvVars)) { - if (typeof value === "string" && - !excluded.includes(key) && - !key.toLowerCase().includes("key") && - !key.toLowerCase().includes("secret") && - !key.toLowerCase().includes("token")) { - if (key === "LANGCHAIN_REVISION_ID") { - envVars["revision_id"] = value; - } - else { - envVars[key] = value; - } - } - } - return envVars; -} -/** - * Retrieves only the LangChain/LangSmith-prefixed environment variables from the current runtime environment. - * This is more efficient than copying all environment variables. - * - * @returns {Record} - * - A record of LangChain/LangSmith environment variables. - */ -function getLangSmithEnvironmentVariables() { - const envVars = {}; - try { - // Check for Node.js environment - // eslint-disable-next-line no-process-env - if (typeof process !== "undefined" && process.env) { - // eslint-disable-next-line no-process-env - for (const [key, value] of Object.entries(process.env)) { - if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && - value != null) { - if ((key.toLowerCase().includes("key") || - key.toLowerCase().includes("secret") || - key.toLowerCase().includes("token")) && - typeof value === "string") { - envVars[key] = - value.slice(0, 2) + - "*".repeat(value.length - 4) + - value.slice(-2); - } - else { - envVars[key] = value; - } - } - } - } - } - catch (e) { - // Catch any errors that might occur while trying to access environment variables - } - return envVars; -} -function env_getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; - } - catch (e) { - return undefined; - } -} -function getLangSmithEnvironmentVariable(name) { - return (env_getEnvironmentVariable(`LANGSMITH_${name}`) || - env_getEnvironmentVariable(`LANGCHAIN_${name}`)); -} -function setEnvironmentVariable(name, value) { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - process.env[name] = value; - } -} -let cachedCommitSHAs; -/** - * Get the Git commit SHA from common environment variables - * used by different CI/CD platforms. - * @returns {string | undefined} The Git commit SHA or undefined if not found. - */ -function getShas() { - if (cachedCommitSHAs !== undefined) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT", - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = env_getEnvironmentVariable(env); - if (envVar !== undefined) { - shas[env] = envVar; - } - } - cachedCommitSHAs = shas; - return shas; -} -function getOtelEnabled() { - return (env_getEnvironmentVariable("OTEL_ENABLED") === "true" || - getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/otel.js -// Should not import any OTEL packages to avoid pulling in optional deps. - -class MockTracer { - constructor() { - Object.defineProperty(this, "hasWarned", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - } - startActiveSpan(_name, ...args) { - if (!this.hasWarned && getOtelEnabled()) { - console.warn("You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. " + - 'Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); - this.hasWarned = true; - } - // Handle different overloads: - // startActiveSpan(name, fn) - // startActiveSpan(name, options, fn) - // startActiveSpan(name, options, context, fn) - let fn; - if (args.length === 1 && typeof args[0] === "function") { - fn = args[0]; - } - else if (args.length === 2 && typeof args[1] === "function") { - fn = args[1]; - } - else if (args.length === 3 && typeof args[2] === "function") { - fn = args[2]; - } - if (typeof fn === "function") { - return fn(); - } - return undefined; - } -} -class MockOTELTrace { - constructor() { - Object.defineProperty(this, "mockTracer", { - enumerable: true, - configurable: true, - writable: true, - value: new MockTracer() - }); - } - getTracer(_name, _version) { - return this.mockTracer; - } - getActiveSpan() { - return undefined; - } - setSpan(context, _span) { - return context; - } - getSpan(_context) { - return undefined; - } - setSpanContext(context, _spanContext) { - return context; - } - getTracerProvider() { - return undefined; - } - setGlobalTracerProvider(_tracerProvider) { - return false; - } -} -class MockOTELContext { - active() { - return {}; - } - with(_context, fn) { - return fn(); - } -} -const OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); -const OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); -const OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); -const mockOTELTrace = new MockOTELTrace(); -const mockOTELContext = new MockOTELContext(); -class OTELProvider { - getTraceInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; - } - getContextInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; - } - initializeGlobalInstances(otel) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[OTEL_TRACE_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[OTEL_TRACE_KEY] = otel.trace; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[OTEL_CONTEXT_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[OTEL_CONTEXT_KEY] = otel.context; - } - } - setDefaultOTLPTracerComponents(components) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; - } - getDefaultOTLPTracerComponents() { - return (globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? - undefined); - } -} -const OTELProviderSingleton = new OTELProvider(); -/** - * Get the current OTEL trace instance. - * Returns a mock implementation if OTEL is not available. - */ -function getOTELTrace() { - return OTELProviderSingleton.getTraceInstance(); -} -/** - * Get the current OTEL context instance. - * Returns a mock implementation if OTEL is not available. - */ -function getOTELContext() { - return OTELProviderSingleton.getContextInstance(); -} -/** - * Initialize the global OTEL instances. - * Should be called once when OTEL packages are available. - */ -function setOTELInstances(otel) { - OTELProviderSingleton.initializeGlobalInstances(otel); -} -/** - * Set a getter function for the default OTLP tracer provider. - * This allows lazy initialization of the tracer provider. - */ -function setDefaultOTLPTracerComponents(components) { - OTELProviderSingleton.setDefaultOTLPTracerComponents(components); -} -/** - * Get the default OTLP tracer provider instance. - * Returns undefined if not set. - */ -function getDefaultOTLPTracerComponents() { - return OTELProviderSingleton.getDefaultOTLPTracerComponents(); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/translator.js - - -const WELL_KNOWN_OPERATION_NAMES = { - llm: "chat", - tool: "execute_tool", - retriever: "embeddings", - embedding: "embeddings", - prompt: "chat", -}; -function getOperationName(runType) { - return WELL_KNOWN_OPERATION_NAMES[runType] || runType; -} -class LangSmithToOTELTranslator { - constructor() { - Object.defineProperty(this, "spans", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - } - exportBatch(operations, otelContextMap) { - for (const op of operations) { - try { - if (!op.run) { - continue; - } - if (op.operation === "post") { - const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); - if (span && !op.run.end_time) { - this.spans.set(op.id, span); - } - } - else { - this.updateSpanForRun(op, op.run); - } - } - catch (e) { - console.error(`Error processing operation ${op.id}:`, e); - } - } - } - createSpanForRun(op, runInfo, otelContext) { - const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); - if (!activeSpan) { - return; - } - try { - return this.finishSpanSetup(activeSpan, runInfo, op); - } - catch (e) { - console.error(`Failed to create span for run ${op.id}:`, e); - return undefined; - } - } - finishSpanSetup(span, runInfo, op) { - // Set all attributes - this.setSpanAttributes(span, runInfo, op); - // Set status based on error - if (runInfo.error) { - span.setStatus({ code: 2 }); // ERROR status - span.recordException(new Error(runInfo.error)); - } - else { - span.setStatus({ code: 1 }); // OK status - } - // End the span if end_time is present - if (runInfo.end_time) { - span.end(new Date(runInfo.end_time)); - } - return span; - } - updateSpanForRun(op, runInfo) { - try { - const span = this.spans.get(op.id); - if (!span) { - console.debug(`No span found for run ${op.id} during update`); - return; - } - // Update attributes - this.setSpanAttributes(span, runInfo, op); - // Update status based on error - if (runInfo.error) { - span.setStatus({ code: 2 }); // ERROR status - span.recordException(new Error(runInfo.error)); - } - else { - span.setStatus({ code: 1 }); // OK status - } - // End the span if end_time is present - const endTime = runInfo.end_time; - if (endTime) { - span.end(new Date(endTime)); - this.spans.delete(op.id); - } - } - catch (e) { - console.error(`Failed to update span for run ${op.id}:`, e); - } - } - extractModelName(runInfo) { - // Try to get model name from metadata - if (runInfo.extra?.metadata) { - const metadata = runInfo.extra.metadata; - // First check for ls_model_name in metadata - if (metadata.ls_model_name) { - return metadata.ls_model_name; - } - // Then check invocation_params for model info - if (metadata.invocation_params) { - const invocationParams = metadata.invocation_params; - if (invocationParams.model) { - return invocationParams.model; - } - else if (invocationParams.model_name) { - return invocationParams.model_name; - } - } - } - return; - } - setSpanAttributes(span, runInfo, op) { - if ("run_type" in runInfo && runInfo.run_type) { - span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); - // Set GenAI attributes according to OTEL semantic conventions - const operationName = getOperationName(runInfo.run_type || "chain"); - span.setAttribute(GEN_AI_OPERATION_NAME, operationName); - } - if ("name" in runInfo && runInfo.name) { - span.setAttribute(LANGSMITH_NAME, runInfo.name); - } - if ("session_id" in runInfo && runInfo.session_id) { - span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); - } - if ("session_name" in runInfo && runInfo.session_name) { - span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); - } - // Set gen_ai.system - this.setGenAiSystem(span, runInfo); - // Set model name if available - const modelName = this.extractModelName(runInfo); - if (modelName) { - span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); - } - // Set token usage information - if ("prompt_tokens" in runInfo && - typeof runInfo.prompt_tokens === "number") { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); - } - if ("completion_tokens" in runInfo && - typeof runInfo.completion_tokens === "number") { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); - } - if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { - span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); - } - // Set other parameters from invocation_params - this.setInvocationParameters(span, runInfo); - // Set metadata and tags if available - const metadata = runInfo.extra?.metadata || {}; - for (const [key, value] of Object.entries(metadata)) { - if (value !== null && value !== undefined) { - span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); - } - } - const tags = runInfo.tags; - if (tags && Array.isArray(tags)) { - span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); - } - else if (tags) { - span.setAttribute(LANGSMITH_TAGS, String(tags)); - } - // Support additional serialized attributes, if present - if ("serialized" in runInfo && typeof runInfo.serialized === "object") { - const serialized = runInfo.serialized; - if (serialized.name) { - span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); - } - if (serialized.signature) { - span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); - } - if (serialized.doc) { - span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); - } - } - // Set inputs/outputs if available - this.setIOAttributes(span, op); - } - setGenAiSystem(span, runInfo) { - // Default to "langchain" if we can't determine the system - let system = "langchain"; - // Extract model name to determine the system - const modelName = this.extractModelName(runInfo); - if (modelName) { - const modelLower = modelName.toLowerCase(); - if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { - system = "anthropic"; - } - else if (modelLower.includes("bedrock")) { - system = "aws.bedrock"; - } - else if (modelLower.includes("azure") && - modelLower.includes("openai")) { - system = "az.ai.openai"; - } - else if (modelLower.includes("azure") && - modelLower.includes("inference")) { - system = "az.ai.inference"; - } - else if (modelLower.includes("cohere")) { - system = "cohere"; - } - else if (modelLower.includes("deepseek")) { - system = "deepseek"; - } - else if (modelLower.includes("gemini")) { - system = "gemini"; - } - else if (modelLower.includes("groq")) { - system = "groq"; - } - else if (modelLower.includes("watson") || modelLower.includes("ibm")) { - system = "ibm.watsonx.ai"; - } - else if (modelLower.includes("mistral")) { - system = "mistral_ai"; - } - else if (modelLower.includes("gpt") || modelLower.includes("openai")) { - system = "openai"; - } - else if (modelLower.includes("perplexity") || - modelLower.includes("sonar")) { - system = "perplexity"; - } - else if (modelLower.includes("vertex")) { - system = "vertex_ai"; - } - else if (modelLower.includes("xai") || modelLower.includes("grok")) { - system = "xai"; - } - } - span.setAttribute(GEN_AI_SYSTEM, system); - } - setInvocationParameters(span, runInfo) { - if (!runInfo.extra?.metadata?.invocation_params) { - return; - } - const invocationParams = runInfo.extra.metadata.invocation_params; - // Set relevant invocation parameters - if (invocationParams.max_tokens !== undefined) { - span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); - } - if (invocationParams.temperature !== undefined) { - span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); - } - if (invocationParams.top_p !== undefined) { - span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); - } - if (invocationParams.frequency_penalty !== undefined) { - span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); - } - if (invocationParams.presence_penalty !== undefined) { - span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); - } - } - setIOAttributes(span, op) { - if (op.run.inputs) { - try { - const inputs = op.run.inputs; - if (typeof inputs === "object" && inputs !== null) { - if (inputs.model && Array.isArray(inputs.messages)) { - span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); - } - // Set additional request attributes if available - if (inputs.stream !== undefined) { - span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); - } - if (inputs.extra_headers) { - span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); - } - if (inputs.extra_query) { - span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); - } - if (inputs.extra_body) { - span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); - } - } - span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); - } - catch (e) { - console.debug(`Failed to process inputs for run ${op.id}`, e); - } - } - if (op.run.outputs) { - try { - const outputs = op.run.outputs; - // Extract token usage from outputs (for LLM runs) - const tokenUsage = this.getUnifiedRunTokens(outputs); - if (tokenUsage) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); - span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); - } - if (outputs && typeof outputs === "object") { - if (outputs.model) { - span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); - } - // Extract additional response attributes - if (outputs.id) { - span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); - } - if (outputs.choices && Array.isArray(outputs.choices)) { - const finishReasons = outputs.choices - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .map((choice) => choice.finish_reason) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .filter((reason) => reason) - .map(String); - if (finishReasons.length > 0) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); - } - } - if (outputs.service_tier) { - span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); - } - if (outputs.system_fingerprint) { - span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); - } - if (outputs.usage_metadata && - typeof outputs.usage_metadata === "object") { - const usageMetadata = outputs.usage_metadata; - if (usageMetadata.input_token_details) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); - } - if (usageMetadata.output_token_details) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); - } - } - } - span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); - } - catch (e) { - console.debug(`Failed to process outputs for run ${op.id}`, e); - } - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - getUnifiedRunTokens(outputs) { - if (!outputs) { - return null; - } - // Search in non-generations lists - let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - // Find if direct kwarg in outputs - const keys = Object.keys(outputs); - for (const key of keys) { - const haystack = outputs[key]; - if (!haystack || typeof haystack !== "object") { - continue; - } - tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - if (haystack.lc === 1 && - haystack.kwargs && - typeof haystack.kwargs === "object") { - tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - } - } - // Find in generations - const generations = outputs.generations || []; - if (!Array.isArray(generations)) { - return null; - } - const flatGenerations = Array.isArray(generations[0]) - ? generations.flat() - : generations; - for (const generation of flatGenerations) { - if (typeof generation === "object" && - generation.message && - typeof generation.message === "object" && - generation.message.kwargs && - typeof generation.message.kwargs === "object") { - tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - } - } - return null; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - extractUnifiedRunTokens(outputs) { - if (!outputs || typeof outputs !== "object") { - return null; - } - if (typeof outputs.input_tokens !== "number" || - typeof outputs.output_tokens !== "number") { - return null; - } - return [outputs.input_tokens, outputs.output_tokens]; - } -} - -// EXTERNAL MODULE: ./node_modules/p-retry/index.js -var p_retry = __nccwpck_require__(2103); -// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js -var p_queue_dist = __nccwpck_require__(6459); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js - - -const STATUS_RETRYABLE = [ - 429, // Too Many Requests - 500, // Internal Server Error - 502, // Bad Gateway - 503, // Service Unavailable - 504, // Gateway Timeout -]; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedResponseHook", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - if ( true) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist["default"]({ - concurrency: this.maxConcurrency, - }); - } - else { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); - } - this.onFailedResponseHook = params?.onFailedResponseHook; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - const onFailedResponseHook = this.onFailedResponseHook; - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; - } - else { - throw new Error(error); - } - }), { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async onFailedAttempt(error) { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.name === "TimeoutError" || - error.message.startsWith("AbortError")) { - throw error; - } - if (error?.code === "ECONNABORTED") { - throw error; - } - const response = error?.response; - if (onFailedResponseHook) { - const handled = await onFailedResponseHook(response); - if (handled) { - return; - } - } - const status = response?.status ?? error?.status; - if (status) { - if (!STATUS_RETRYABLE.includes(+status)) { - throw error; - } - } - }, - retries: this.maxRetries, - randomize: true, - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); - } - return this.call(callable, ...args); - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content }, - }; - // Check for presence of keys in additional_kwargs - if (message?.additional_kwargs && - Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; - } - return converted; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js -// Relaxed UUID validation regex (allows any valid UUID format including nil UUIDs) -const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -function assertUuid(str, which) { - // Use relaxed regex validation instead of strict uuid.validate() - // This allows edge cases like nil UUIDs or test UUIDs that might not pass strict validation - if (!UUID_REGEX.test(str)) { - const msg = which !== undefined - ? `Invalid UUID for ${which}: ${str}` - : `Invalid UUID: ${str}`; - throw new Error(msg); - } - return str; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js -const warnedMessages = {}; -function warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; - } -} - -// EXTERNAL MODULE: ./node_modules/semver/index.js -var semver = __nccwpck_require__(2088); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js - -function isVersionGreaterOrEqual(current_version, target_version) { - const current = parseVersion(current_version); - const target = parseVersion(target_version); - if (!current || !target) { - throw new Error("Invalid version format."); - } - return current.compare(target) >= 0; -} -function parsePromptIdentifier(identifier) { - if (!identifier || - identifier.split("/").length > 2 || - identifier.startsWith("/") || - identifier.endsWith("/") || - identifier.split(":").length > 2) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - const [ownerNamePart, commitPart] = identifier.split(":"); - const commit = commitPart || "latest"; - if (ownerNamePart.includes("/")) { - const [owner, name] = ownerNamePart.split("/", 2); - if (!owner || !name) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - return [owner, name, commit]; - } - else { - if (!ownerNamePart) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - return ["-", ownerNamePart, commit]; - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js -function getErrorStackTrace(e) { - if (typeof e !== "object" || e == null) - return undefined; - if (!("stack" in e) || typeof e.stack !== "string") - return undefined; - let stack = e.stack; - const prevLine = `${e}`; - if (stack.startsWith(prevLine)) { - stack = stack.slice(prevLine.length); - } - if (stack.startsWith("\n")) { - stack = stack.slice(1); - } - return stack; -} -function printErrorStackTrace(e) { - const stack = getErrorStackTrace(e); - if (stack == null) - return; - console.error(stack); -} -/** - * LangSmithConflictError - * - * Represents an error that occurs when there's a conflict during an operation, - * typically corresponding to HTTP 409 status code responses. - * - * This error is thrown when an attempt to create or modify a resource conflicts - * with the current state of the resource on the server. Common scenarios include: - * - Attempting to create a resource that already exists - * - Trying to update a resource that has been modified by another process - * - Violating a uniqueness constraint in the data - * - * @extends Error - * - * @example - * try { - * await createProject("existingProject"); - * } catch (error) { - * if (error instanceof ConflictError) { - * console.log("A conflict occurred:", error.message); - * // Handle the conflict, e.g., by suggesting a different project name - * } else { - * // Handle other types of errors - * } - * } - * - * @property {string} name - Always set to 'ConflictError' for easy identification - * @property {string} message - Detailed error message including server response - * - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 - */ -class LangSmithConflictError extends Error { - constructor(message) { - super(message); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = "LangSmithConflictError"; - this.status = 409; - } -} -/** - * Throws an appropriate error based on the response status and body. - * - * @param response - The fetch Response object - * @param context - Additional context to include in the error message (e.g., operation being performed) - * @throws {LangSmithConflictError} When the response status is 409 - * @throws {Error} For all other non-ok responses - */ -async function raiseForStatus(response, context, consumeOnSuccess) { - let errorBody; - if (response.ok) { - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - if (consumeOnSuccess) { - errorBody = await response.text(); - } - return; - } - if (response.status === 403) { - try { - const errorData = await response.json(); - const errorCode = errorData?.error; - if (errorCode === "org_scoped_key_requires_workspace") { - errorBody = - "This API key is org-scoped and requires workspace specification. " + - "Please provide 'workspaceId' parameter, " + - "or set LANGSMITH_WORKSPACE_ID environment variable."; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - const errorWithStatus = new Error(`${response.status} ${response.statusText}`); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - errorWithStatus.status = response?.status; - throw errorWithStatus; - } - } - if (errorBody === undefined) { - try { - errorBody = await response.text(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - errorBody = ""; - } - } - const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`; - if (response.status === 409) { - throw new LangSmithConflictError(fullMessage); - } - const err = new Error(fullMessage); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - err.status = response.status; - throw err; -} -const ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; -class ConflictingEndpointsError extends Error { - constructor() { - super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT " + - "and LANGSMITH_RUNS_ENDPOINTS."); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: ERR_CONFLICTING_ENDPOINTS - }); - this.name = "ConflictingEndpointsError"; // helpful in logs - } -} -function isConflictingEndpointsError(err) { - return (typeof err === "object" && - err !== null && - err.code === ERR_CONFLICTING_ENDPOINTS); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js -/* eslint-disable */ -// @ts-nocheck - -var LIMIT_REPLACE_NODE = "[...]"; -var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; -var arr = []; -var replacerStack = []; -const encoder = new TextEncoder(); -function defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER, - }; -} -function encodeString(str) { - return encoder.encode(str); -} -// Shared function to handle well-known types -function serializeWellKnownTypes(val) { - if (val && typeof val === "object" && val !== null) { - if (val instanceof Map) { - return Object.fromEntries(val); - } - else if (val instanceof Set) { - return Array.from(val); - } - else if (val instanceof Date) { - return val.toISOString(); - } - else if (val instanceof RegExp) { - return val.toString(); - } - else if (val instanceof Error) { - return { - name: val.name, - message: val.message, - }; - } - } - else if (typeof val === "bigint") { - return val.toString(); - } - return val; -} -// Default replacer function to handle well-known types -function createDefaultReplacer(userReplacer) { - return function (key, val) { - // Apply user replacer first if provided - if (userReplacer) { - const userResult = userReplacer.call(this, key, val); - // If user replacer returned undefined, fall back to our serialization - if (userResult !== undefined) { - return userResult; - } - } - // Fall back to our well-known type handling - return serializeWellKnownTypes(val); - }; -} -// Regular stringify -function serialize(obj, errorContext, replacer, spacer, options) { - try { - const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); - return encodeString(str); - } - catch (e) { - // Fall back to more complex stringify if circular reference - if (!e.message?.includes("Converting circular structure to JSON")) { - console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); - return encodeString("[Unserializable]"); - } - getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== - "true" && - console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); - if (typeof options === "undefined") { - options = defaultOptions(); - } - decirc(obj, "", 0, [], undefined, 0, options); - let res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer); - } - else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); - } - } - catch (_) { - return encodeString("[unable to serialize, circular reference is too complex to analyze]"); - } - finally { - while (arr.length !== 0) { - const part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } - else { - part[0][part[1]] = part[2]; - } - } - } - return encodeString(res); - } -} -function setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - arr.push([parent, k, val, propertyDescriptor]); - } - else { - replacerStack.push([val, k, replace]); - } - } - else { - parent[k] = replace; - arr.push([parent, k, val]); - } -} -function decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } - } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options); - } - } - else { - // Handle well-known types before Object.keys iteration - val = serializeWellKnownTypes(val); - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - decirc(val[key], key, i, stack, val, depth, options); - } - } - stack.pop(); - } -} -// Stable-stringify -function compareFunction(a, b) { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} -function deterministicStringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") { - options = defaultOptions(); - } - var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; - var res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer); - } - else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); - } - } - catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } - finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } - else { - part[0][part[1]] = part[2]; - } - } - } - return res; -} -function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } - } - try { - if (typeof val.toJSON === "function") { - return; - } - } - catch (_) { - return; - } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options); - } - } - else { - // Handle well-known types before Object.keys iteration - val = serializeWellKnownTypes(val); - // Create a temporary object in the required way - var tmp = {}; - var keys = Object.keys(val).sort(compareFunction); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - deterministicDecirc(val[key], key, i, stack, val, depth, options); - tmp[key] = val[key]; - } - if (typeof parent !== "undefined") { - arr.push([parent, k, val]); - parent[k] = tmp; - } - else { - return tmp; - } - } - stack.pop(); - } -} -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues(replacer) { - replacer = - typeof replacer !== "undefined" - ? replacer - : function (k, v) { - return v; - }; - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - replacerStack.splice(i, 1); - break; - } - } - } - return replacer.call(this, key, val); - }; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js - - - - - - - - - - - - - -function mergeRuntimeEnvIntoRun(run, cachedEnvVars) { - const runtimeEnv = env_getRuntimeEnvironment(); - const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata(); - const extra = run.extra ?? {}; - const metadata = extra.metadata; - run.extra = { - ...extra, - runtime: { - ...runtimeEnv, - ...extra?.runtime, - }, - metadata: { - ...envVars, - ...(envVars.revision_id || ("revision_id" in run && run.revision_id) - ? { - revision_id: ("revision_id" in run ? run.revision_id : undefined) ?? - envVars.revision_id, - } - : {}), - ...metadata, - }, - }; - return run; -} -const getTracingSamplingRate = (configRate) => { - const samplingRateStr = configRate?.toString() ?? - getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); - if (samplingRateStr === undefined) { - return undefined; - } - const samplingRate = parseFloat(samplingRateStr); - if (samplingRate < 0 || samplingRate > 1) { - throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); - } - return samplingRate; -}; -// utility functions -const isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); -}; -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); - } - return result; -} -function trimQuotes(str) { - if (str === undefined) { - return undefined; - } - return str - .trim() - .replace(/^"(.*)"$/, "$1") - .replace(/^'(.*)'$/, "$1"); -} -const handle429 = async (response) => { - if (response?.status === 429) { - const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1000; - if (retryAfter > 0) { - await new Promise((resolve) => setTimeout(resolve, retryAfter)); - // Return directly after calling this check - return true; - } - } - // Fall back to existing status checks - return false; -}; -function _formatFeedbackScore(score) { - if (typeof score === "number") { - // Truncate at 4 decimal places - return Number(score.toFixed(4)); - } - return score; -} -class AutoBatchQueue { - constructor() { - Object.defineProperty(this, "items", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "sizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - } - peek() { - return this.items[0]; - } - push(item) { - let itemPromiseResolve; - const itemPromise = new Promise((resolve) => { - // Setting itemPromiseResolve is synchronous with promise creation: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise - itemPromiseResolve = resolve; - }); - const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; - this.items.push({ - action: item.action, - payload: item.item, - otelContext: item.otelContext, - apiKey: item.apiKey, - apiUrl: item.apiUrl, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - itemPromiseResolve: itemPromiseResolve, - itemPromise, - size, - }); - this.sizeBytes += size; - return itemPromise; - } - pop({ upToSizeBytes, upToSize, }) { - if (upToSizeBytes < 1) { - throw new Error("Number of bytes to pop off may not be less than 1."); - } - const popped = []; - let poppedSizeBytes = 0; - // Pop items until we reach or exceed the size limit - while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && - this.items.length > 0 && - popped.length < upToSize) { - const item = this.items.shift(); - if (item) { - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } - } - // If there is an item on the queue we were unable to pop, - // just return it as a single batch. - if (popped.length === 0 && this.items.length > 0) { - const item = this.items.shift(); - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } - return [ - popped.map((it) => ({ - action: it.action, - item: it.payload, - otelContext: it.otelContext, - apiKey: it.apiKey, - apiUrl: it.apiUrl, - })), - () => popped.forEach((it) => it.itemPromiseResolve()), - ]; - } -} -const DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 24 * 1024 * 1024; -const SERVER_INFO_REQUEST_TIMEOUT_MS = 10000; -/** Maximum number of operations to batch in a single request. */ -const DEFAULT_BATCH_SIZE_LIMIT = 100; -const DEFAULT_API_URL = "https://api.smith.langchain.com"; -class Client { - get _fetch() { - return this.fetchImplementation || _getFetchImplementation(this.debug); - } - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "workspaceId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchIngestCaller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "hideInputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "hideOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingSampleRate", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "filteredPostUuids", { - enumerable: true, - configurable: true, - writable: true, - value: new Set() - }); - Object.defineProperty(this, "autoBatchTracing", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "autoBatchQueue", { - enumerable: true, - configurable: true, - writable: true, - value: new AutoBatchQueue() - }); - Object.defineProperty(this, "autoBatchTimeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "autoBatchAggregationDelayMs", { - enumerable: true, - configurable: true, - writable: true, - value: 250 - }); - Object.defineProperty(this, "batchSizeBytesLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchSizeLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchOptions", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "settings", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "blockOnRootRunFinalization", { - enumerable: true, - configurable: true, - writable: true, - value: env_getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" - }); - Object.defineProperty(this, "traceBatchConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: 5 - }); - Object.defineProperty(this, "_serverInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "_getServerInfoPromise", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "manualFlushMode", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "langSmithToOTELTranslator", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchImplementation", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cachedLSEnvVarsForMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "multipartStreamingDisabled", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "debug", { - enumerable: true, - configurable: true, - writable: true, - value: env_getEnvironmentVariable("LANGSMITH_DEBUG") === "true" - }); - const defaultConfig = Client.getDefaultClientConfig(); - this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - if (this.apiUrl.endsWith("/")) { - this.apiUrl = this.apiUrl.slice(0, -1); - } - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - if (this.webUrl?.endsWith("/")) { - this.webUrl = this.webUrl.slice(0, -1); - } - this.workspaceId = trimQuotes(config.workspaceId ?? getLangSmithEnvironmentVariable("WORKSPACE_ID")); - this.timeout_ms = config.timeout_ms ?? 90_000; - this.caller = new AsyncCaller({ - ...(config.callerOptions ?? {}), - maxRetries: 4, - debug: config.debug ?? this.debug, - }); - this.traceBatchConcurrency = - config.traceBatchConcurrency ?? this.traceBatchConcurrency; - if (this.traceBatchConcurrency < 1) { - throw new Error("Trace batch concurrency must be positive."); - } - this.debug = config.debug ?? this.debug; - this.fetchImplementation = config.fetchImplementation; - this.batchIngestCaller = new AsyncCaller({ - maxRetries: 2, - maxConcurrency: this.traceBatchConcurrency, - ...(config.callerOptions ?? {}), - onFailedResponseHook: handle429, - debug: config.debug ?? this.debug, - }); - this.hideInputs = - config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; - this.hideOutputs = - config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; - this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; - this.blockOnRootRunFinalization = - config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; - this.batchSizeBytesLimit = config.batchSizeBytesLimit; - this.batchSizeLimit = config.batchSizeLimit; - this.fetchOptions = config.fetchOptions || {}; - this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; - if (getOtelEnabled()) { - this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); - } - // Cache metadata env vars once during construction to avoid repeatedly scanning process.env - this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata(); - } - static getDefaultClientConfig() { - const apiKey = getLangSmithEnvironmentVariable("API_KEY"); - const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; - const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; - const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; - return { - apiUrl: apiUrl, - apiKey: apiKey, - webUrl: undefined, - hideInputs: hideInputs, - hideOutputs: hideOutputs, - }; - } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; - } - else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost:3000"; - return this.webUrl; - } - else if (this.apiUrl.endsWith("/api/v1")) { - this.webUrl = this.apiUrl.replace("/api/v1", ""); - return this.webUrl; - } - else if (this.apiUrl.includes("/api") && - !this.apiUrl.split(".", 1)[0].endsWith("api")) { - this.webUrl = this.apiUrl.replace("/api", ""); - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("eu")) { - this.webUrl = "https://eu.smith.langchain.com"; - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("beta")) { - this.webUrl = "https://beta.smith.langchain.com"; - return this.webUrl; - } - else { - this.webUrl = "https://smith.langchain.com"; - return this.webUrl; - } - } - get headers() { - const headers = { - "User-Agent": `langsmith-js/${__version__}`, - }; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; - } - if (this.workspaceId) { - headers["x-tenant-id"] = this.workspaceId; - } - return headers; - } - _getPlatformEndpointPath(path) { - // Check if apiUrl already ends with /v1 or /v1/ to avoid double /v1/v1/ paths - const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; - return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; - } - async processInputs(inputs) { - if (this.hideInputs === false) { - return inputs; - } - if (this.hideInputs === true) { - return {}; - } - if (typeof this.hideInputs === "function") { - return this.hideInputs(inputs); - } - return inputs; - } - async processOutputs(outputs) { - if (this.hideOutputs === false) { - return outputs; - } - if (this.hideOutputs === true) { - return {}; - } - if (typeof this.hideOutputs === "function") { - return this.hideOutputs(outputs); - } - return outputs; - } - async prepareRunCreateOrUpdateInputs(run) { - const runParams = { ...run }; - if (runParams.inputs !== undefined) { - runParams.inputs = await this.processInputs(runParams.inputs); - } - if (runParams.outputs !== undefined) { - runParams.outputs = await this.processOutputs(runParams.outputs); - } - return runParams; - } - async _getResponse(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `fetch ${path}`); - return res; - }); - return response; - } - async _get(path, queryParams) { - const response = await this._getResponse(path, queryParams); - return response.json(); - } - async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { - let offset = Number(queryParams.get("offset")) || 0; - const limit = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset)); - queryParams.set("limit", String(limit)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `fetch ${path}`); - return res; - }); - const items = transform - ? transform(await response.json()) - : await response.json(); - if (items.length === 0) { - break; - } - yield items; - if (items.length < limit) { - break; - } - offset += items.length; - } - } - async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { - const bodyParams = body ? { ...body } : {}; - while (true) { - const body = JSON.stringify(bodyParams); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${path}`, { - method: requestMethod, - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, `fetch ${path}`); - return res; - }); - const responseBody = await response.json(); - if (!responseBody) { - break; - } - if (!responseBody[dataKey]) { - break; - } - yield responseBody[dataKey]; - const cursors = responseBody.cursors; - if (!cursors) { - break; - } - if (!cursors.next) { - break; - } - bodyParams.cursor = cursors.next; - } - } - // Allows mocking for tests - _shouldSample() { - if (this.tracingSampleRate === undefined) { - return true; - } - return Math.random() < this.tracingSampleRate; - } - _filterForSampling(runs, patch = false) { - if (this.tracingSampleRate === undefined) { - return runs; - } - if (patch) { - const sampled = []; - for (const run of runs) { - if (!this.filteredPostUuids.has(run.trace_id)) { - sampled.push(run); - } - else if (run.id === run.trace_id) { - this.filteredPostUuids.delete(run.trace_id); - } - } - return sampled; - } - else { - // For new runs, sample at trace level to maintain consistency - const sampled = []; - for (const run of runs) { - const traceId = run.trace_id ?? run.id; - // If we've already made a decision about this trace, follow it - if (this.filteredPostUuids.has(traceId)) { - continue; - } - // For new traces, apply sampling - if (run.id === traceId) { - if (this._shouldSample()) { - sampled.push(run); - } - else { - this.filteredPostUuids.add(traceId); - } - } - else { - // Child runs follow their trace's sampling decision - sampled.push(run); - } - } - return sampled; - } - } - async _getBatchSizeLimitBytes() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeBytesLimit ?? - serverInfo.batch_ingest_config?.size_limit_bytes ?? - DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES); - } - /** - * Get the maximum number of operations to batch in a single request. - */ - async _getBatchSizeLimit() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeLimit ?? - serverInfo.batch_ingest_config?.size_limit ?? - DEFAULT_BATCH_SIZE_LIMIT); - } - async _getDatasetExamplesMultiPartSupport() { - const serverInfo = await this._ensureServerInfo(); - return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); - } - drainAutoBatchQueue({ batchSizeLimitBytes, batchSizeLimit, }) { - const promises = []; - while (this.autoBatchQueue.items.length > 0) { - const [batch, done] = this.autoBatchQueue.pop({ - upToSizeBytes: batchSizeLimitBytes, - upToSize: batchSizeLimit, - }); - if (!batch.length) { - done(); - break; - } - const batchesByDestination = batch.reduce((acc, item) => { - const apiUrl = item.apiUrl ?? this.apiUrl; - const apiKey = item.apiKey ?? this.apiKey; - const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; - const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; - if (!acc[batchKey]) { - acc[batchKey] = []; - } - acc[batchKey].push(item); - return acc; - }, {}); - const batchPromises = []; - for (const [batchKey, batch] of Object.entries(batchesByDestination)) { - const batchPromise = this._processBatch(batch, { - apiUrl: batchKey === "default" ? undefined : batchKey.split("|")[0], - apiKey: batchKey === "default" ? undefined : batchKey.split("|")[1], - }); - batchPromises.push(batchPromise); - } - // Wait for all batches to complete, then call the overall done callback - const allBatchesPromise = Promise.all(batchPromises).finally(done); - promises.push(allBatchesPromise); - } - return Promise.all(promises); - } - async _processBatch(batch, options) { - if (!batch.length) { - return; - } - try { - if (this.langSmithToOTELTranslator !== undefined) { - this._sendBatchToOTELTranslator(batch); - } - else { - const ingestParams = { - runCreates: batch - .filter((item) => item.action === "create") - .map((item) => item.item), - runUpdates: batch - .filter((item) => item.action === "update") - .map((item) => item.item), - }; - const serverInfo = await this._ensureServerInfo(); - if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { - const useGzip = serverInfo?.instance_flags?.gzip_body_enabled; - await this.multipartIngestRuns(ingestParams, { ...options, useGzip }); - } - else { - await this.batchIngestRuns(ingestParams, options); - } - } - } - catch (e) { - console.error("Error exporting batch:", e); - } - } - _sendBatchToOTELTranslator(batch) { - if (this.langSmithToOTELTranslator !== undefined) { - const otelContextMap = new Map(); - const operations = []; - for (const item of batch) { - if (item.item.id && item.otelContext) { - otelContextMap.set(item.item.id, item.otelContext); - if (item.action === "create") { - operations.push({ - operation: "post", - id: item.item.id, - trace_id: item.item.trace_id ?? item.item.id, - run: item.item, - }); - } - else { - operations.push({ - operation: "patch", - id: item.item.id, - trace_id: item.item.trace_id ?? item.item.id, - run: item.item, - }); - } - } - } - this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); - } - } - async processRunOperation(item) { - clearTimeout(this.autoBatchTimeout); - this.autoBatchTimeout = undefined; - item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata); - const itemPromise = this.autoBatchQueue.push(item); - if (this.manualFlushMode) { - // Rely on manual flushing in serverless environments - return itemPromise; - } - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - const sizeLimit = await this._getBatchSizeLimit(); - if (this.autoBatchQueue.sizeBytes > sizeLimitBytes || - this.autoBatchQueue.items.length > sizeLimit) { - void this.drainAutoBatchQueue({ - batchSizeLimitBytes: sizeLimitBytes, - batchSizeLimit: sizeLimit, - }); - } - if (this.autoBatchQueue.items.length > 0) { - this.autoBatchTimeout = setTimeout(() => { - this.autoBatchTimeout = undefined; - void this.drainAutoBatchQueue({ - batchSizeLimitBytes: sizeLimitBytes, - batchSizeLimit: sizeLimit, - }); - }, this.autoBatchAggregationDelayMs); - } - return itemPromise; - } - async _getServerInfo() { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/info`, { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get server info"); - return res; - }); - const json = await response.json(); - if (this.debug) { - console.log("\n=== LangSmith Server Configuration ===\n" + - JSON.stringify(json, null, 2) + - "\n"); - } - return json; - } - async _ensureServerInfo() { - if (this._getServerInfoPromise === undefined) { - this._getServerInfoPromise = (async () => { - if (this._serverInfo === undefined) { - try { - this._serverInfo = await this._getServerInfo(); - } - catch (e) { - console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status ?? "Unspecified status code"} ${e.message}`); - } - } - return this._serverInfo ?? {}; - })(); - } - return this._getServerInfoPromise.then((serverInfo) => { - if (this._serverInfo === undefined) { - this._getServerInfoPromise = undefined; - } - return serverInfo; - }); - } - async _getSettings() { - if (!this.settings) { - this.settings = this._get("/settings"); - } - return await this.settings; - } - /** - * Flushes current queued traces. - */ - async flush() { - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - const sizeLimit = await this._getBatchSizeLimit(); - await this.drainAutoBatchQueue({ - batchSizeLimitBytes: sizeLimitBytes, - batchSizeLimit: sizeLimit, - }); - } - _cloneCurrentOTELContext() { - const otel_trace = getOTELTrace(); - const otel_context = getOTELContext(); - if (this.langSmithToOTELTranslator !== undefined) { - const currentSpan = otel_trace.getActiveSpan(); - if (currentSpan) { - return otel_trace.setSpan(otel_context.active(), currentSpan); - } - } - return undefined; - } - async createRun(run, options) { - if (!this._filterForSampling([run]).length) { - return; - } - const headers = { - ...this.headers, - "Content-Type": "application/json", - }; - const session_name = run.project_name; - delete run.project_name; - const runCreate = await this.prepareRunCreateOrUpdateInputs({ - session_name, - ...run, - start_time: run.start_time ?? Date.now(), - }); - if (this.autoBatchTracing && - runCreate.trace_id !== undefined && - runCreate.dotted_order !== undefined) { - const otelContext = this._cloneCurrentOTELContext(); - void this.processRunOperation({ - action: "create", - item: runCreate, - otelContext, - apiKey: options?.apiKey, - apiUrl: options?.apiUrl, - }).catch(console.error); - return; - } - const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata); - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - if (options?.workspaceId !== undefined) { - headers["x-tenant-id"] = options.workspaceId; - } - const body = serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`); - await this.caller.call(async () => { - const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs`, { - method: "POST", - headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create run", true); - return res; - }); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async batchIngestRuns({ runCreates, runUpdates, }, options) { - if (runCreates === undefined && runUpdates === undefined) { - return; - } - let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); - let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; - } - const rawBatch = { - post: preparedCreateParams, - patch: preparedUpdateParams, - }; - if (!rawBatch.post.length && !rawBatch.patch.length) { - return; - } - const batchChunks = { - post: [], - patch: [], - }; - for (const k of ["post", "patch"]) { - const key = k; - const batchItems = rawBatch[key].reverse(); - let batchItem = batchItems.pop(); - while (batchItem !== undefined) { - // Type is wrong but this is a deprecated code path anyway - batchChunks[key].push(batchItem); - batchItem = batchItems.pop(); - } - } - if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { - const runIds = batchChunks.post - .map((item) => item.id) - .concat(batchChunks.patch.map((item) => item.id)) - .join(","); - await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); - } - } - async _postBatchIngestRuns(body, options) { - const headers = { - ...this.headers, - "Content-Type": "application/json", - Accept: "application/json", - }; - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - await this.batchIngestCaller.call(async () => { - const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/batch`, { - method: "POST", - headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "batch create run", true); - return res; - }); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async multipartIngestRuns({ runCreates, runUpdates, }, options) { - if (runCreates === undefined && runUpdates === undefined) { - return; - } - // transform and convert to dicts - const allAttachments = {}; - let preparedCreateParams = []; - for (const create of runCreates ?? []) { - const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); - if (preparedCreate.id !== undefined && - preparedCreate.attachments !== undefined) { - allAttachments[preparedCreate.id] = preparedCreate.attachments; - } - delete preparedCreate.attachments; - preparedCreateParams.push(preparedCreate); - } - let preparedUpdateParams = []; - for (const update of runUpdates ?? []) { - preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); - } - // require trace_id and dotted_order - const invalidRunCreate = preparedCreateParams.find((runCreate) => { - return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); - }); - if (invalidRunCreate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); - } - const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { - return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); - }); - if (invalidRunUpdate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); - } - // combine post and patch dicts where possible - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; - } - if (preparedCreateParams.length === 0 && - preparedUpdateParams.length === 0) { - return; - } - // send the runs in multipart requests - const accumulatedContext = []; - const accumulatedParts = []; - for (const [method, payloads] of [ - ["post", preparedCreateParams], - ["patch", preparedUpdateParams], - ]) { - for (const originalPayload of payloads) { - // collect fields to be sent as separate parts - const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload; - const fields = { inputs, outputs, events, extra, error, serialized }; - // encode the main run payload - const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); - accumulatedParts.push({ - name: `${method}.${payload.id}`, - payload: new Blob([stringifiedPayload], { - type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip - }), - }); - // encode the fields we collected - for (const [key, value] of Object.entries(fields)) { - if (value === undefined) { - continue; - } - const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); - accumulatedParts.push({ - name: `${method}.${payload.id}.${key}`, - payload: new Blob([stringifiedValue], { - type: `application/json; length=${stringifiedValue.length}`, - }), - }); - } - // encode the attachments - if (payload.id !== undefined) { - const attachments = allAttachments[payload.id]; - if (attachments) { - delete allAttachments[payload.id]; - for (const [name, attachment] of Object.entries(attachments)) { - let contentType; - let content; - if (Array.isArray(attachment)) { - [contentType, content] = attachment; - } - else { - contentType = attachment.mimeType; - content = attachment.data; - } - // Validate that the attachment name doesn't contain a '.' - if (name.includes(".")) { - console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + - `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); - continue; - } - accumulatedParts.push({ - name: `attachment.${payload.id}.${name}`, - payload: new Blob([content], { - type: `${contentType}; length=${content.byteLength}`, - }), - }); - } - } - } - // compute context - accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); - } - } - await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); - } - async _createNodeFetchBody(parts, boundary) { - // Create multipart form data manually using Blobs - const chunks = []; - for (const part of parts) { - // Add field boundary - chunks.push(new Blob([`--${boundary}\r\n`])); - chunks.push(new Blob([ - `Content-Disposition: form-data; name="${part.name}"\r\n`, - `Content-Type: ${part.payload.type}\r\n\r\n`, - ])); - chunks.push(part.payload); - chunks.push(new Blob(["\r\n"])); - } - // Add final boundary - chunks.push(new Blob([`--${boundary}--\r\n`])); - // Combine all chunks into a single Blob - const body = new Blob(chunks); - // Convert Blob to ArrayBuffer for compatibility - const arrayBuffer = await body.arrayBuffer(); - return arrayBuffer; - } - async _createMultipartStream(parts, boundary) { - const encoder = new TextEncoder(); - // Create a ReadableStream for streaming the multipart data - // Only do special handling if we're using node-fetch - const stream = new ReadableStream({ - async start(controller) { - // Helper function to write a chunk to the stream - const writeChunk = async (chunk) => { - if (typeof chunk === "string") { - controller.enqueue(encoder.encode(chunk)); - } - else { - controller.enqueue(chunk); - } - }; - // Write each part to the stream - for (const part of parts) { - // Write boundary and headers - await writeChunk(`--${boundary}\r\n`); - await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); - await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); - // Write the payload - const payloadStream = part.payload.stream(); - const reader = payloadStream.getReader(); - try { - let result; - while (!(result = await reader.read()).done) { - controller.enqueue(result.value); - } - } - finally { - reader.releaseLock(); - } - await writeChunk("\r\n"); - } - // Write final boundary - await writeChunk(`--${boundary}--\r\n`); - controller.close(); - }, - }); - return stream; - } - async _sendMultipartRequest(parts, context, options) { - // Create multipart form data boundary - const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); - const isNodeFetch = _globalFetchImplementationIsNodeFetch(); - const buildBuffered = () => this._createNodeFetchBody(parts, boundary); - const buildStream = () => this._createMultipartStream(parts, boundary); - const sendWithRetry = async (bodyFactory) => { - return this.batchIngestCaller.call(async () => { - const body = await bodyFactory(); - const headers = { - ...this.headers, - "Content-Type": `multipart/form-data; boundary=${boundary}`, - }; - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - let transformedBody = body; - if (options?.useGzip && - typeof body === "object" && - "pipeThrough" in body) { - transformedBody = body.pipeThrough(new CompressionStream("gzip")); - headers["Content-Encoding"] = "gzip"; - } - const response = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { - method: "POST", - headers, - body: transformedBody, - duplex: "half", - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to send multipart request`, true); - return response; - }); - }; - try { - let res; - let streamedAttempt = false; - // attempt stream only if not disabled and not using node-fetch or Bun - if (!isNodeFetch && - !this.multipartStreamingDisabled && - env_getEnv() !== "bun") { - streamedAttempt = true; - res = await sendWithRetry(buildStream); - } - else { - res = await sendWithRetry(buildBuffered); - } - // if stream fails, fallback to buffered body - if ((!this.multipartStreamingDisabled || streamedAttempt) && - res.status === 422 && - (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { - console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. ` + - `This usually means the host does not support chunked uploads. ` + - `Retrying with a buffered upload for operation "${context}".`); - // Disable streaming for future requests - this.multipartStreamingDisabled = true; - // retry with fully-buffered body - res = await sendWithRetry(buildBuffered); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - console.warn(`${e.message.trim()}\n\nContext: ${context}`); - } - } - async updateRun(runId, run, options) { - assertUuid(runId); - if (run.inputs) { - run.inputs = await this.processInputs(run.inputs); - } - if (run.outputs) { - run.outputs = await this.processOutputs(run.outputs); - } - // TODO: Untangle types - const data = { ...run, id: runId }; - if (!this._filterForSampling([data], true).length) { - return; - } - if (this.autoBatchTracing && - data.trace_id !== undefined && - data.dotted_order !== undefined) { - const otelContext = this._cloneCurrentOTELContext(); - if (run.end_time !== undefined && - data.parent_run_id === undefined && - this.blockOnRootRunFinalization && - !this.manualFlushMode) { - // Trigger batches as soon as a root trace ends and wait to ensure trace finishes - // in serverless environments. - await this.processRunOperation({ - action: "update", - item: data, - otelContext, - apiKey: options?.apiKey, - apiUrl: options?.apiUrl, - }).catch(console.error); - return; - } - else { - void this.processRunOperation({ - action: "update", - item: data, - otelContext, - apiKey: options?.apiKey, - apiUrl: options?.apiUrl, - }).catch(console.error); - } - return; - } - const headers = { - ...this.headers, - "Content-Type": "application/json", - }; - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - if (options?.workspaceId !== undefined) { - headers["x-tenant-id"] = options.workspaceId; - } - const body = serialize(run, `Serializing payload to update run with id: ${runId}`); - await this.caller.call(async () => { - const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update run", true); - return res; - }); - } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - assertUuid(runId); - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns) { - run = await this._loadChildRuns(run); - } - return run; - } - async getRunUrl({ runId, run, projectOpts, }) { - if (run !== undefined) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; - } - else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; - } - else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; - } - else { - const project = await this.readProject({ - projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", - }); - sessionId = project.id; - } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; - } - else if (runId !== undefined) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); - } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; - } - else { - throw new Error("Must provide either runId or run"); - } - } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ - isRoot: false, - projectId: run.session_id, - traceId: run.trace_id, - })); - const treemap = {}; - const runs = {}; - // TODO: make dotted order required when the migration finishes - childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || - childRun.parent_run_id === undefined) { - throw new Error(`Child run ${childRun.id} has no parent`); - } - if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && - childRun.id !== run.id) { - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; - } - } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; - } - } - return run; - } - /** - * List runs from the LangSmith server. - * @param projectId - The ID of the project to filter by. - * @param projectName - The name of the project to filter by. - * @param parentRunId - The ID of the parent run to filter by. - * @param traceId - The ID of the trace to filter by. - * @param referenceExampleId - The ID of the reference example to filter by. - * @param startTime - The start time to filter by. - * @param isRoot - Indicates whether to only return root runs. - * @param runType - The run type to filter by. - * @param error - Indicates whether to filter by error runs. - * @param id - The ID of the run to filter by. - * @param query - The query string to filter by. - * @param filter - The filter string to apply to the run spans. - * @param traceFilter - The filter string to apply on the root run of the trace. - * @param treeFilter - The filter string to apply on other runs in the trace. - * @param limit - The maximum number of runs to retrieve. - * @returns {AsyncIterable} - The runs. - * - * @example - * // List all runs in a project - * const projectRuns = client.listRuns({ projectName: "" }); - * - * @example - * // List LLM and Chat runs in the last 24 hours - * const todaysLLMRuns = client.listRuns({ - * projectName: "", - * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), - * run_type: "llm", - * }); - * - * @example - * // List traces in a project - * const rootRuns = client.listRuns({ - * projectName: "", - * execution_order: 1, - * }); - * - * @example - * // List runs without errors - * const correctRuns = client.listRuns({ - * projectName: "", - * error: false, - * }); - * - * @example - * // List runs by run ID - * const runIds = [ - * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", - * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", - * ]; - * const selectedRuns = client.listRuns({ run_ids: runIds }); - * - * @example - * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 - * const chainRuns = client.listRuns({ - * projectName: "", - * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', - * }); - * - * @example - * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 - * const goodExtractorRuns = client.listRuns({ - * projectName: "", - * filter: 'eq(name, "extractor")', - * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', - * }); - * - * @example - * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 - * const complexRuns = client.listRuns({ - * projectName: "", - * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', - * }); - * - * @example - * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds - * const taggedRuns = client.listRuns({ - * projectName: "", - * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', - * }); - */ - async *listRuns(props) { - const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; - let projectIds = []; - if (projectId) { - projectIds = Array.isArray(projectId) ? projectId : [projectId]; - } - if (projectName) { - const projectNames = Array.isArray(projectName) - ? projectName - : [projectName]; - const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); - projectIds.push(...projectIds_); - } - const default_select = [ - "app_path", - "completion_cost", - "completion_tokens", - "dotted_order", - "end_time", - "error", - "events", - "extra", - "feedback_stats", - "first_token_time", - "id", - "inputs", - "name", - "outputs", - "parent_run_id", - "parent_run_ids", - "prompt_cost", - "prompt_tokens", - "reference_example_id", - "run_type", - "session_id", - "start_time", - "status", - "tags", - "total_cost", - "total_tokens", - "trace_id", - ]; - const body = { - session: projectIds.length ? projectIds : null, - run_type: runType, - reference_example: referenceExampleId, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - execution_order: executionOrder, - parent_run: parentRunId, - start_time: startTime ? startTime.toISOString() : null, - error, - id, - limit, - trace: traceId, - select: select ? select : default_select, - is_root: isRoot, - order, - }; - if (body.select.includes("child_run_ids")) { - warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version."); - } - let runsYielded = 0; - for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { - if (limit) { - if (runsYielded >= limit) { - break; - } - if (runs.length + runsYielded > limit) { - const newRuns = runs.slice(0, limit - runsYielded); - yield* newRuns; - break; - } - runsYielded += runs.length; - yield* runs; - } - else { - yield* runs; - } - } - } - async *listGroupRuns(props) { - const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; - const sessionId = projectId || (await this.readProject({ projectName })).id; - const baseBody = { - session_id: sessionId, - group_by: groupBy, - filter, - start_time: startTime ? startTime.toISOString() : null, - end_time: endTime ? endTime.toISOString() : null, - limit: Number(limit) || 100, - }; - let currentOffset = Number(offset) || 0; - const path = "/runs/group"; - const url = `${this.apiUrl}${path}`; - while (true) { - const currentBody = { - ...baseBody, - offset: currentOffset, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); - const body = JSON.stringify(filteredPayload); - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, `Failed to fetch ${path}`); - return res; - }); - const items = await response.json(); - const { groups, total } = items; - if (groups.length === 0) { - break; - } - for (const thread of groups) { - yield thread; - } - currentOffset += groups.length; - if (currentOffset >= total) { - break; - } - } - } - async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { - let projectIds_ = projectIds || []; - if (projectNames) { - projectIds_ = [ - ...(projectIds || []), - ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), - ]; - } - const payload = { - id, - trace, - parent_run: parentRun, - run_type: runType, - session: projectIds_, - reference_example: referenceExampleIds, - start_time: startTime, - end_time: endTime, - error, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - is_root: isRoot, - data_source_type: dataSourceType, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); - const body = JSON.stringify(filteredPayload); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/stats`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "get run stats"); - return res; - }); - const result = await response.json(); - return result; - } - async shareRun(runId, { shareId } = {}) { - const data = { - run_id: runId, - share_token: shareId || wrapper_v4(), - }; - assertUuid(runId); - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "share run"); - return res; - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async unshareRun(runId) { - assertUuid(runId); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "unshare run", true); - return res; - }); - } - async readRunSharedLink(runId) { - assertUuid(runId); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read run shared link"); - return res; - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return undefined; - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async listSharedRuns(shareToken, { runIds, } = {}) { - const queryParams = new URLSearchParams({ - share_token: shareToken, - }); - if (runIds !== undefined) { - for (const runId of runIds) { - queryParams.append("id", runId); - } - } - assertUuid(shareToken); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "list shared runs"); - return res; - }); - const runs = await response.json(); - return runs; - } - async readDatasetSharedSchema(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - assertUuid(datasetId); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read dataset shared schema"); - return res; - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; - } - async shareDataset(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - const data = { - dataset_id: datasetId, - }; - assertUuid(datasetId); - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { - method: "PUT", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "share dataset"); - return res; - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; - } - async unshareDataset(datasetId) { - assertUuid(datasetId); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "unshare dataset", true); - return res; - }); - } - async readSharedDataset(shareToken) { - assertUuid(shareToken); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/datasets`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read shared dataset"); - return res; - }); - const dataset = await response.json(); - return dataset; - } - /** - * Get shared examples. - * - * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. - * @param {Object} [options] Additional options for listing the examples. - * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. - * @returns {Promise} The shared examples. - */ - async listSharedExamples(shareToken, options) { - const params = {}; - if (options?.exampleIds) { - params.id = options.exampleIds; - } - const urlParams = new URLSearchParams(); - Object.entries(params).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((v) => urlParams.append(key, v)); - } - else { - urlParams.append(key, value); - } - }); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "list shared examples"); - return res; - }); - const result = await response.json(); - if (!response.ok) { - if ("detail" in result) { - throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) - ? result.detail.join("\n") - : "Unspecified error"}`); - } - throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); - } - return result.map((example) => ({ - ...example, - _hostUrl: this.getHostUrl(), - })); - } - async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const extra = projectExtra || {}; - if (metadata) { - extra["metadata"] = metadata; - } - const body = { - name: projectName, - extra, - description, - }; - if (referenceDatasetId !== null) { - body["reference_dataset_id"] = referenceDatasetId; - } - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(endpoint, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create project"); - return res; - }); - const result = await response.json(); - return result; - } - async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { - const endpoint = `${this.apiUrl}/sessions/${projectId}`; - let extra = projectExtra; - if (metadata) { - extra = { ...(extra || {}), metadata }; - } - const body = JSON.stringify({ - name, - extra, - description, - end_time: endTime ? new Date(endTime).toISOString() : null, - }); - const response = await this.caller.call(async () => { - const res = await this._fetch(endpoint, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update project"); - return res; - }); - const result = await response.json(); - return result; - } - async hasProject({ projectId, projectName, }) { - // TODO: Add a head request - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${path}?${params}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "has project"); - return res; - }); - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - try { - const result = await response.json(); - if (!response.ok) { - return false; - } - // If it's OK and we're querying by name, need to check the list is not empty - if (Array.isArray(result)) { - return result.length > 0; - } - // projectId querying - return true; - } - catch (e) { - return false; - } - } - async readProject({ projectId, projectName, includeStats, }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); - } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); - } - result = response[0]; - } - else { - result = response; - } - return result; - } - async getProjectUrl({ projectId, projectName, }) { - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide either projectName or projectId"); - } - const project = await this.readProject({ projectId, projectName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; - } - async getDatasetUrl({ datasetId, datasetName, }) { - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - const dataset = await this.readDataset({ datasetId, datasetName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; - } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; - } - throw new Error("No projects found to resolve tenant."); - } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, includeStats, datasetVersion, referenceFree, metadata, } = {}) { - const params = new URLSearchParams(); - if (projectIds !== undefined) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== undefined) { - params.append("name", name); - } - if (nameContains !== undefined) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== undefined) { - params.append("reference_dataset", referenceDatasetId); - } - else if (referenceDatasetName !== undefined) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName, - }); - params.append("reference_dataset", dataset.id); - } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); - } - if (datasetVersion !== undefined) { - params.append("dataset_version", datasetVersion); - } - if (referenceFree !== undefined) { - params.append("reference_free", referenceFree.toString()); - } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; - } - } - async deleteProject({ projectId, projectName, }) { - let projectId_; - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide projectName or projectId"); - } - else if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId === undefined) { - projectId_ = (await this.readProject({ projectName })).id; - } - else { - projectId_ = projectId; - } - assertUuid(projectId_); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete session ${projectId_} (${projectName})`, true); - return res; - }); - } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); - }); - if (description) { - formData.append("description", description); - } - if (dataType) { - formData.append("data_type", dataType); - } - if (name) { - formData.append("name", name); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "POST", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: formData, - }); - await raiseForStatus(res, "upload CSV"); - return res; - }); - const result = await response.json(); - return result; - } - async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { - const body = { - name, - description, - extra: metadata ? { metadata } : undefined, - }; - if (dataType) { - body.data_type = dataType; - } - if (inputsSchema) { - body.inputs_schema_definition = inputsSchema; - } - if (outputsSchema) { - body.outputs_schema_definition = outputsSchema; - } - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create dataset"); - return res; - }); - const result = await response.json(); - return result; - } - async readDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - // limit to 1 result - const params = new URLSearchParams({ limit: "1" }); - if (datasetId && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId) { - assertUuid(datasetId); - path += `/${datasetId}`; - } - else if (datasetName) { - params.append("name", datasetName); - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); - } - result = response[0]; - } - else { - result = response; - } - return result; - } - async hasDataset({ datasetId, datasetName, }) { - try { - await this.readDataset({ datasetId, datasetName }); - return true; - } - catch (e) { - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - e instanceof Error && - e.message.toLocaleLowerCase().includes("not found")) { - return false; - } - throw e; - } - } - async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { - let datasetId_ = datasetId; - if (datasetId_ === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - const urlParams = new URLSearchParams({ - from_version: typeof fromVersion === "string" - ? fromVersion - : fromVersion.toISOString(), - to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), - }); - const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); - return response; - } - async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { - const path = "/datasets"; - if (datasetId !== undefined) { - // do nothing - } - else if (datasetName !== undefined) { - datasetId = (await this.readDataset({ datasetName })).id; - } - else { - throw new Error("Must provide either datasetName or datasetId"); - } - const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); - const datasetText = await response.text(); - const dataset = datasetText - .trim() - .split("\n") - .map((line) => JSON.parse(line)); - return dataset; - } - async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit.toString(), - offset: offset.toString(), - }); - if (datasetIds !== undefined) { - for (const id_ of datasetIds) { - params.append("id", id_); - } - } - if (datasetName !== undefined) { - params.append("name", datasetName); - } - if (datasetNameContains !== undefined) { - params.append("name_contains", datasetNameContains); - } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; - } - } - /** - * Update a dataset - * @param props The dataset details to update - * @returns The updated dataset - */ - async updateDataset(props) { - const { datasetId, datasetName, ...update } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const body = JSON.stringify(update); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update dataset"); - return res; - }); - return (await response.json()); - } - /** - * Updates a tag on a dataset. - * - * If the tag is already assigned to a different version of this dataset, - * the tag will be moved to the new version. The as_of parameter is used to - * determine which version of the dataset to apply the new tags to. - * - * It must be an exact version of the dataset to succeed. You can - * use the "readDatasetVersion" method to find the exact version - * to apply the tags to. - * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. - * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. - * @param params.asOf The timestamp of the dataset to apply the new tags to. - * @param params.tag The new tag to apply to the dataset. - */ - async updateDatasetTag(props) { - const { datasetId, datasetName, asOf, tag } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const body = JSON.stringify({ - as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), - tag, - }); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}/tags`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update dataset tags", true); - return res; - }); - } - async deleteDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - if (datasetId_ !== undefined) { - assertUuid(datasetId_); - path += `/${datasetId_}`; - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - await this.caller.call(async () => { - const res = await this._fetch(this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete ${path}`, true); - return res; - }); - } - async indexDataset({ datasetId, datasetName, tag, }) { - let datasetId_ = datasetId; - if (!datasetId_ && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (!datasetId_) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - assertUuid(datasetId_); - const data = { - tag: tag, - }; - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/index`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "index dataset"); - return res; - }); - await response.json(); - } - /** - * Lets you run a similarity search query on a dataset. - * - * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. - * - * @param inputs The input on which to run the similarity search. Must have the - * same schema as the dataset. - * - * @param datasetId The dataset to search for similar examples. - * - * @param limit The maximum number of examples to return. Will return the top `limit` most - * similar examples in order of most similar to least similar. If no similar - * examples are found, random examples will be returned. - * - * @param filter A filter string to apply to the search. Only examples will be returned that - * match the filter string. Some examples of filters - * - * - eq(metadata.mykey, "value") - * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) - * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) - * - * @returns A list of similar examples. - * - * - * @example - * dataset_id = "123e4567-e89b-12d3-a456-426614174000" - * inputs = {"text": "How many people live in Berlin?"} - * limit = 5 - * examples = await client.similarExamples(inputs, dataset_id, limit) - */ - async similarExamples(inputs, datasetId, limit, { filter, } = {}) { - const data = { - limit: limit, - inputs: inputs, - }; - if (filter !== undefined) { - data["filter"] = filter; - } - assertUuid(datasetId); - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/search`, { - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - method: "POST", - body, - }); - await raiseForStatus(res, "fetch similar examples"); - return res; - }); - const result = await response.json(); - return result["examples"]; - } - async createExample(inputsOrUpdate, outputs, options) { - if (isExampleCreate(inputsOrUpdate)) { - if (outputs !== undefined || options !== undefined) { - throw new Error("Cannot provide outputs or options when using ExampleCreate object"); - } - } - let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; - const datasetName_ = outputs - ? options?.datasetName - : inputsOrUpdate.dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); - let data; - if (!isExampleCreate(inputsOrUpdate)) { - data = { - inputs: inputsOrUpdate, - outputs, - created_at: createdAt_?.toISOString(), - id: options?.exampleId, - metadata: options?.metadata, - split: options?.split, - source_run_id: options?.sourceRunId, - use_source_run_io: options?.useSourceRunIO, - use_source_run_attachments: options?.useSourceRunAttachments, - attachments: options?.attachments, - }; - } - else { - data = inputsOrUpdate; - } - const response = await this._uploadExamplesMultipart(datasetId_, [data]); - const example = await this.readExample(response.example_ids?.[0] ?? wrapper_v4()); - return example; - } - async createExamples(propsOrUploads) { - if (Array.isArray(propsOrUploads)) { - if (propsOrUploads.length === 0) { - return []; - } - const uploads = propsOrUploads; - let datasetId_ = uploads[0].dataset_id; - const datasetName_ = uploads[0].dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const response = await this._uploadExamplesMultipart(datasetId_, uploads); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; - if (inputs === undefined) { - throw new Error("Must provide inputs when using legacy parameters"); - } - let datasetId_ = datasetId; - const datasetName_ = datasetName; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const formattedExamples = inputs.map((input, idx) => { - return { - dataset_id: datasetId_, - inputs: input, - outputs: outputs?.[idx], - metadata: metadata?.[idx], - split: splits?.[idx], - id: exampleIds?.[idx], - attachments: attachments?.[idx], - source_run_id: sourceRunIds?.[idx], - use_source_run_io: useSourceRunIOs?.[idx], - use_source_run_attachments: useSourceRunAttachments?.[idx], - }; - }); - const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); - } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); - } - return message; - }); - const finalOutput = isLangChainMessage(generations) - ? convertLangChainMessageToExample(generations) - : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); - } - async readExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const rawExample = await this._get(path); - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type, - }; - return acc; - }, {}); - } - return example; - } - async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { - let datasetId_; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - datasetId_ = datasetId; - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - throw new Error("Must provide a datasetName or datasetId"); - } - const params = new URLSearchParams({ dataset: datasetId_ }); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const inlineS3Urls_ = inlineS3Urls ?? true; - params.append("inline_s3_urls", inlineS3Urls_.toString()); - if (exampleIds !== undefined) { - for (const id_ of exampleIds) { - params.append("id", id_); - } - } - if (splits !== undefined) { - for (const split of splits) { - params.append("splits", split); - } - } - if (metadata !== undefined) { - const serializedMetadata = JSON.stringify(metadata); - params.append("metadata", serializedMetadata); - } - if (limit !== undefined) { - params.append("limit", limit.toString()); - } - if (offset !== undefined) { - params.append("offset", offset.toString()); - } - if (filter !== undefined) { - params.append("filter", filter); - } - if (includeAttachments === true) { - ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); - } - let i = 0; - for await (const rawExamples of this._getPaginated("/examples", params)) { - for (const rawExample of rawExamples) { - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type || undefined, - }; - return acc; - }, {}); - } - yield example; - i++; - } - if (limit !== undefined && i >= limit) { - break; - } - } - } - async deleteExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - await this.caller.call(async () => { - const res = await this._fetch(this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete ${path}`, true); - return res; - }); - } - async updateExample(exampleIdOrUpdate, update) { - let exampleId; - if (update) { - exampleId = exampleIdOrUpdate; - } - else { - exampleId = exampleIdOrUpdate.id; - } - assertUuid(exampleId); - let updateToUse; - if (update) { - updateToUse = { id: exampleId, ...update }; - } - else { - updateToUse = exampleIdOrUpdate; - } - let datasetId; - if (updateToUse.dataset_id !== undefined) { - datasetId = updateToUse.dataset_id; - } - else { - const example = await this.readExample(exampleId); - datasetId = example.dataset_id; - } - return this._updateExamplesMultipart(datasetId, [updateToUse]); - } - async updateExamples(update) { - // We will naively get dataset id from first example and assume it works for all - let datasetId; - if (update[0].dataset_id === undefined) { - const example = await this.readExample(update[0].id); - datasetId = example.dataset_id; - } - else { - datasetId = update[0].dataset_id; - } - return this._updateExamplesMultipart(datasetId, update); - } - /** - * Get dataset version by closest date or exact tag. - * - * Use this to resolve the nearest version to a given timestamp or for a given tag. - * - * @param options The options for getting the dataset version - * @param options.datasetId The ID of the dataset - * @param options.datasetName The name of the dataset - * @param options.asOf The timestamp of the dataset to retrieve - * @param options.tag The tag of the dataset to retrieve - * @returns The dataset version - */ - async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { - let resolvedDatasetId; - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - resolvedDatasetId = dataset.id; - } - else { - resolvedDatasetId = datasetId; - } - assertUuid(resolvedDatasetId); - if ((asOf && tag) || (!asOf && !tag)) { - throw new Error("Exactly one of asOf and tag must be specified."); - } - const params = new URLSearchParams(); - if (asOf !== undefined) { - params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); - } - if (tag !== undefined) { - params.append("tag", tag); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { - method: "GET", - headers: { ...this.headers }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read dataset version"); - return res; - }); - return await response.json(); - } - async listDatasetSplits({ datasetId, datasetName, asOf, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); - } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const params = new URLSearchParams(); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const response = await this._get(`/datasets/${datasetId_}/splits`, params); - return response; - } - async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); - } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const data = { - split_name: splitName, - examples: exampleIds.map((id) => { - assertUuid(id); - return id; - }), - remove, - }; - const body = JSON.stringify(data); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/splits`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update dataset splits", true); - return res; - }); - } - /** - * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. - */ - async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { - warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); - let run_; - if (typeof run === "string") { - run_ = await this.readRun(run, { loadChildRuns }); - } - else if (typeof run === "object" && "id" in run) { - run_ = run; - } - else { - throw new Error(`Invalid run type: ${typeof run}`); - } - if (run_.reference_example_id !== null && - run_.reference_example_id !== undefined) { - referenceExample = await this.readExample(run_.reference_example_id); - } - const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); - const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); - return feedbacks[0]; - } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { - if (!runId && !projectId) { - throw new Error("One of runId or projectId must be provided"); - } - if (runId && projectId) { - throw new Error("Only one of runId or projectId can be provided"); - } - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {}, - }; - if (sourceRunId !== undefined && - feedback_source?.metadata !== undefined && - !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; - } - if (feedback_source?.metadata !== undefined && - feedback_source.metadata["__run"]?.run_id !== undefined) { - assertUuid(feedback_source.metadata["__run"].run_id); - } - const feedback = { - id: feedbackId ?? wrapper_v4(), - run_id: runId, - key, - score: _formatFeedbackScore(score), - value, - correction, - comment, - feedback_source: feedback_source, - comparative_experiment_id: comparativeExperimentId, - feedbackConfig, - session_id: projectId, - }; - const body = JSON.stringify(feedback); - const url = `${this.apiUrl}/feedback`; - await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create feedback", true); - return res; - }); - return feedback; - } - async updateFeedback(feedbackId, { score, value, correction, comment, }) { - const feedbackUpdate = {}; - if (score !== undefined && score !== null) { - feedbackUpdate["score"] = _formatFeedbackScore(score); - } - if (value !== undefined && value !== null) { - feedbackUpdate["value"] = value; - } - if (correction !== undefined && correction !== null) { - feedbackUpdate["correction"] = correction; - } - if (comment !== undefined && comment !== null) { - feedbackUpdate["comment"] = comment; - } - assertUuid(feedbackId); - const body = JSON.stringify(feedbackUpdate); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/feedback/${feedbackId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update feedback", true); - return res; - }); - } - async readFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; - } - async deleteFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - await this.caller.call(async () => { - const res = await this._fetch(this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete ${path}`, true); - return res; - }); - } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - for (const runId of runIds) { - assertUuid(runId); - queryParams.append("run", runId); - } - } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); - } - } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); - } - } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; - } - } - /** - * Creates a presigned feedback token and URL. - * - * The token can be used to authorize feedback metrics without - * needing an API key. This is useful for giving browser-based - * applications the ability to submit feedback without needing - * to expose an API key. - * - * @param runId The ID of the run. - * @param feedbackKey The feedback key. - * @param options Additional options for the token. - * @param options.expiration The expiration time for the token. - * - * @returns A promise that resolves to a FeedbackIngestToken. - */ - async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { - const body = { - run_id: runId, - feedback_key: feedbackKey, - feedback_config: feedbackConfig, - }; - if (expiration) { - if (typeof expiration === "string") { - body["expires_at"] = expiration; - } - else if (expiration?.hours || expiration?.minutes || expiration?.days) { - body["expires_in"] = expiration; - } - } - else { - body["expires_in"] = { - hours: 3, - }; - } - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/feedback/tokens`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create presigned feedback token"); - return res; - }); - return await response.json(); - } - async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { - if (experimentIds.length === 0) { - throw new Error("At least one experiment is required"); - } - if (!referenceDatasetId) { - referenceDatasetId = (await this.readProject({ - projectId: experimentIds[0], - })).reference_dataset_id; - } - if (!referenceDatasetId == null) { - throw new Error("A reference dataset is required"); - } - const body = { - id, - name, - experiment_ids: experimentIds, - reference_dataset_id: referenceDatasetId, - description, - created_at: (createdAt ?? new Date())?.toISOString(), - extra: {}, - }; - if (metadata) - body.extra["metadata"] = metadata; - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/comparative`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create comparative experiment"); - return res; - }); - return response.json(); - } - /** - * Retrieves a list of presigned feedback tokens for a given run ID. - * @param runId The ID of the run. - * @returns An async iterable of FeedbackIngestToken objects. - */ - async *listPresignedFeedbackTokens(runId) { - assertUuid(runId); - const params = new URLSearchParams({ run_id: runId }); - for await (const tokens of this._getPaginated("/feedback/tokens", params)) { - yield* tokens; - } - } - _selectEvalResults(results) { - let results_; - if ("results" in results) { - results_ = results.results; - } - else if (Array.isArray(results)) { - results_ = results; - } - else { - results_ = [results]; - } - return results_; - } - async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const evalResults = this._selectEvalResults(evaluatorResponse); - const feedbacks = []; - for (const res of evalResults) { - let sourceInfo_ = sourceInfo || {}; - if (res.evaluatorInfo) { - sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; - } - let runId_ = null; - if (res.targetRunId) { - runId_ = res.targetRunId; - } - else if (run) { - runId_ = run.id; - } - feedbacks.push(await this.createFeedback(runId_, res.key, { - score: res.score, - value: res.value, - comment: res.comment, - correction: res.correction, - sourceInfo: sourceInfo_, - sourceRunId: res.sourceRunId, - feedbackConfig: res.feedbackConfig, - feedbackSourceType: "model", - })); - } - return [evalResults, feedbacks]; - } - async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); - return results; - } - /** - * API for managing annotation queues - */ - /** - * List the annotation queues on the LangSmith API. - * @param options - The options for listing annotation queues - * @param options.queueIds - The IDs of the queues to filter by - * @param options.name - The name of the queue to filter by - * @param options.nameContains - The substring that the queue name should contain - * @param options.limit - The maximum number of queues to return - * @returns An iterator of AnnotationQueue objects - */ - async *listAnnotationQueues(options = {}) { - const { queueIds, name, nameContains, limit } = options; - const params = new URLSearchParams(); - if (queueIds) { - queueIds.forEach((id, i) => { - assertUuid(id, `queueIds[${i}]`); - params.append("ids", id); - }); - } - if (name) - params.append("name", name); - if (nameContains) - params.append("name_contains", nameContains); - params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); - let count = 0; - for await (const queues of this._getPaginated("/annotation-queues", params)) { - yield* queues; - count++; - if (limit !== undefined && count >= limit) - break; - } - } - /** - * Create an annotation queue on the LangSmith API. - * @param options - The options for creating an annotation queue - * @param options.name - The name of the annotation queue - * @param options.description - The description of the annotation queue - * @param options.queueId - The ID of the annotation queue - * @returns The created AnnotationQueue object - */ - async createAnnotationQueue(options) { - const { name, description, queueId, rubricInstructions } = options; - const body = { - name, - description, - id: queueId || wrapper_v4(), - rubric_instructions: rubricInstructions, - }; - const serializedBody = JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create annotation queue"); - return res; - }); - return response.json(); - } - /** - * Read an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to read - * @returns The AnnotationQueueWithDetails object - */ - async readAnnotationQueue(queueId) { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read annotation queue"); - return res; - }); - return response.json(); - } - /** - * Update an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to update - * @param options - The options for updating the annotation queue - * @param options.name - The new name for the annotation queue - * @param options.description - The new description for the annotation queue - */ - async updateAnnotationQueue(queueId, options) { - const { name, description, rubricInstructions } = options; - const body = JSON.stringify({ - name, - description, - rubric_instructions: rubricInstructions, - }); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update annotation queue", true); - return res; - }); - } - /** - * Delete an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to delete - */ - async deleteAnnotationQueue(queueId) { - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete annotation queue", true); - return res; - }); - } - /** - * Add runs to an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue - * @param runIds - The IDs of the runs to be added to the annotation queue - */ - async addRunsToAnnotationQueue(queueId, runIds) { - const body = JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "add runs to annotation queue", true); - return res; - }); - } - /** - * Get a run from an annotation queue at the specified index. - * @param queueId - The ID of the annotation queue - * @param index - The index of the run to retrieve - * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object - * @throws {Error} If the run is not found at the given index or for other API-related errors - */ - async getRunFromAnnotationQueue(queueId, index) { - const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${baseUrl}/${index}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get run from annotation queue"); - return res; - }); - return response.json(); - } - /** - * Delete a run from an an annotation queue. - * @param queueId - The ID of the annotation queue to delete the run from - * @param queueRunId - The ID of the run to delete from the annotation queue - */ - async deleteRunFromAnnotationQueue(queueId, queueRunId) { - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete run from annotation queue", true); - return res; - }); - } - /** - * Get the size of an annotation queue. - * @param queueId - The ID of the annotation queue - */ - async getSizeFromAnnotationQueue(queueId) { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get size from annotation queue"); - return res; - }); - return response.json(); - } - async _currentTenantIsOwner(owner) { - const settings = await this._getSettings(); - return owner == "-" || settings.tenant_handle === owner; - } - async _ownerConflictError(action, owner) { - const settings = await this._getSettings(); - return new Error(`Cannot ${action} for another tenant.\n - Current tenant: ${settings.tenant_handle}\n - Requested tenant: ${owner}`); - } - async _getLatestCommitHash(promptOwnerAndName) { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get latest commit hash"); - return res; - }); - const json = await response.json(); - if (json.commits.length === 0) { - return undefined; - } - return json.commits[0].commit_hash; - } - async _likeOrUnlikePrompt(promptIdentifier, like) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const body = JSON.stringify({ like: like }); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/likes/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, `${like ? "like" : "unlike"} prompt`); - return res; - }); - return response.json(); - } - async _getPromptUrl(promptIdentifier) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - if (commitHash !== "latest") { - return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; - } - else { - return `${this.getHostUrl()}/hub/${owner}/${promptName}`; - } - } - else { - const settings = await this._getSettings(); - if (commitHash !== "latest") { - return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; - } - else { - return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; - } - } - } - async promptExists(promptIdentifier) { - const prompt = await this.getPrompt(promptIdentifier); - return !!prompt; - } - async likePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, true); - } - async unlikePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, false); - } - async *listCommits(promptOwnerAndName) { - for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { - yield* commits; - } - } - async *listPrompts(options) { - const params = new URLSearchParams(); - params.append("sort_field", options?.sortField ?? "updated_at"); - params.append("sort_direction", "desc"); - params.append("is_archived", (!!options?.isArchived).toString()); - if (options?.isPublic !== undefined) { - params.append("is_public", options.isPublic.toString()); - } - if (options?.query) { - params.append("query", options.query); - } - for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { - yield* prompts; - } - } - async getPrompt(promptIdentifier) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - if (res?.status === 404) { - return null; - } - await raiseForStatus(res, "get prompt"); - return res; - }); - const result = await response?.json(); - if (result?.repo) { - return result.repo; - } - else { - return null; - } - } - async createPrompt(promptIdentifier, options) { - const settings = await this._getSettings(); - if (options?.isPublic && !settings.tenant_handle) { - throw new Error(`Cannot create a public prompt without first\n - creating a LangChain Hub handle. - You can add a handle by creating a public prompt at:\n - https://smith.langchain.com/prompts`); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("create a prompt", owner); - } - const data = { - repo_handle: promptName, - ...(options?.description && { description: options.description }), - ...(options?.readme && { readme: options.readme }), - ...(options?.tags && { tags: options.tags }), - is_public: !!options?.isPublic, - }; - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create prompt"); - return res; - }); - const { repo } = await response.json(); - return repo; - } - async createCommit(promptIdentifier, object, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash - ? await this._getLatestCommitHash(`${owner}/${promptName}`) - : options?.parentCommitHash; - const payload = { - manifest: JSON.parse(JSON.stringify(object)), - parent_commit: resolvedParentCommitHash, - }; - const body = JSON.stringify(payload); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create commit"); - return res; - }); - const result = await response.json(); - return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); - } - /** - * Update examples with attachments using multipart form data. - * @param updates List of ExampleUpdateWithAttachments objects to upsert - * @returns Promise with the update response - */ - async updateExamplesMultipart(datasetId, updates = []) { - return this._updateExamplesMultipart(datasetId, updates); - } - async _updateExamplesMultipart(datasetId, updates = []) { - if (!(await this._getDatasetExamplesMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); - } - const formData = new FormData(); - for (const example of updates) { - const exampleId = example.id; - // Prepare the main example body - const exampleBody = { - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - if (example.attachments_operations) { - const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); - const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { - type: "application/json", - }); - formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); - } - } - const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { - method: "PATCH", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: formData, - }); - await raiseForStatus(res, "update examples"); - return res; - }); - return response.json(); - } - /** - * Upload examples with attachments using multipart form data. - * @param uploads List of ExampleUploadWithAttachments objects to upload - * @returns Promise with the upload response - * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead - */ - async uploadExamplesMultipart(datasetId, uploads = []) { - return this._uploadExamplesMultipart(datasetId, uploads); - } - async _uploadExamplesMultipart(datasetId, uploads = []) { - if (!(await this._getDatasetExamplesMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); - } - const formData = new FormData(); - for (const example of uploads) { - const exampleId = (example.id ?? wrapper_v4()).toString(); - // Prepare the main example body - const exampleBody = { - created_at: example.created_at, - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - ...(example.source_run_id && { source_run_id: example.source_run_id }), - ...(example.use_source_run_io && { - use_source_run_io: example.use_source_run_io, - }), - ...(example.use_source_run_attachments && { - use_source_run_attachments: example.use_source_run_attachments, - }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { - method: "POST", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: formData, - }); - await raiseForStatus(res, "upload examples"); - return res; - }); - return response.json(); - } - async updatePrompt(promptIdentifier, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("update a prompt", owner); - } - const payload = {}; - if (options?.description !== undefined) - payload.description = options.description; - if (options?.readme !== undefined) - payload.readme = options.readme; - if (options?.tags !== undefined) - payload.tags = options.tags; - if (options?.isPublic !== undefined) - payload.is_public = options.isPublic; - if (options?.isArchived !== undefined) - payload.is_archived = options.isArchived; - // Check if payload is empty - if (Object.keys(payload).length === 0) { - throw new Error("No valid update options provided"); - } - const body = JSON.stringify(payload); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "PATCH", - headers: { - ...this.headers, - "Content-Type": "application/json", - }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update prompt"); - return res; - }); - return response.json(); - } - async deletePrompt(promptIdentifier) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("delete a prompt", owner); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete prompt"); - return res; - }); - return response.json(); - } - async pullPromptCommit(promptIdentifier, options) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "pull prompt commit"); - return res; - }); - const result = await response.json(); - return { - owner, - repo: promptName, - commit_hash: result.commit_hash, - manifest: result.manifest, - examples: result.examples, - }; - } - /** - * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. - * Using this method directly returns the JSON string of the prompt rather than a LangChain object. - * @private - */ - async _pullPrompt(promptIdentifier, options) { - const promptObject = await this.pullPromptCommit(promptIdentifier, { - includeModel: options?.includeModel, - }); - const prompt = JSON.stringify(promptObject.manifest); - return prompt; - } - async pushPrompt(promptIdentifier, options) { - // Create or update prompt metadata - if (await this.promptExists(promptIdentifier)) { - if (options && Object.keys(options).some((key) => key !== "object")) { - await this.updatePrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - } - else { - await this.createPrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - if (!options?.object) { - return await this._getPromptUrl(promptIdentifier); - } - // Create a commit with the new manifest - const url = await this.createCommit(promptIdentifier, options?.object, { - parentCommitHash: options?.parentCommitHash, - }); - return url; - } - /** - * Clone a public dataset to your own langsmith tenant. - * This operation is idempotent. If you already have a dataset with the given name, - * this function will do nothing. - - * @param {string} tokenOrUrl The token of the public dataset to clone. - * @param {Object} [options] Additional options for cloning the dataset. - * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. - * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. - * @returns {Promise} - */ - async clonePublicDataset(tokenOrUrl, options = {}) { - const { sourceApiUrl = this.apiUrl, datasetName } = options; - const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); - const sourceClient = new Client({ - apiUrl: parsedApiUrl, - // Placeholder API key not needed anymore in most cases, but - // some private deployments may have API key-based rate limiting - // that would cause this to fail if we provide no value. - apiKey: "placeholder", - }); - const ds = await sourceClient.readSharedDataset(tokenUuid); - const finalDatasetName = datasetName || ds.name; - try { - if (await this.hasDataset({ datasetId: finalDatasetName })) { - console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); - return; - } - } - catch (_) { - // `.hasDataset` will throw an error if the dataset does not exist. - // no-op in that case - } - // Fetch examples first, then create the dataset - const examples = await sourceClient.listSharedExamples(tokenUuid); - const dataset = await this.createDataset(finalDatasetName, { - description: ds.description, - dataType: ds.data_type || "kv", - inputsSchema: ds.inputs_schema_definition ?? undefined, - outputsSchema: ds.outputs_schema_definition ?? undefined, - }); - try { - await this.createExamples({ - inputs: examples.map((e) => e.inputs), - outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), - datasetId: dataset.id, - }); - } - catch (e) { - console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + - "You should delete it manually."); - throw e; - } - } - parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { - // Try parsing as UUID - try { - assertUuid(urlOrToken); // Will throw if it's not a UUID. - return [apiUrl, urlOrToken]; - } - catch (_) { - // no-op if it's not a uuid - } - // Parse as URL - try { - const parsedUrl = new URL(urlOrToken); - const pathParts = parsedUrl.pathname - .split("/") - .filter((part) => part !== ""); - if (pathParts.length >= numParts) { - const tokenUuid = pathParts[pathParts.length - numParts]; - return [apiUrl, tokenUuid]; - } - else { - throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); - } - } - catch (error) { - throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); - } - } - /** - * Awaits all pending trace batches. Useful for environments where - * you need to be sure that all tracing requests finish before execution ends, - * such as serverless environments. - * - * @example - * ``` - * import { Client } from "langsmith"; - * - * const client = new Client(); - * - * try { - * // Tracing happens here - * ... - * } finally { - * await client.awaitPendingTraceBatches(); - * } - * ``` - * - * @returns A promise that resolves once all currently pending traces have sent. - */ - async awaitPendingTraceBatches() { - if (this.manualFlushMode) { - console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); - return Promise.resolve(); - } - await Promise.all([ - ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), - this.batchIngestCaller.queue.onIdle(), - ]); - if (this.langSmithToOTELTranslator !== undefined) { - await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); - } - } -} -function isExampleCreate(input) { - return "dataset_id" in input || "dataset_name" in input; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js - -const isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; - } - const envVars = ["TRACING_V2", "TRACING"]; - return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js -const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js - - - - - - - - - -function stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { - // Date only has millisecond precision, so we use the microseconds to break - // possible ties, avoiding incorrect run order - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - const microsecondPrecisionDatestring = `${new Date(epoch) - .toISOString() - .slice(0, -1)}${paddedOrder}Z`; - return { - dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, - microsecondPrecisionDatestring, - }; -} -/** - * Baggage header information - */ -class Baggage { - constructor(metadata, tags, project_name, replicas) { - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "replicas", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.metadata = metadata; - this.tags = tags; - this.project_name = project_name; - this.replicas = replicas; - } - static fromHeader(value) { - const items = value.split(","); - let metadata = {}; - let tags = []; - let project_name; - let replicas; - for (const item of items) { - const [key, uriValue] = item.split("="); - const value = decodeURIComponent(uriValue); - if (key === "langsmith-metadata") { - metadata = JSON.parse(value); - } - else if (key === "langsmith-tags") { - tags = value.split(","); - } - else if (key === "langsmith-project") { - project_name = value; - } - else if (key === "langsmith-replicas") { - replicas = JSON.parse(value); - } - } - return new Baggage(metadata, tags, project_name, replicas); - } - toHeader() { - const items = []; - if (this.metadata && Object.keys(this.metadata).length > 0) { - items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); - } - if (this.tags && this.tags.length > 0) { - items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); - } - if (this.project_name) { - items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); - } - return items.join(","); - } -} -class run_trees_RunTree { - constructor(originalConfig) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "end_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "extra", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "serialized", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "reference_example_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "events", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "trace_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "dotted_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingEnabled", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Attachments associated with the run. - * Each entry is a tuple of [mime_type, bytes] - */ - Object.defineProperty(this, "attachments", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Projects to replicate this run to with optional updates. - */ - Object.defineProperty(this, "replicas", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_serialized_start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // If you pass in a run tree directly, return a shallow clone - if (run_trees_isRunTree(originalConfig)) { - Object.assign(this, { ...originalConfig }); - return; - } - const defaultConfig = run_trees_RunTree.getDefaultConfig(); - const { metadata, ...config } = originalConfig; - const client = config.client ?? run_trees_RunTree.getSharedClient(); - const dedupedMetadata = { - ...metadata, - ...config?.extra?.metadata, - }; - config.extra = { ...config.extra, metadata: dedupedMetadata }; - if ("id" in config && config.id == null) { - delete config.id; - } - Object.assign(this, { ...defaultConfig, ...config, client }); - if (!this.trace_id) { - if (this.parent_run) { - this.trace_id = this.parent_run.trace_id ?? this.id; - } - else { - this.trace_id = this.id; - } - } - this.replicas = _ensureWriteReplicas(this.replicas); - this.execution_order ??= 1; - this.child_execution_order ??= 1; - if (!this.dotted_order) { - const { dottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); - if (this.parent_run) { - this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; - } - else { - this.dotted_order = dottedOrder; - } - this._serialized_start_time = microsecondPrecisionDatestring; - } - } - set metadata(metadata) { - this.extra = { - ...this.extra, - metadata: { - ...this.extra?.metadata, - ...metadata, - }, - }; - } - get metadata() { - return this.extra?.metadata; - } - static getDefaultConfig() { - return { - id: wrapper_v4(), - run_type: "chain", - project_name: getDefaultProjectName(), - child_runs: [], - api_url: env_getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: env_getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time: Date.now(), - serialized: {}, - inputs: {}, - extra: {}, - }; - } - static getSharedClient() { - if (!run_trees_RunTree.sharedClient) { - run_trees_RunTree.sharedClient = new Client(); - } - return run_trees_RunTree.sharedClient; - } - createChild(config) { - const child_execution_order = this.child_execution_order + 1; - const child = new run_trees_RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - replicas: this.replicas, - client: this.client, - tracingEnabled: this.tracingEnabled, - execution_order: child_execution_order, - child_execution_order: child_execution_order, - }); - // Copy context vars over into the new run tree. - if (_LC_CONTEXT_VARIABLES_KEY in this) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - child[_LC_CONTEXT_VARIABLES_KEY] = - this[_LC_CONTEXT_VARIABLES_KEY]; - } - const LC_CHILD = Symbol.for("lc:child_config"); - const presentConfig = config.extra?.[LC_CHILD] ?? - this.extra[LC_CHILD]; - // tracing for LangChain is defined by the _parentRunId and runMap of the tracer - if (isRunnableConfigLike(presentConfig)) { - const newConfig = { ...presentConfig }; - const callbacks = isCallbackManagerLike(newConfig.callbacks) - ? newConfig.callbacks.copy?.() - : undefined; - if (callbacks) { - // update the parent run id - Object.assign(callbacks, { _parentRunId: child.id }); - // only populate if we're in a newer LC.JS version - callbacks.handlers - ?.find(isLangChainTracerLike) - ?.updateFromRunTree?.(child); - newConfig.callbacks = callbacks; - } - child.extra[LC_CHILD] = newConfig; - } - // propagate child_execution_order upwards - const visited = new Set(); - let current = this; - while (current != null && !visited.has(current.id)) { - visited.add(current.id); - current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); - current = current.parent_run; - } - this.child_runs.push(child); - return child; - } - async end(outputs, error, endTime = Date.now(), metadata) { - this.outputs = this.outputs ?? outputs; - this.error = this.error ?? error; - this.end_time = this.end_time ?? endTime; - if (metadata && Object.keys(metadata).length > 0) { - this.extra = this.extra - ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } - : { metadata }; - } - } - _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - // Avoid overwriting the runtime environment if it's already set - if (runExtra?.runtime?.library === undefined) { - if (!runExtra.runtime) { - runExtra.runtime = {}; - } - if (runtimeEnv) { - for (const [k, v] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k]) { - runExtra.runtime[k] = v; - } - } - } - } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); - parent_run_id = undefined; - } - else { - parent_run_id = run.parent_run?.id ?? run.parent_run_id; - child_runs = []; - } - return { - id: run.id, - name: run.name, - start_time: run._serialized_start_time ?? run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs: child_runs, - parent_run_id: parent_run_id, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - tags: run.tags, - attachments: run.attachments, - events: run.events, - }; - } - _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) { - const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); - if (projectName === this.project_name) { - return baseRun; - } - // Create a deterministic UUID mapping for this project - const createRemappedId = (originalId) => { - return wrapper_v5(`${originalId}:${projectName}`, wrapper_v5.DNS); - }; - // Remap the current run's ID - const newId = createRemappedId(baseRun.id); - const newTraceId = baseRun.trace_id - ? createRemappedId(baseRun.trace_id) - : undefined; - const newParentRunId = baseRun.parent_run_id - ? createRemappedId(baseRun.parent_run_id) - : undefined; - let newDottedOrder; - if (baseRun.dotted_order) { - const segments = _parseDottedOrder(baseRun.dotted_order); - const rebuilt = []; - // Process all segments except the last one - for (let i = 0; i < segments.length - 1; i++) { - const [timestamp, segmentId] = segments[i]; - const remappedId = createRemappedId(segmentId); - rebuilt.push(timestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + - remappedId); - } - // Process the last segment with the new run ID - const [lastTimestamp] = segments[segments.length - 1]; - rebuilt.push(lastTimestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + - newId); - newDottedOrder = rebuilt.join("."); - } - else { - newDottedOrder = undefined; - } - const remappedRun = { - ...baseRun, - id: newId, - trace_id: newTraceId, - parent_run_id: newParentRunId, - dotted_order: newDottedOrder, - session_name: projectName, - }; - return remappedRun; - } - async postRun(excludeChildRuns = true) { - try { - const runtimeEnv = env_getRuntimeEnvironment(); - if (this.replicas && this.replicas.length > 0) { - for (const { projectName, apiKey, apiUrl, workspaceId } of this - .replicas) { - const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true); - await this.client.createRun(runCreate, { - apiKey, - apiUrl, - workspaceId, - }); - } - } - else { - const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); - await this.client.createRun(runCreate); - } - if (!excludeChildRuns) { - warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); - } - } - } - catch (error) { - console.error(`Error in postRun for run ${this.id}:`, error); - } - } - async patchRun(options) { - if (this.replicas && this.replicas.length > 0) { - for (const { projectName, apiKey, apiUrl, workspaceId, updates } of this - .replicas) { - const runData = this._remapForProject(projectName ?? this.project_name); - const updatePayload = { - id: runData.id, - outputs: runData.outputs, - error: runData.error, - parent_run_id: runData.parent_run_id, - session_name: runData.session_name, - reference_example_id: runData.reference_example_id, - end_time: runData.end_time, - dotted_order: runData.dotted_order, - trace_id: runData.trace_id, - events: runData.events, - tags: runData.tags, - extra: runData.extra, - attachments: this.attachments, - ...updates, - }; - // Important that inputs is not a key in the run update - // if excluded because it will overwrite the run create if the - // two operations are merged during batching - if (!options?.excludeInputs) { - updatePayload.inputs = runData.inputs; - } - await this.client.updateRun(runData.id, updatePayload, { - apiKey, - apiUrl, - workspaceId, - }); - } - } - else { - try { - const runUpdate = { - end_time: this.end_time, - error: this.error, - outputs: this.outputs, - parent_run_id: this.parent_run?.id ?? this.parent_run_id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, - dotted_order: this.dotted_order, - trace_id: this.trace_id, - tags: this.tags, - attachments: this.attachments, - session_name: this.project_name, - }; - // Important that inputs is not a key in the run update - // if excluded because it will overwrite the run create if the - // two operations are merged during batching - if (!options?.excludeInputs) { - runUpdate.inputs = this.inputs; - } - await this.client.updateRun(this.id, runUpdate); - } - catch (error) { - console.error(`Error in patchRun for run ${this.id}`, error); - } - } - } - toJSON() { - return this._convertToCreate(this, undefined, false); - } - /** - * Add an event to the run tree. - * @param event - A single event or string to add - */ - addEvent(event) { - if (!this.events) { - this.events = []; - } - if (typeof event === "string") { - this.events.push({ - name: "event", - time: new Date().toISOString(), - message: event, - }); - } - else { - this.events.push({ - ...event, - time: event.time ?? new Date().toISOString(), - }); - } - } - static fromRunnableConfig(parentConfig, props) { - // We only handle the callback manager case for now - const callbackManager = parentConfig?.callbacks; - let parentRun; - let projectName; - let client; - let tracingEnabled = isTracingEnabled(); - if (callbackManager) { - const parentRunId = callbackManager?.getParentRunId?.() ?? ""; - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); - parentRun = langChainTracer?.getRun?.(parentRunId); - projectName = langChainTracer?.projectName; - client = langChainTracer?.client; - tracingEnabled = tracingEnabled || !!langChainTracer; - } - if (!parentRun) { - return new run_trees_RunTree({ - ...props, - client, - tracingEnabled, - project_name: projectName, - }); - } - const parentRunTree = new run_trees_RunTree({ - name: parentRun.name, - id: parentRun.id, - trace_id: parentRun.trace_id, - dotted_order: parentRun.dotted_order, - client, - tracingEnabled, - project_name: projectName, - tags: [ - ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), - ], - extra: { - metadata: { - ...parentRun?.extra?.metadata, - ...parentConfig?.metadata, - }, - }, - }); - return parentRunTree.createChild(props); - } - static fromDottedOrder(dottedOrder) { - return this.fromHeaders({ "langsmith-trace": dottedOrder }); - } - static fromHeaders(headers, inheritArgs) { - const rawHeaders = "get" in headers && typeof headers.get === "function" - ? { - "langsmith-trace": headers.get("langsmith-trace"), - baggage: headers.get("baggage"), - } - : headers; - const headerTrace = rawHeaders["langsmith-trace"]; - if (!headerTrace || typeof headerTrace !== "string") - return undefined; - const parentDottedOrder = headerTrace.trim(); - const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { - const [strTime, uuid] = part.split("Z"); - return { strTime, time: Date.parse(strTime + "Z"), uuid }; - }); - const traceId = parsedDottedOrder[0].uuid; - const config = { - ...inheritArgs, - name: inheritArgs?.["name"] ?? "parent", - run_type: inheritArgs?.["run_type"] ?? "chain", - start_time: inheritArgs?.["start_time"] ?? Date.now(), - id: parsedDottedOrder.at(-1)?.uuid, - trace_id: traceId, - dotted_order: parentDottedOrder, - }; - if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { - const baggage = Baggage.fromHeader(rawHeaders["baggage"]); - config.metadata = baggage.metadata; - config.tags = baggage.tags; - config.project_name = baggage.project_name; - config.replicas = baggage.replicas; - } - return new run_trees_RunTree(config); - } - toHeaders(headers) { - const result = { - "langsmith-trace": this.dotted_order, - baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader(), - }; - if (headers) { - for (const [key, value] of Object.entries(result)) { - headers.set(key, value); - } - } - return result; - } -} -Object.defineProperty(run_trees_RunTree, "sharedClient", { - enumerable: true, - configurable: true, - writable: true, - value: null -}); -function run_trees_isRunTree(x) { - return (x != null && - typeof x.createChild === "function" && - typeof x.postRun === "function"); -} -function isLangChainTracerLike(x) { - return (typeof x === "object" && - x != null && - typeof x.name === "string" && - x.name === "langchain_tracer"); -} -function containsLangChainTracerLike(x) { - return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); -} -function isCallbackManagerLike(x) { - return (typeof x === "object" && - x != null && - Array.isArray(x.handlers)); -} -function isRunnableConfigLike(x) { - // Check that it's an object with a callbacks arg - // that has either a CallbackManagerLike object with a langchain tracer within it - // or an array with a LangChainTracerLike object within it - return (x != null && - typeof x.callbacks === "object" && - // Callback manager with a langchain tracer - (containsLangChainTracerLike(x.callbacks?.handlers) || - // Or it's an array with a LangChainTracerLike object within it - containsLangChainTracerLike(x.callbacks))); -} -function _parseDottedOrder(dottedOrder) { - const parts = dottedOrder.split("."); - return parts.map((part) => { - const timestampStr = part.slice(0, -36); - const uuidStr = part.slice(-36); - // Parse timestamp: "%Y%m%dT%H%M%S%fZ" format - // Example: "20231215T143045123456Z" - const year = parseInt(timestampStr.slice(0, 4)); - const month = parseInt(timestampStr.slice(4, 6)) - 1; // JS months are 0-indexed - const day = parseInt(timestampStr.slice(6, 8)); - const hour = parseInt(timestampStr.slice(9, 11)); - const minute = parseInt(timestampStr.slice(11, 13)); - const second = parseInt(timestampStr.slice(13, 15)); - const microsecond = parseInt(timestampStr.slice(15, 21)); - const timestamp = new Date(year, month, day, hour, minute, second, microsecond / 1000); - return [timestamp, uuidStr]; - }); -} -function _getWriteReplicasFromEnv() { - const envVar = env_getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); - if (!envVar) - return []; - try { - const parsed = JSON.parse(envVar); - if (Array.isArray(parsed)) { - const replicas = []; - for (const item of parsed) { - if (typeof item !== "object" || item === null) { - console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: ` + - `expected object, got ${typeof item}`); - continue; - } - if (typeof item.api_url !== "string") { - console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: ` + - `expected string, got ${typeof item.api_url}`); - continue; - } - if (typeof item.api_key !== "string") { - console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: ` + - `expected string, got ${typeof item.api_key}`); - continue; - } - replicas.push({ - apiUrl: item.api_url.replace(/\/$/, ""), - apiKey: item.api_key, - }); - } - return replicas; - } - else if (typeof parsed === "object" && parsed !== null) { - _checkEndpointEnvUnset(parsed); - const replicas = []; - for (const [url, key] of Object.entries(parsed)) { - const cleanUrl = url.replace(/\/$/, ""); - if (typeof key === "string") { - replicas.push({ - apiUrl: cleanUrl, - apiKey: key, - }); - } - else { - console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: ` + - `expected string, got ${typeof key}`); - continue; - } - } - return replicas; - } - else { - console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + - `objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); - return []; - } - } - catch (e) { - if (isConflictingEndpointsError(e)) { - throw e; - } - console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + - "objects with api_url and api_key properties, or object mapping url->apiKey"); - return []; - } -} -function _ensureWriteReplicas(replicas) { - // If null -> fetch from env - if (replicas) { - return replicas.map((replica) => { - if (Array.isArray(replica)) { - return { - projectName: replica[0], - updates: replica[1], - }; - } - return replica; - }); - } - return _getWriteReplicasFromEnv(); -} -function _checkEndpointEnvUnset(parsed) { - if (Object.keys(parsed).length > 0 && - getLangSmithEnvironmentVariable("ENDPOINT")) { - throw new ConflictingEndpointsError(); - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js - - - - - -//#region src/tracers/base.ts -var base_base_exports = {}; -__export(base_base_exports, { - BaseTracer: () => BaseTracer, - isBaseTracer: () => isBaseTracer -}); -const convertRunTreeToRun = (runTree) => { - if (!runTree) return void 0; - runTree.events = runTree.events ?? []; - runTree.child_runs = runTree.child_runs ?? []; - return runTree; -}; -function convertRunToRunTree(run, parentRun) { - if (!run) return void 0; - return new run_trees_RunTree({ - ...run, - start_time: run._serialized_start_time ?? run.start_time, - parent_run: convertRunToRunTree(parentRun), - child_runs: run.child_runs.map((r) => convertRunToRunTree(r)).filter((r) => r !== void 0), - extra: { - ...run.extra, - runtime: getRuntimeEnvironment() - }, - tracingEnabled: false - }); -} -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function isBaseTracer(x) { - return typeof x._addRunToRunMap === "function"; -} -var BaseTracer = class extends BaseCallbackHandler { - /** @deprecated Use `runTreeMap` instead. */ - runMap = /* @__PURE__ */ new Map(); - runTreeMap = /* @__PURE__ */ new Map(); - usesRunTreeMap = false; - constructor(_fields) { - super(...arguments); - } - copy() { - return this; - } - getRunById(runId) { - if (runId === void 0) return void 0; - return this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId); - } - stringifyError(error) { - if (error instanceof Error) return error.message + (error?.stack ? `\n\n${error.stack}` : ""); - if (typeof error === "string") return error; - return `${error}`; - } - _addChildRun(parentRun, childRun) { - parentRun.child_runs.push(childRun); - } - _addRunToRunMap(run) { - const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); - const storedRun = { ...run }; - const parentRun = this.getRunById(storedRun.parent_run_id); - if (storedRun.parent_run_id !== void 0) { - if (parentRun) { - this._addChildRun(parentRun, storedRun); - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); - storedRun.trace_id = parentRun.trace_id; - if (parentRun.dotted_order !== void 0) { - storedRun.dotted_order = [parentRun.dotted_order, currentDottedOrder].join("."); - storedRun._serialized_start_time = microsecondPrecisionDatestring; - } - } - } else { - storedRun.trace_id = storedRun.id; - storedRun.dotted_order = currentDottedOrder; - storedRun._serialized_start_time = microsecondPrecisionDatestring; - } - if (this.usesRunTreeMap) { - const runTree = convertRunToRunTree(storedRun, parentRun); - if (runTree !== void 0) this.runTreeMap.set(storedRun.id, runTree); - } else this.runMap.set(storedRun.id, storedRun); - return storedRun; - } - async _endTrace(run) { - const parentRun = run.parent_run_id !== void 0 && this.getRunById(run.parent_run_id); - if (parentRun) parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); - else await this.persistRun(run); - await this.onRunUpdate?.(run); - if (this.usesRunTreeMap) this.runTreeMap.delete(run.id); - else this.runMap.delete(run.id); - } - _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== void 0 && this.getRunById(parentRunId); - if (!parentRun) return 1; - return parentRun.child_execution_order + 1; - } - /** - * Create and add a run to the run map for LLM start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata ? { - ...extraParams, - metadata - } : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { prompts }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; - } - /** - * Create and add a run to the run map for chat model start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata ? { - ...extraParams, - metadata - } : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { messages }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; - } - async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "llm") throw new Error("No LLM run to end."); - run.end_time = Date.now(); - run.outputs = output; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - run.extra = { - ...run.extra, - ...extraParams - }; - await this.onLLMEnd?.(run); - await this._endTrace(run); - return run; - } - async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "llm") throw new Error("No LLM run to end."); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - run.extra = { - ...run.extra, - ...extraParams - }; - await this.onLLMError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for chain start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? chain.id[chain.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: chain, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs, - execution_order, - child_execution_order: execution_order, - run_type: runType ?? "chain", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); - await this.onRunCreate?.(run); - await this.onChainStart?.(run); - return run; - } - async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.getRunById(runId); - if (!run) throw new Error("No chain run to end."); - run.end_time = Date.now(); - run.outputs = _coerceToDict(outputs, "output"); - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, "input"); - await this.onChainEnd?.(run); - await this._endTrace(run); - return run; - } - async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.getRunById(runId); - if (!run) throw new Error("No chain run to end."); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, "input"); - await this.onChainError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for tool start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? tool.id[tool.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: tool, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { input }, - execution_order, - child_execution_order: execution_order, - run_type: "tool", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onToolStart?.(run); - return run; - } - async handleToolEnd(output, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "tool") throw new Error("No tool run to end"); - run.end_time = Date.now(); - run.outputs = { output }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - await this.onToolEnd?.(run); - await this._endTrace(run); - return run; - } - async handleToolError(error, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "tool") throw new Error("No tool run to end"); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - await this.onToolError?.(run); - await this._endTrace(run); - return run; - } - async handleAgentAction(action, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "chain") return; - const agentRun = run; - agentRun.actions = agentRun.actions || []; - agentRun.actions.push(action); - agentRun.events.push({ - name: "agent_action", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { action } - }); - await this.onAgentAction?.(run); - } - async handleAgentEnd(action, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "chain") return; - run.events.push({ - name: "agent_end", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { action } - }); - await this.onAgentEnd?.(run); - } - /** - * Create and add a run to the run map for retriever start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? retriever.id[retriever.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: retriever, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { query }, - execution_order, - child_execution_order: execution_order, - run_type: "retriever", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onRetrieverStart?.(run); - return run; - } - async handleRetrieverEnd(documents, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "retriever") throw new Error("No retriever run to end"); - run.end_time = Date.now(); - run.outputs = { documents }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - await this.onRetrieverEnd?.(run); - await this._endTrace(run); - return run; - } - async handleRetrieverError(error, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "retriever") throw new Error("No retriever run to end"); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - await this.onRetrieverError?.(run); - await this._endTrace(run); - return run; - } - async handleText(text, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "chain") return; - run.events.push({ - name: "text", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { text } - }); - await this.onText?.(run); - } - async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "llm") throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); - run.events.push({ - name: "new_token", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { - token, - idx, - chunk: fields?.chunk - } - }); - await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); - return run; - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/ansi-styles/index.js -var ansi_styles = __nccwpck_require__(2227); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js - - - - -//#region src/tracers/console.ts -var console_exports = {}; -__export(console_exports, { ConsoleCallbackHandler: () => ConsoleCallbackHandler }); -function wrap(style, text) { - return `${style.open}${text}${style.close}`; -} -function tryJsonStringify(obj, fallback) { - try { - return JSON.stringify(obj, null, 2); - } catch { - return fallback; - } -} -function formatKVMapItem(value) { - if (typeof value === "string") return value.trim(); - if (value === null || value === void 0) return value; - return tryJsonStringify(value, value.toString()); -} -function elapsed(run) { - if (!run.end_time) return ""; - const elapsed$1 = run.end_time - run.start_time; - if (elapsed$1 < 1e3) return `${elapsed$1}ms`; - return `${(elapsed$1 / 1e3).toFixed(2)}s`; -} -const { color } = ansi_styles; -/** -* A tracer that logs all events to the console. It extends from the -* `BaseTracer` class and overrides its methods to provide custom logging -* functionality. -* @example -* ```typescript -* -* const llm = new ChatAnthropic({ -* temperature: 0, -* tags: ["example", "callbacks", "constructor"], -* callbacks: [new ConsoleCallbackHandler()], -* }); -* -* ``` -*/ -var ConsoleCallbackHandler = class extends BaseTracer { - name = "console_callback_handler"; - /** - * Method used to persist the run. In this case, it simply returns a - * resolved promise as there's no persistence logic. - * @param _run The run to persist. - * @returns A resolved promise. - */ - persistRun(_run) { - return Promise.resolve(); - } - /** - * Method used to get all the parent runs of a given run. - * @param run The run whose parents are to be retrieved. - * @returns An array of parent runs. - */ - getParents(run) { - const parents = []; - let currentRun = run; - while (currentRun.parent_run_id) { - const parent = this.runMap.get(currentRun.parent_run_id); - if (parent) { - parents.push(parent); - currentRun = parent; - } else break; - } - return parents; - } - /** - * Method used to get a string representation of the run's lineage, which - * is used in logging. - * @param run The run whose lineage is to be retrieved. - * @returns A string representation of the run's lineage. - */ - getBreadcrumbs(run) { - const parents = this.getParents(run).reverse(); - const string = [...parents, run].map((parent, i, arr) => { - const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; - return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; - }).join(" > "); - return wrap(color.grey, string); - } - /** - * Method used to log the start of a chain run. - * @param run The chain run that has started. - * @returns void - */ - onChainStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a chain run. - * @param run The chain run that has ended. - * @returns void - */ - onChainEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a chain run. - * @param run The chain run that has errored. - * @returns void - */ - onChainError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of an LLM run. - * @param run The LLM run that has started. - * @returns void - */ - onLLMStart(run) { - const crumbs = this.getBreadcrumbs(run); - const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs; - console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); - } - /** - * Method used to log the end of an LLM run. - * @param run The LLM run that has ended. - * @returns void - */ - onLLMEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); - } - /** - * Method used to log any errors of an LLM run. - * @param run The LLM run that has errored. - * @returns void - */ - onLLMError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a tool run. - * @param run The tool run that has started. - * @returns void - */ - onToolStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); - } - /** - * Method used to log the end of a tool run. - * @param run The tool run that has ended. - * @returns void - */ - onToolEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); - } - /** - * Method used to log any errors of a tool run. - * @param run The tool run that has errored. - * @returns void - */ - onToolError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a retriever run. - * @param run The retriever run that has started. - * @returns void - */ - onRetrieverStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a retriever run. - * @param run The retriever run that has ended. - * @returns void - */ - onRetrieverEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a retriever run. - * @param run The retriever run that has errored. - * @returns void - */ - onRetrieverError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the action selected by the agent. - * @param run The run in which the agent action occurred. - * @returns void - */ - onAgentAction(run) { - const agentRun = run; - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); - } -}; - -//#endregion - -//# sourceMappingURL=console.js.map -;// CONCATENATED MODULE: ./node_modules/langsmith/index.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js - - - -//#region src/singletons/tracer.ts -let client; -const getDefaultLangChainClientSingleton = () => { - if (client === void 0) { - const clientParams = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {}; - client = new Client(clientParams); - } - return client; -}; - -//#endregion - -//# sourceMappingURL=tracer.js.map -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js -class MockAsyncLocalStorage { - getStore() { - return undefined; - } - run(_, callback) { - return callback(); - } -} -const traceable_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const mockAsyncLocalStorage = new MockAsyncLocalStorage(); -class AsyncLocalStorageProvider { - getInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[traceable_TRACING_ALS_KEY] ?? mockAsyncLocalStorage; - } - initializeGlobalInstance(instance) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[traceable_TRACING_ALS_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[traceable_TRACING_ALS_KEY] = instance; - } - } -} -const traceable_AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); -function getCurrentRunTree(permitAbsentRunTree = false) { - const runTree = traceable_AsyncLocalStorageProviderSingleton.getInstance().getStore(); - if (!permitAbsentRunTree && runTree === undefined) { - throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); - } - return runTree; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function withRunTree(runTree, fn) { - const storage = traceable_AsyncLocalStorageProviderSingleton.getInstance(); - return new Promise((resolve, reject) => { - storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); - }); -} -const ROOT = Symbol.for("langsmith:traceable:root"); -function isTraceableFunction(x -// eslint-disable-next-line @typescript-eslint/no-explicit-any -) { - return typeof x === "function" && "langsmith:traceable" in x; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js - - - - - - - -//#region src/tracers/tracer_langchain.ts -var tracer_langchain_exports = {}; -__export(tracer_langchain_exports, { LangChainTracer: () => LangChainTracer }); -var LangChainTracer = class LangChainTracer extends BaseTracer { - name = "langchain_tracer"; - projectName; - exampleId; - client; - replicas; - usesRunTreeMap = true; - constructor(fields = {}) { - super(fields); - const { exampleId, projectName, client, replicas } = fields; - this.projectName = projectName ?? getDefaultProjectName(); - this.replicas = replicas; - this.exampleId = exampleId; - this.client = client ?? getDefaultLangChainClientSingleton(); - const traceableTree = LangChainTracer.getTraceableRunTree(); - if (traceableTree) this.updateFromRunTree(traceableTree); - } - async persistRun(_run) {} - async onRunCreate(run) { - const runTree = this.getRunTreeWithTracingConfig(run.id); - await runTree?.postRun(); - } - async onRunUpdate(run) { - const runTree = this.getRunTreeWithTracingConfig(run.id); - await runTree?.patchRun(); - } - getRun(id) { - return this.runTreeMap.get(id); - } - updateFromRunTree(runTree) { - this.runTreeMap.set(runTree.id, runTree); - let rootRun = runTree; - const visited = /* @__PURE__ */ new Set(); - while (rootRun.parent_run) { - if (visited.has(rootRun.id)) break; - visited.add(rootRun.id); - if (!rootRun.parent_run) break; - rootRun = rootRun.parent_run; - } - visited.clear(); - const queue = [rootRun]; - while (queue.length > 0) { - const current = queue.shift(); - if (!current || visited.has(current.id)) continue; - visited.add(current.id); - this.runTreeMap.set(current.id, current); - if (current.child_runs) queue.push(...current.child_runs); - } - this.client = runTree.client ?? this.client; - this.replicas = runTree.replicas ?? this.replicas; - this.projectName = runTree.project_name ?? this.projectName; - this.exampleId = runTree.reference_example_id ?? this.exampleId; - } - getRunTreeWithTracingConfig(id) { - const runTree = this.runTreeMap.get(id); - if (!runTree) return void 0; - return new run_trees_RunTree({ - ...runTree, - client: this.client, - project_name: this.projectName, - replicas: this.replicas, - reference_example_id: this.exampleId, - tracingEnabled: true - }); - } - static getTraceableRunTree() { - try { - return getCurrentRunTree(true); - } catch { - return void 0; - } - } -}; - -//#endregion - -//# sourceMappingURL=tracer_langchain.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js - - - - -//#region src/singletons/callbacks.ts -let queue; -/** -* Creates a queue using the p-queue library. The queue is configured to -* auto-start and has a concurrency of 1, meaning it will process tasks -* one at a time. -*/ -function createQueue() { - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - return new PQueue({ - autoStart: true, - concurrency: 1 - }); -} -function getQueue() { - if (typeof queue === "undefined") queue = createQueue(); - return queue; -} -/** -* Consume a promise, either adding it to the queue or waiting for it to resolve -* @param promiseFn Promise to consume -* @param wait Whether to wait for the promise to resolve or resolve immediately -*/ -async function consumeCallback(promiseFn, wait) { - if (wait === true) { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); - else await promiseFn(); - } else { - queue = getQueue(); - queue.add(async () => { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); - else await promiseFn(); - }); - } -} -/** -* Waits for all promises in the queue to resolve. If the queue is -* undefined, it immediately resolves a promise. -*/ -async function awaitAllCallbacks() { - const defaultClient = getDefaultLangChainClientSingleton(); - await Promise.allSettled([typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), defaultClient.awaitPendingTraceBatches()]); -} - -//#endregion - -//# sourceMappingURL=callbacks.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js - - - -//#region src/callbacks/promises.ts -var promises_exports = {}; -__export(promises_exports, { - awaitAllCallbacks: () => awaitAllCallbacks, - consumeCallback: () => consumeCallback -}); - -//#endregion - -//# sourceMappingURL=promises.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js - - -//#region src/utils/callbacks.ts -const callbacks_isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== void 0) return tracingEnabled; - const envVars = [ - "LANGSMITH_TRACING_V2", - "LANGCHAIN_TRACING_V2", - "LANGSMITH_TRACING", - "LANGCHAIN_TRACING" - ]; - return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true"); -}; - -//#endregion - -//# sourceMappingURL=callbacks.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js - - - -//#region src/singletons/async_local_storage/context.ts -/** -* Set a context variable. Context variables are scoped to any -* child runnables called by the current runnable, or globally if set outside -* of any runnable. -* -* @remarks -* This function is only supported in environments that support AsyncLocalStorage, -* including Node.js, Deno, and Cloudflare Workers. -* -* @example -* ```ts -* import { RunnableLambda } from "@langchain/core/runnables"; -* import { -* getContextVariable, -* setContextVariable -* } from "@langchain/core/context"; -* -* const nested = RunnableLambda.from(() => { -* // "bar" because it was set by a parent -* console.log(getContextVariable("foo")); -* -* // Override to "baz", but only for child runnables -* setContextVariable("foo", "baz"); -* -* // Now "baz", but only for child runnables -* return getContextVariable("foo"); -* }); -* -* const runnable = RunnableLambda.from(async () => { -* // Set a context variable named "foo" -* setContextVariable("foo", "bar"); -* -* const res = await nested.invoke({}); -* -* // Still "bar" since child changes do not affect parents -* console.log(getContextVariable("foo")); -* -* return res; -* }); -* -* // undefined, because context variable has not been set yet -* console.log(getContextVariable("foo")); -* -* // Final return value is "baz" -* const result = await runnable.invoke({}); -* ``` -* -* @param name The name of the context variable. -* @param value The value to set. -*/ -function setContextVariable(name, value) { - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === void 0) throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); - const runTree = asyncLocalStorageInstance.getStore(); - const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; - contextVars[name] = value; - let newValue = {}; - if (isRunTree(runTree)) newValue = new RunTree(runTree); - newValue[_CONTEXT_VARIABLES_KEY] = contextVars; - asyncLocalStorageInstance.enterWith(newValue); -} -/** -* Get the value of a previously set context variable. Context variables -* are scoped to any child runnables called by the current runnable, -* or globally if set outside of any runnable. -* -* @remarks -* This function is only supported in environments that support AsyncLocalStorage, -* including Node.js, Deno, and Cloudflare Workers. -* -* @example -* ```ts -* import { RunnableLambda } from "@langchain/core/runnables"; -* import { -* getContextVariable, -* setContextVariable -* } from "@langchain/core/context"; -* -* const nested = RunnableLambda.from(() => { -* // "bar" because it was set by a parent -* console.log(getContextVariable("foo")); -* -* // Override to "baz", but only for child runnables -* setContextVariable("foo", "baz"); -* -* // Now "baz", but only for child runnables -* return getContextVariable("foo"); -* }); -* -* const runnable = RunnableLambda.from(async () => { -* // Set a context variable named "foo" -* setContextVariable("foo", "bar"); -* -* const res = await nested.invoke({}); -* -* // Still "bar" since child changes do not affect parents -* console.log(getContextVariable("foo")); -* -* return res; -* }); -* -* // undefined, because context variable has not been set yet -* console.log(getContextVariable("foo")); -* -* // Final return value is "baz" -* const result = await runnable.invoke({}); -* ``` -* -* @param name The name of the context variable. -*/ -function getContextVariable(name) { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === void 0) return void 0; - const runTree = asyncLocalStorageInstance.getStore(); - return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; -} -const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); -const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; -/** -* Register a callback configure hook to automatically add callback handlers to all runs. -* -* There are two ways to use this: -* -* 1. Using a context variable: -* - Set `contextVar` to specify the variable name -* - Use `setContextVariable()` to store your handler instance -* -* 2. Using an environment variable: -* - Set both `envVar` and `handlerClass` -* - The handler will be instantiated when the env var is set to "true". -* -* @example -* ```typescript -* // Method 1: Using context variable -* import { -* registerConfigureHook, -* setContextVariable -* } from "@langchain/core/context"; -* -* const tracer = new MyCallbackHandler(); -* registerConfigureHook({ -* contextVar: "my_tracer", -* }); -* setContextVariable("my_tracer", tracer); -* -* // ...run code here -* -* // Method 2: Using environment variable -* registerConfigureHook({ -* handlerClass: MyCallbackHandler, -* envVar: "MY_TRACER_ENABLED", -* }); -* process.env.MY_TRACER_ENABLED = "true"; -* -* // ...run code here -* ``` -* -* @param config Configuration object for the hook -* @param config.contextVar Name of the context variable containing the handler instance -* @param config.inheritable Whether child runs should inherit this handler -* @param config.handlerClass Optional callback handler class (required if using envVar) -* @param config.envVar Optional environment variable name to control handler activation -*/ -const registerConfigureHook = (config) => { - if (config.envVar && !config.handlerClass) throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); - setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); -}; - -//#endregion - -//# sourceMappingURL=context.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js - - - - - - - - - - - - - -//#region src/callbacks/manager.ts -var manager_exports = {}; -__export(manager_exports, { - BaseCallbackManager: () => BaseCallbackManager, - BaseRunManager: () => BaseRunManager, - CallbackManager: () => CallbackManager, - CallbackManagerForChainRun: () => CallbackManagerForChainRun, - CallbackManagerForLLMRun: () => CallbackManagerForLLMRun, - CallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun, - CallbackManagerForToolRun: () => CallbackManagerForToolRun, - ensureHandler: () => ensureHandler, - parseCallbackConfigArg: () => parseCallbackConfigArg -}); -function parseCallbackConfigArg(arg) { - if (!arg) return {}; - else if (Array.isArray(arg) || "name" in arg) return { callbacks: arg }; - else return arg; -} -/** -* Manage callbacks from different components of LangChain. -*/ -var BaseCallbackManager = class { - setHandler(handler) { - return this.setHandlers([handler]); - } -}; -/** -* Base class for run manager in LangChain. -*/ -var BaseRunManager = class { - constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { - this.runId = runId; - this.handlers = handlers; - this.inheritableHandlers = inheritableHandlers; - this.tags = tags; - this.inheritableTags = inheritableTags; - this.metadata = metadata; - this.inheritableMetadata = inheritableMetadata; - this._parentRunId = _parentRunId; - } - get parentRunId() { - return this._parentRunId; - } - async handleText(text) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -/** -* Manages callbacks for retriever runs. -*/ -var CallbackManagerForRetrieverRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) manager.addTags([tag], false); - return manager; - } - async handleRetrieverEnd(documents) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) try { - await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleRetrieverError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) try { - await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); - } catch (error) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -var CallbackManagerForLLMRun = class extends BaseRunManager { - async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) try { - await handler.handleLLMNewToken?.(token, idx ?? { - prompt: 0, - completion: 0 - }, this.runId, this._parentRunId, this.tags, fields); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) try { - await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); - } catch (err$1) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err$1}`); - if (handler.raiseError) throw err$1; - } - }, handler.awaitHandlers))); - } - async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) try { - await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -var CallbackManagerForChainRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) manager.addTags([tag], false); - return manager; - } - async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) try { - await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); - } catch (err$1) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err$1}`); - if (handler.raiseError) throw err$1; - } - }, handler.awaitHandlers))); - } - async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) try { - await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleAgentAction(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleAgentEnd(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -var CallbackManagerForToolRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) manager.addTags([tag], false); - return manager; - } - async handleToolError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); - } catch (err$1) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err$1}`); - if (handler.raiseError) throw err$1; - } - }, handler.awaitHandlers))); - } - async handleToolEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -/** -* @example -* ```typescript -* const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); -* -* // Example of using LLMChain with OpenAI and a simple prompt -* const chain = new LLMChain({ -* llm: new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0.9 }), -* prompt, -* }); -* -* // Running the chain with a single question -* const result = await chain.call({ -* question: "What is the airspeed velocity of an unladen swallow?", -* }); -* console.log("The answer is:", result); -* ``` -*/ -var CallbackManager = class CallbackManager extends BaseCallbackManager { - handlers = []; - inheritableHandlers = []; - tags = []; - inheritableTags = []; - metadata = {}; - inheritableMetadata = {}; - name = "callback_manager"; - _parentRunId; - constructor(parentRunId, options) { - super(); - this.handlers = options?.handlers ?? this.handlers; - this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; - this.tags = options?.tags ?? this.tags; - this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; - this.metadata = options?.metadata ?? this.metadata; - this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; - this._parentRunId = parentRunId; - } - /** - * Gets the parent run ID, if any. - * - * @returns The parent run ID. - */ - getParentRunId() { - return this._parentRunId; - } - async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - return Promise.all(prompts.map(async (prompt, idx) => { - const runId_ = idx === 0 && runId ? runId : v4(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) return; - if (isBaseTracer(handler)) handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - return Promise.all(messages.map(async (messageGroup, idx) => { - const runId_ = idx === 0 && runId ? runId : v4(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) return; - if (isBaseTracer(handler)) handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - if (handler.handleChatModelStart) await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - else if (handler.handleLLMStart) { - const messageString = getBufferString(messageGroup); - await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChainStart(chain, inputs, runId = v4(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreChain) return; - if (isBaseTracer(handler)) handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); - return consumeCallback(async () => { - try { - await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleToolStart(tool, input, runId = v4(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreAgent) return; - if (isBaseTracer(handler)) handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreRetriever) return; - if (isBaseTracer(handler)) handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleCustomEvent(eventName, data, runId, _tags, _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreCustomEvent) try { - await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - addHandler(handler, inherit = true) { - this.handlers.push(handler); - if (inherit) this.inheritableHandlers.push(handler); - } - removeHandler(handler) { - this.handlers = this.handlers.filter((_handler) => _handler !== handler); - this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); - } - setHandlers(handlers, inherit = true) { - this.handlers = []; - this.inheritableHandlers = []; - for (const handler of handlers) this.addHandler(handler, inherit); - } - addTags(tags, inherit = true) { - this.removeTags(tags); - this.tags.push(...tags); - if (inherit) this.inheritableTags.push(...tags); - } - removeTags(tags) { - this.tags = this.tags.filter((tag) => !tags.includes(tag)); - this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); - } - addMetadata(metadata, inherit = true) { - this.metadata = { - ...this.metadata, - ...metadata - }; - if (inherit) this.inheritableMetadata = { - ...this.inheritableMetadata, - ...metadata - }; - } - removeMetadata(metadata) { - for (const key of Object.keys(metadata)) { - delete this.metadata[key]; - delete this.inheritableMetadata[key]; - } - } - copy(additionalHandlers = [], inherit = true) { - const manager = new CallbackManager(this._parentRunId); - for (const handler of this.handlers) { - const inheritable = this.inheritableHandlers.includes(handler); - manager.addHandler(handler, inheritable); - } - for (const tag of this.tags) { - const inheritable = this.inheritableTags.includes(tag); - manager.addTags([tag], inheritable); - } - for (const key of Object.keys(this.metadata)) { - const inheritable = Object.keys(this.inheritableMetadata).includes(key); - manager.addMetadata({ [key]: this.metadata[key] }, inheritable); - } - for (const handler of additionalHandlers) { - if (manager.handlers.filter((h) => h.name === "console_callback_handler").some((h) => h.name === handler.name)) continue; - manager.addHandler(handler, inherit); - } - return manager; - } - static fromHandlers(handlers) { - class Handler extends BaseCallbackHandler { - name = v4(); - constructor() { - super(); - Object.assign(this, handlers); - } - } - const manager = new this(); - manager.addHandler(new Handler()); - return manager; - } - static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); - } - static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - let callbackManager; - if (inheritableHandlers || localHandlers) { - if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { - callbackManager = new CallbackManager(); - callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); - } else callbackManager = inheritableHandlers; - callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); - } - const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || options?.verbose; - const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || callbacks_isTracingEnabled(); - const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); - if (verboseEnabled || tracingEnabled) { - if (!callbackManager) callbackManager = new CallbackManager(); - if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { - const consoleHandler = new ConsoleCallbackHandler(); - callbackManager.addHandler(consoleHandler, true); - } - if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { - if (tracingV2Enabled) { - const tracerV2 = new LangChainTracer(); - callbackManager.addHandler(tracerV2, true); - } - } - if (tracingV2Enabled) { - const implicitRunTree = LangChainTracer.getTraceableRunTree(); - if (implicitRunTree && callbackManager._parentRunId === void 0) { - callbackManager._parentRunId = implicitRunTree.id; - const tracerV2 = callbackManager.handlers.find((handler) => handler.name === "langchain_tracer"); - tracerV2?.updateFromRunTree(implicitRunTree); - } - } - } - for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { - const createIfNotInContext = envVar && getEnvironmentVariable(envVar) === "true" && handlerClass; - let handler; - const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; - if (contextVarValue && isBaseCallbackHandler(contextVarValue)) handler = contextVarValue; - else if (createIfNotInContext) handler = new handlerClass({}); - if (handler !== void 0) { - if (!callbackManager) callbackManager = new CallbackManager(); - if (!callbackManager.handlers.some((h) => h.name === handler.name)) callbackManager.addHandler(handler, inheritable); - } - } - if (inheritableTags || localTags) { - if (callbackManager) { - callbackManager.addTags(inheritableTags ?? []); - callbackManager.addTags(localTags ?? [], false); - } - } - if (inheritableMetadata || localMetadata) { - if (callbackManager) { - callbackManager.addMetadata(inheritableMetadata ?? {}); - callbackManager.addMetadata(localMetadata ?? {}, false); - } - } - return callbackManager; - } -}; -function ensureHandler(handler) { - if ("name" in handler) return handler; - return BaseCallbackHandler.fromMethods(handler); -} - -//#endregion - -//# sourceMappingURL=manager.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js - - - - -//#region src/singletons/async_local_storage/index.ts -var async_local_storage_MockAsyncLocalStorage = class { - getStore() { - return void 0; - } - run(_store, callback) { - return callback(); - } - enterWith(_store) { - return void 0; - } -}; -const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); -const LC_CHILD_KEY = Symbol.for("lc:child_config"); -var async_local_storage_AsyncLocalStorageProvider = class { - getInstance() { - return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; - } - getRunnableConfig() { - const storage = this.getInstance(); - return storage.getStore()?.extra?.[LC_CHILD_KEY]; - } - runWithConfig(config, callback, avoidCreatingRootRunTree) { - const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); - const storage = this.getInstance(); - const previousValue = storage.getStore(); - const parentRunId = callbackManager?.getParentRunId(); - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); - let runTree; - if (langChainTracer && parentRunId) runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); - else if (!avoidCreatingRootRunTree) runTree = new run_trees_RunTree({ - name: "", - tracingEnabled: false - }); - if (runTree) runTree.extra = { - ...runTree.extra, - [LC_CHILD_KEY]: config - }; - if (previousValue !== void 0 && previousValue[globals_CONTEXT_VARIABLES_KEY] !== void 0) { - if (runTree === void 0) runTree = {}; - runTree[globals_CONTEXT_VARIABLES_KEY] = previousValue[globals_CONTEXT_VARIABLES_KEY]; - } - return storage.run(runTree, callback); - } - initializeGlobalInstance(instance) { - if (globals_getGlobalAsyncLocalStorageInstance() === void 0) setGlobalAsyncLocalStorageInstance(instance); - } -}; -const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js - - - - -//#region src/singletons/index.ts -var singletons_exports = {}; -__export(singletons_exports, { - AsyncLocalStorageProviderSingleton: () => async_local_storage_AsyncLocalStorageProviderSingleton, - MockAsyncLocalStorage: () => async_local_storage_MockAsyncLocalStorage, - _CONTEXT_VARIABLES_KEY: () => globals_CONTEXT_VARIABLES_KEY -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: external "node:async_hooks" -const external_node_async_hooks_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks"); -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/setup/async_local_storage.js - - - -//#region src/setup/async_local_storage.ts -function initializeAsyncLocalStorageSingleton() { - async_local_storage_AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new external_node_async_hooks_namespaceObject.AsyncLocalStorage()); -} - -//#endregion - -//# sourceMappingURL=async_local_storage.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/errors.js -//#region src/errors.ts -/** @category Errors */ -var BaseLangGraphError = class extends Error { - lc_error_code; - constructor(message, fields) { - let finalMessage = message ?? ""; - if (fields?.lc_error_code) finalMessage = `${finalMessage}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\n`; - super(finalMessage); - this.lc_error_code = fields?.lc_error_code; - } -}; -var GraphBubbleUp = class extends BaseLangGraphError { - get is_bubble_up() { - return true; - } -}; -var GraphRecursionError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "GraphRecursionError"; - } - static get unminifiable_name() { - return "GraphRecursionError"; - } -}; -var GraphValueError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "GraphValueError"; - } - static get unminifiable_name() { - return "GraphValueError"; - } -}; -var GraphInterrupt = class extends GraphBubbleUp { - interrupts; - constructor(interrupts, fields) { - super(JSON.stringify(interrupts, null, 2), fields); - this.name = "GraphInterrupt"; - this.interrupts = interrupts ?? []; - } - static get unminifiable_name() { - return "GraphInterrupt"; - } -}; -/** Raised by a node to interrupt execution. */ -var NodeInterrupt = class extends GraphInterrupt { - constructor(message, fields) { - super([{ value: message }], fields); - this.name = "NodeInterrupt"; - } - static get unminifiable_name() { - return "NodeInterrupt"; - } -}; -var ParentCommand = class extends GraphBubbleUp { - command; - constructor(command) { - super(); - this.name = "ParentCommand"; - this.command = command; - } - static get unminifiable_name() { - return "ParentCommand"; - } -}; -function isParentCommand(e) { - return e !== void 0 && e.name === ParentCommand.unminifiable_name; -} -function isGraphBubbleUp(e) { - return e !== void 0 && e.is_bubble_up === true; -} -function isGraphInterrupt(e) { - return e !== void 0 && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name); -} -var EmptyInputError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyInputError"; - } - static get unminifiable_name() { - return "EmptyInputError"; - } -}; -var EmptyChannelError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyChannelError"; - } - static get unminifiable_name() { - return "EmptyChannelError"; - } -}; -var InvalidUpdateError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "InvalidUpdateError"; - } - static get unminifiable_name() { - return "InvalidUpdateError"; - } -}; -/** -* @deprecated This exception type is no longer thrown. -*/ -var MultipleSubgraphsError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "MultipleSubgraphError"; - } - static get unminifiable_name() { - return "MultipleSubgraphError"; - } -}; -var UnreachableNodeError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "UnreachableNodeError"; - } - static get unminifiable_name() { - return "UnreachableNodeError"; - } -}; -/** -* Exception raised when an error occurs in the remote graph. -*/ -var RemoteException = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "RemoteException"; - } - static get unminifiable_name() { - return "RemoteException"; - } -}; -/** -* Used for subgraph detection. -*/ -const getSubgraphsSeenSet = () => { - if (globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] === void 0) globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] = /* @__PURE__ */ new Set(); - return globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]; -}; - -//#endregion - -//# sourceMappingURL=errors.js.map -// EXTERNAL MODULE: ./node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/index.js -var node_modules_uuid_dist = __nccwpck_require__(6061); -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/wrapper.mjs - -const uuid_wrapper_v1 = node_modules_uuid_dist.v1; -const uuid_wrapper_v1ToV6 = node_modules_uuid_dist/* v1ToV6 */.bV; -const uuid_wrapper_v3 = node_modules_uuid_dist.v3; -const uuid_wrapper_v4 = node_modules_uuid_dist.v4; -const uuid_wrapper_v5 = node_modules_uuid_dist.v5; -const uuid_wrapper_v6 = node_modules_uuid_dist.v6; -const uuid_wrapper_v6ToV1 = node_modules_uuid_dist/* v6ToV1 */.JE; -const uuid_wrapper_v7 = node_modules_uuid_dist.v7; -const uuid_wrapper_NIL = node_modules_uuid_dist/* NIL */.wD; -const uuid_wrapper_MAX = node_modules_uuid_dist/* MAX */.Zu; -const uuid_wrapper_version = node_modules_uuid_dist/* version */.rE; -const node_modules_uuid_wrapper_validate = node_modules_uuid_dist/* validate */.tf; -const uuid_wrapper_stringify = node_modules_uuid_dist/* stringify */.As; -const uuid_wrapper_parse = node_modules_uuid_dist/* parse */.qg; - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/id.js - - -//#region src/id.ts -function uuid6(clockseq) { - return uuid_wrapper_v6({ clockseq }); -} -function uuid5(name, namespace) { - const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); - return uuid_wrapper_v5(name, new Uint8Array(namespaceBytes)); -} - -//#endregion - -//# sourceMappingURL=id.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js -//#region src/serde/types.ts -const TASKS = "__pregel_tasks"; -const types_ERROR = "__error__"; -const SCHEDULED = "__scheduled__"; -const INTERRUPT = "__interrupt__"; -const RESUME = "__resume__"; - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js -//#region src/serde/utils/fast-safe-stringify/index.ts -var fast_safe_stringify_LIMIT_REPLACE_NODE = "[...]"; -var fast_safe_stringify_CIRCULAR_REPLACE_NODE = "[Circular]"; -var fast_safe_stringify_arr = []; -var fast_safe_stringify_replacerStack = []; -function fast_safe_stringify_defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER - }; -} -function fast_safe_stringify_stringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") options = fast_safe_stringify_defaultOptions(); - fast_safe_stringify_decirc(obj, "", 0, [], void 0, 0, options); - var res; - try { - if (fast_safe_stringify_replacerStack.length === 0) res = JSON.stringify(obj, replacer, spacer); - else res = JSON.stringify(obj, fast_safe_stringify_replaceGetterValues(replacer), spacer); - } catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } finally { - while (fast_safe_stringify_arr.length !== 0) { - var part = fast_safe_stringify_arr.pop(); - if (part.length === 4) Object.defineProperty(part[0], part[1], part[3]); - else part[0][part[1]] = part[2]; - } - } - return res; -} -function fast_safe_stringify_setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== void 0) if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - fast_safe_stringify_arr.push([ - parent, - k, - val, - propertyDescriptor - ]); - } else fast_safe_stringify_replacerStack.push([ - val, - k, - replace - ]); - else { - parent[k] = replace; - fast_safe_stringify_arr.push([ - parent, - k, - val - ]); - } -} -function fast_safe_stringify_decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) if (stack[i] === val) { - fast_safe_stringify_setReplace(fast_safe_stringify_CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { - fast_safe_stringify_setReplace(fast_safe_stringify_LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { - fast_safe_stringify_setReplace(fast_safe_stringify_LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - if (Array.isArray(val)) for (i = 0; i < val.length; i++) fast_safe_stringify_decirc(val[i], i, i, stack, val, depth, options); - else { - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - fast_safe_stringify_decirc(val[key], key, i, stack, val, depth, options); - } - } - stack.pop(); - } -} -function fast_safe_stringify_replaceGetterValues(replacer) { - replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { - return v; - }; - return function(key, val) { - if (fast_safe_stringify_replacerStack.length > 0) for (var i = 0; i < fast_safe_stringify_replacerStack.length; i++) { - var part = fast_safe_stringify_replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - fast_safe_stringify_replacerStack.splice(i, 1); - break; - } - } - return replacer.call(this, key, val); - }; -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/import_constants.js -//#region src/load/import_constants.ts -const optionalImportEntrypoints = []; - -//#endregion - -//# sourceMappingURL=import_constants.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/agents.js -//#region src/agents.ts -var agents_exports = {}; - -//#endregion - -//# sourceMappingURL=agents.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js - - - - -//#region src/runnables/config.ts -const DEFAULT_RECURSION_LIMIT = 25; -async function getCallbackManagerForConfig(config) { - return CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); -} -function mergeConfigs(...configs) { - const copy = {}; - for (const options of configs.filter((c) => !!c)) for (const key of Object.keys(options)) if (key === "metadata") copy[key] = { - ...copy[key], - ...options[key] - }; - else if (key === "tags") { - const baseKeys = copy[key] ?? []; - copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; - } else if (key === "configurable") copy[key] = { - ...copy[key], - ...options[key] - }; - else if (key === "timeout") { - if (copy.timeout === void 0) copy.timeout = options.timeout; - else if (options.timeout !== void 0) copy.timeout = Math.min(copy.timeout, options.timeout); - } else if (key === "signal") { - if (copy.signal === void 0) copy.signal = options.signal; - else if (options.signal !== void 0) if ("any" in AbortSignal) copy.signal = AbortSignal.any([copy.signal, options.signal]); - else copy.signal = options.signal; - } else if (key === "callbacks") { - const baseCallbacks = copy.callbacks; - const providedCallbacks = options.callbacks; - if (Array.isArray(providedCallbacks)) if (!baseCallbacks) copy.callbacks = providedCallbacks; - else if (Array.isArray(baseCallbacks)) copy.callbacks = baseCallbacks.concat(providedCallbacks); - else { - const manager = baseCallbacks.copy(); - for (const callback of providedCallbacks) manager.addHandler(ensureHandler(callback), true); - copy.callbacks = manager; - } - else if (providedCallbacks) if (!baseCallbacks) copy.callbacks = providedCallbacks; - else if (Array.isArray(baseCallbacks)) { - const manager = providedCallbacks.copy(); - for (const callback of baseCallbacks) manager.addHandler(ensureHandler(callback), true); - copy.callbacks = manager; - } else copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { - handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), - inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), - tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), - inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), - metadata: { - ...baseCallbacks.metadata, - ...providedCallbacks.metadata - } - }); - } else { - const typedKey = key; - copy[typedKey] = options[typedKey] ?? copy[typedKey]; - } - return copy; -} -const PRIMITIVES = new Set([ - "string", - "number", - "boolean" -]); -/** -* Ensure that a passed config is an object with all required keys present. -*/ -function ensureConfig(config) { - const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - let empty = { - tags: [], - metadata: {}, - recursionLimit: 25, - runId: void 0 - }; - if (implicitConfig) { - const { runId, runName,...rest } = implicitConfig; - empty = Object.entries(rest).reduce((currentConfig, [key, value]) => { - if (value !== void 0) currentConfig[key] = value; - return currentConfig; - }, empty); - } - if (config) empty = Object.entries(config).reduce((currentConfig, [key, value]) => { - if (value !== void 0) currentConfig[key] = value; - return currentConfig; - }, empty); - if (empty?.configurable) { - for (const key of Object.keys(empty.configurable)) if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) { - if (!empty.metadata) empty.metadata = {}; - empty.metadata[key] = empty.configurable[key]; - } - } - if (empty.timeout !== void 0) { - if (empty.timeout <= 0) throw new Error("Timeout must be a positive number"); - const timeoutSignal = AbortSignal.timeout(empty.timeout); - if (empty.signal !== void 0) { - if ("any" in AbortSignal) empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); - } else empty.signal = timeoutSignal; - delete empty.timeout; - } - return empty; -} -/** -* Helper function that patches runnable configs with updated properties. -*/ -function config_patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) { - const newConfig = ensureConfig(config); - if (callbacks !== void 0) { - /** - * If we're replacing callbacks we need to unset runName - * since that should apply only to the same run as the original callbacks - */ - delete newConfig.runName; - newConfig.callbacks = callbacks; - } - if (recursionLimit !== void 0) newConfig.recursionLimit = recursionLimit; - if (maxConcurrency !== void 0) newConfig.maxConcurrency = maxConcurrency; - if (runName !== void 0) newConfig.runName = runName; - if (configurable !== void 0) newConfig.configurable = { - ...newConfig.configurable, - ...configurable - }; - if (runId !== void 0) delete newConfig.runId; - return newConfig; -} -function config_pickRunnableConfigKeys(config) { - return config ? { - configurable: config.configurable, - recursionLimit: config.recursionLimit, - callbacks: config.callbacks, - tags: config.tags, - metadata: config.metadata, - maxConcurrency: config.maxConcurrency, - timeout: config.timeout, - signal: config.signal - } : void 0; -} - -//#endregion - -//# sourceMappingURL=config.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js -//#region src/utils/signal.ts -/** -* Race a promise with an abort signal. If the signal is aborted, the promise will -* be rejected with the error from the signal. If the promise is rejected, the signal will be aborted. -* -* @param promise - The promise to race. -* @param signal - The abort signal. -* @returns The result of the promise. -*/ -async function raceWithSignal(promise, signal) { - if (signal === void 0) return promise; - let listener; - return Promise.race([promise.catch((err) => { - if (!signal?.aborted) throw err; - else return void 0; - }), new Promise((_, reject) => { - listener = () => { - reject(getAbortSignalError(signal)); - }; - signal.addEventListener("abort", listener); - if (signal.aborted) reject(getAbortSignalError(signal)); - })]).finally(() => signal.removeEventListener("abort", listener)); -} -/** -* Get the error from an abort signal. Since you can set the reason to anything, -* we have to do some type gymnastics to get a proper error message. -* -* @param signal - The abort signal. -* @returns The error from the abort signal. -*/ -function getAbortSignalError(signal) { - if (signal?.reason instanceof Error) return signal.reason; - if (typeof signal?.reason === "string") return new Error(signal.reason); - return /* @__PURE__ */ new Error("Aborted"); -} - -//#endregion - -//# sourceMappingURL=signal.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js - - - - - - -//#region src/utils/stream.ts -var stream_exports = {}; -__export(stream_exports, { - AsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup, - IterableReadableStream: () => IterableReadableStream, - atee: () => atee, - concat: () => concat, - pipeGeneratorWithSetup: () => pipeGeneratorWithSetup -}); -var IterableReadableStream = class IterableReadableStream extends ReadableStream { - reader; - ensureReader() { - if (!this.reader) this.reader = this.getReader(); - } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) { - this.reader.releaseLock(); - return { - done: true, - value: void 0 - }; - } else return { - done: false, - value: result.value - }; - } catch (e) { - this.reader.releaseLock(); - throw e; - } - } - async return() { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise; - } - return { - done: true, - value: void 0 - }; - } - async throw(e) { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise; - } - throw e; - } - [Symbol.asyncIterator]() { - return this; - } - async [Symbol.asyncDispose]() { - await this.return(); - } - static fromReadableStream(stream) { - const reader = stream.getReader(); - return new IterableReadableStream({ - start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump(); - }); - } - }, - cancel() { - reader.releaseLock(); - } - }); - } - static fromAsyncGenerator(generator) { - return new IterableReadableStream({ - async pull(controller) { - const { value, done } = await generator.next(); - if (done) controller.close(); - controller.enqueue(value); - }, - async cancel(reason) { - await generator.return(reason); - } - }); - } -}; -function atee(iter, length = 2) { - const buffers = Array.from({ length }, () => []); - return buffers.map(async function* makeIter(buffer) { - while (true) if (buffer.length === 0) { - const result = await iter.next(); - for (const buffer$1 of buffers) buffer$1.push(result); - } else if (buffer[0].done) return; - else yield buffer.shift().value; - }); -} -function concat(first, second) { - if (Array.isArray(first) && Array.isArray(second)) return first.concat(second); - else if (typeof first === "string" && typeof second === "string") return first + second; - else if (typeof first === "number" && typeof second === "number") return first + second; - else if ("concat" in first && typeof first.concat === "function") return first.concat(second); - else if (typeof first === "object" && typeof second === "object") { - const chunk = { ...first }; - for (const [key, value] of Object.entries(second)) if (key in chunk && !Array.isArray(chunk[key])) chunk[key] = concat(chunk[key], value); - else chunk[key] = value; - return chunk; - } else throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); -} -var AsyncGeneratorWithSetup = class { - generator; - setup; - config; - signal; - firstResult; - firstResultUsed = false; - constructor(params) { - this.generator = params.generator; - this.config = params.config; - this.signal = params.signal ?? this.config?.signal; - this.setup = new Promise((resolve, reject) => { - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(params.config), async () => { - this.firstResult = params.generator.next(); - if (params.startSetup) this.firstResult.then(params.startSetup).then(resolve, reject); - else this.firstResult.then((_result) => resolve(void 0), reject); - }, true); - }); - } - async next(...args) { - this.signal?.throwIfAborted(); - if (!this.firstResultUsed) { - this.firstResultUsed = true; - return this.firstResult; - } - return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(this.config), this.signal ? async () => { - return raceWithSignal(this.generator.next(...args), this.signal); - } : async () => { - return this.generator.next(...args); - }, true); - } - async return(value) { - return this.generator.return(value); - } - async throw(e) { - return this.generator.throw(e); - } - [Symbol.asyncIterator]() { - return this; - } - async [Symbol.asyncDispose]() { - await this.return(); - } -}; -async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { - const gen = new AsyncGeneratorWithSetup({ - generator, - startSetup, - signal - }); - const setup = await gen.setup; - return { - output: to(gen, setup, ...args), - setup - }; -} - -//#endregion - -//# sourceMappingURL=stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -//#region src/utils/fast-json-patch/src/helpers.ts -/*! -* https://github.com/Starcounter-Jack/JSON-Patch -* (c) 2017-2022 Joachim Wester -* MIT licensed -*/ -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function helpers_hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys$1 = new Array(obj.length); - for (let k = 0; k < keys$1.length; k++) keys$1[k] = "" + k; - return keys$1; - } - if (Object.keys) return Object.keys(obj); - let keys = []; - for (let i in obj) if (helpers_hasOwnProperty(obj, i)) keys.push(i); - return keys; -} -/** -* Deeply clone the object. -* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) -* @param {any} obj value to clone -* @return {any} cloned obj -*/ -function _deepClone(obj) { - switch (typeof obj) { - case "object": return JSON.parse(JSON.stringify(obj)); - case "undefined": return null; - default: return obj; - } -} -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; - } - return false; - } - return true; -} -/** -* Escapes a json pointer path -* @param path The raw pointer -* @return the Escaped path -*/ -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** -* Unescapes a json pointer path -* @param path The escaped pointer -* @return The unescaped path -*/ -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -/** -* Recursively checks whether an object has any undefined values inside. -*/ -function hasUndefined(obj) { - if (obj === void 0) return true; - if (obj) { - if (Array.isArray(obj)) { - for (let i$1 = 0, len = obj.length; i$1 < len; i$1++) if (hasUndefined(obj[i$1])) return true; - } else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) if (hasUndefined(obj[objKeys[i]])) return true; - } - } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; - if (typeof value !== "undefined") messageParts.push(`${key}: ${value}`); - } - return messageParts.join("\n"); -} -var PatchError = class extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { - name, - index, - operation, - tree - })); - this.name = name; - this.index = index; - this.operation = operation; - this.tree = tree; - Object.setPrototypeOf(this, new.target.prototype); - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree - }); - } -}; - -//#endregion - -//# sourceMappingURL=helpers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js - - - -//#region src/utils/fast-json-patch/src/core.ts -var core_exports = {}; -__export(core_exports, { - JsonPatchError: () => JsonPatchError, - _areEquals: () => _areEquals, - applyOperation: () => applyOperation, - applyPatch: () => applyPatch, - applyReducer: () => applyReducer, - deepClone: () => deepClone, - getValueByPointer: () => getValueByPointer, - validate: () => core_validate, - validator: () => validator -}); -const JsonPatchError = PatchError; -const deepClone = _deepClone; -const objOps = { - add: function(obj, key, document) { - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function(obj, key, document) { - var removed = obj[key]; - delete obj[key]; - return { - newDocument: document, - removed - }; - }, - replace: function(obj, key, document) { - var removed = obj[key]; - obj[key] = this.value; - return { - newDocument: document, - removed - }; - }, - move: function(obj, key, document) { - let removed = getValueByPointer(document, this.path); - if (removed) removed = _deepClone(removed); - const originalValue = applyOperation(document, { - op: "remove", - path: this.from - }).removed; - applyOperation(document, { - op: "add", - path: this.path, - value: originalValue - }); - return { - newDocument: document, - removed - }; - }, - copy: function(obj, key, document) { - const valueToCopy = getValueByPointer(document, this.from); - applyOperation(document, { - op: "add", - path: this.path, - value: _deepClone(valueToCopy) - }); - return { newDocument: document }; - }, - test: function(obj, key, document) { - return { - newDocument: document, - test: _areEquals(obj[key], this.value) - }; - }, - _get: function(obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - } -}; -var arrOps = { - add: function(arr, i, document) { - if (isInteger(i)) arr.splice(i, 0, this.value); - else arr[i] = this.value; - return { - newDocument: document, - index: i - }; - }, - remove: function(arr, i, document) { - var removedList = arr.splice(i, 1); - return { - newDocument: document, - removed: removedList[0] - }; - }, - replace: function(arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { - newDocument: document, - removed - }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get -}; -/** -* Retrieves a value from a JSON document by a JSON pointer. -* Returns the value. -* -* @param document The document to get the value from -* @param pointer an escaped JSON pointer -* @return The retrieved value -*/ -function getValueByPointer(document, pointer) { - if (pointer == "") return document; - var getOriginalDestination = { - op: "_get", - path: pointer - }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; -} -/** -* Apply a single JSON Patch Operation on a JSON document. -* Returns the {newDocument, result} of the operation. -* It modifies the `document` and `operation` objects - it gets the values by reference. -* If you would like to avoid touching your values, clone them: -* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. -* -* @param document The document to patch -* @param operation The operation to apply -* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. -* @param mutateDocument Whether to mutate the original document or clone it before applying -* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. -* @return `{newDocument, result}` after the operation -*/ -function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) if (typeof validateOperation == "function") validateOperation(operation, 0, document, operation.path); - else validator(operation, 0); - if (operation.path === "") { - let returnValue = { newDocument: document }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document; - return returnValue; - } else if (operation.op === "move" || operation.op === "copy") { - returnValue.newDocument = getValueByPointer(document, operation.from); - if (operation.op === "move") returnValue.removed = document; - return returnValue; - } else if (operation.op === "test") { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - returnValue.newDocument = document; - return returnValue; - } else if (operation.op === "remove") { - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; - } else if (operation.op === "_get") { - operation.value = document; - return returnValue; - } else if (validateOperation) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - else return returnValue; - } else { - if (!mutateDocument) document = _deepClone(document); - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document; - let t = 1; - let len = keys.length; - let existingPathFragment = void 0; - let key; - let validateFunction; - if (typeof validateOperation == "function") validateFunction = validateOperation; - else validateFunction = validator; - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) key = unescapePathComponent(key); - if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); - if (validateOperation) { - if (existingPathFragment === void 0) { - if (obj[key] === void 0) existingPathFragment = keys.slice(0, t).join("/"); - else if (t == len - 1) existingPathFragment = operation.path; - if (existingPathFragment !== void 0) validateFunction(operation, 0, document, existingPathFragment); - } - } - t++; - if (Array.isArray(obj)) { - if (key === "-") key = obj.length; - else if (validateOperation && !isInteger(key)) throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); - else if (isInteger(key)) key = ~~key; - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); - const returnValue = arrOps[operation.op].call(operation, obj, key, document); - if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - return returnValue; - } - } else if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document); - if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - return returnValue; - } - obj = obj[key]; - if (validateOperation && t < len && (!obj || typeof obj !== "object")) throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } - } -} -/** -* Apply a full JSON Patch array on a JSON document. -* Returns the {newDocument, result} of the patch. -* It modifies the `document` object and `patch` - it gets the values by reference. -* If you would like to avoid touching your values, clone them: -* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. -* -* @param document The document to patch -* @param patch The patch to apply -* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. -* @param mutateDocument Whether to mutate the original document or clone it before applying -* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. -* @return An array of `{newDocument, result}` after the patch -*/ -function applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (!mutateDocument) document = _deepClone(document); - const results = new Array(patch.length); - for (let i = 0, length = patch.length; i < length; i++) { - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; - } - results.newDocument = document; - return results; -} -/** -* Apply a single JSON Patch Operation on a JSON document. -* Returns the updated document. -* Suitable as a reducer. -* -* @param document The document to patch -* @param operation The operation to apply -* @return The updated document -*/ -function applyReducer(document, operation, index) { - const operationResult = applyOperation(document, operation); - if (operationResult.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - return operationResult.newDocument; -} -/** -* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. -* @param {object} operation - operation object (patch) -* @param {number} index - index of operation in the sequence -* @param {object} [document] - object where the operation is supposed to be applied -* @param {string} [existingPathFragment] - comes along with `document` -*/ -function validator(operation, index, document, existingPathFragment) { - if (typeof operation !== "object" || operation === null || Array.isArray(operation)) throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); - else if (!objOps[operation.op]) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - else if (typeof operation.path !== "string") throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) throw new JsonPatchError("Operation `path` property must start with \"/\"", "OPERATION_PATH_INVALID", index, operation, document); - else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); - else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); - else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); - else if (document) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); - } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { - if (operation.path !== existingPathFragment) throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: void 0 - }; - var error = core_validate([existingValue], document); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); - } - } -} -/** -* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. -* If error is encountered, returns a JsonPatchError object -* @param sequence -* @param document -* @returns {JsonPatchError|undefined} -*/ -function core_validate(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - if (document) applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); - else { - externalValidator = externalValidator || validator; - for (var i = 0; i < sequence.length; i++) externalValidator(sequence[i], i, document, void 0); - } - } catch (e) { - if (e instanceof JsonPatchError) return e; - else throw e; - } -} -function _areEquals(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false; - return true; - } - if (arrA != arrB) return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; -} - -//#endregion - -//# sourceMappingURL=core.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js - - - -//#region src/utils/fast-json-patch/src/duplex.ts -function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) return; - if (typeof obj.toJSON === "function") obj = obj.toJSON(); - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var changed = false; - var deleted = false; - for (var t = oldKeys.length - 1; t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (helpers_hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); - else if (oldVal !== newVal) { - changed = true; - if (invertible) patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - patches.push({ - op: "replace", - path: path + "/" + escapePathComponent(key), - value: _deepClone(newVal) - }); - } - } else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - patches.push({ - op: "remove", - path: path + "/" + escapePathComponent(key) - }); - deleted = true; - } else { - if (invertible) patches.push({ - op: "test", - path, - value: mirror - }); - patches.push({ - op: "replace", - path, - value: obj - }); - changed = true; - } - } - if (!deleted && newKeys.length == oldKeys.length) return; - for (var t = 0; t < newKeys.length; t++) { - var key = newKeys[t]; - if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({ - op: "add", - path: path + "/" + escapePathComponent(key), - value: _deepClone(obj[key]) - }); - } -} -/** -* Create an array of patches from the differences in two objects -*/ -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; -} - -//#endregion - -//# sourceMappingURL=duplex.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js - - - - -//#region src/utils/fast-json-patch/index.ts -var fast_json_patch_default = { - ...core_exports, - JsonPatchError: PatchError, - deepClone: _deepClone, - escapePathComponent: escapePathComponent, - unescapePathComponent: unescapePathComponent -}; - -//#endregion -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js - - - - - - - -//#region src/tracers/log_stream.ts -var log_stream_exports = {}; -__export(log_stream_exports, { - LogStreamCallbackHandler: () => LogStreamCallbackHandler, - RunLog: () => RunLog, - RunLogPatch: () => RunLogPatch, - isLogStreamHandler: () => isLogStreamHandler -}); -/** -* List of jsonpatch JSONPatchOperations, which describe how to create the run state -* from an empty dict. This is the minimal representation of the log, designed to -* be serialized as JSON and sent over the wire to reconstruct the log on the other -* side. Reconstruction of the state can be done with any jsonpatch-compliant library, -* see https://jsonpatch.com for more information. -*/ -var RunLogPatch = class { - ops; - constructor(fields) { - this.ops = fields.ops ?? []; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch({}, ops); - return new RunLog({ - ops, - state: states[states.length - 1].newDocument - }); - } -}; -var RunLog = class RunLog extends RunLogPatch { - state; - constructor(fields) { - super(fields); - this.state = fields.state; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch(this.state, other.ops); - return new RunLog({ - ops, - state: states[states.length - 1].newDocument - }); - } - static fromRunLogPatch(patch) { - const states = applyPatch({}, patch.ops); - return new RunLog({ - ops: patch.ops, - state: states[states.length - 1].newDocument - }); - } -}; -const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; -/** -* Extract standardized inputs from a run. -* -* Standardizes the inputs based on the type of the runnable used. -* -* @param run - Run object -* @param schemaFormat - The schema format to use. -* -* @returns Valid inputs are only dict. By conventions, inputs always represented -* invocation using named arguments. -* A null means that the input is not yet known! -*/ -async function _getStandardizedInputs(run, schemaFormat) { - if (schemaFormat === "original") throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); - const { inputs } = run; - if ([ - "retriever", - "llm", - "prompt" - ].includes(run.run_type)) return inputs; - if (Object.keys(inputs).length === 1 && inputs?.input === "") return void 0; - return inputs.input; -} -async function _getStandardizedOutputs(run, schemaFormat) { - const { outputs } = run; - if (schemaFormat === "original") return outputs; - if ([ - "retriever", - "llm", - "prompt" - ].includes(run.run_type)) return outputs; - if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) return outputs.output; - return outputs; -} -function isChatGenerationChunk(x) { - return x !== void 0 && x.message !== void 0; -} -/** -* Class that extends the `BaseTracer` class from the -* `langchain.callbacks.tracers.base` module. It represents a callback -* handler that logs the execution of runs and emits `RunLog` instances to a -* `RunLogStream`. -*/ -var LogStreamCallbackHandler = class extends BaseTracer { - autoClose = true; - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - _schemaFormat = "original"; - rootId; - keyMapByRunId = {}; - counterMapByRunName = {}; - transformStream; - writer; - receiveStream; - name = "log_stream_tracer"; - lc_prefer_streaming = true; - constructor(fields) { - super({ - _awaitHandler: true, - ...fields - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) {} - _includeRun(run) { - if (run.id === this.rootId) return false; - const runTags = run.tags ?? []; - let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; - if (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name); - if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.run_type); - if (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; - if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name); - if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.run_type); - if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } - async *tapOutputIterable(runId, output) { - for await (const chunk of output) { - if (runId !== this.rootId) { - const key = this.keyMapByRunId[runId]; - if (key) await this.writer.write(new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${key}/streamed_output/-`, - value: chunk - }] })); - } - yield chunk; - } - } - async onRunCreate(run) { - if (this.rootId === void 0) { - this.rootId = run.id; - await this.writer.write(new RunLogPatch({ ops: [{ - op: "replace", - path: "", - value: { - id: run.id, - name: run.name, - type: run.run_type, - streamed_output: [], - final_output: void 0, - logs: {} - } - }] })); - } - if (!this._includeRun(run)) return; - if (this.counterMapByRunName[run.name] === void 0) this.counterMapByRunName[run.name] = 0; - this.counterMapByRunName[run.name] += 1; - const count = this.counterMapByRunName[run.name]; - this.keyMapByRunId[run.id] = count === 1 ? run.name : `${run.name}:${count}`; - const logEntry = { - id: run.id, - name: run.name, - type: run.run_type, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - start_time: new Date(run.start_time).toISOString(), - streamed_output: [], - streamed_output_str: [], - final_output: void 0, - end_time: void 0 - }; - if (this._schemaFormat === "streaming_events") logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); - await this.writer.write(new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${this.keyMapByRunId[run.id]}`, - value: logEntry - }] })); - } - async onRunUpdate(run) { - try { - const runName = this.keyMapByRunId[run.id]; - if (runName === void 0) return; - const ops = []; - if (this._schemaFormat === "streaming_events") ops.push({ - op: "replace", - path: `/logs/${runName}/inputs`, - value: await _getStandardizedInputs(run, this._schemaFormat) - }); - ops.push({ - op: "add", - path: `/logs/${runName}/final_output`, - value: await _getStandardizedOutputs(run, this._schemaFormat) - }); - if (run.end_time !== void 0) ops.push({ - op: "add", - path: `/logs/${runName}/end_time`, - value: new Date(run.end_time).toISOString() - }); - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); - } finally { - if (run.id === this.rootId) { - const patch = new RunLogPatch({ ops: [{ - op: "replace", - path: "/final_output", - value: await _getStandardizedOutputs(run, this._schemaFormat) - }] }); - await this.writer.write(patch); - if (this.autoClose) await this.writer.close(); - } - } - } - async onLLMNewToken(run, token, kwargs) { - const runName = this.keyMapByRunId[run.id]; - if (runName === void 0) return; - const isChatModel = run.inputs.messages !== void 0; - let streamedOutputValue; - if (isChatModel) if (isChatGenerationChunk(kwargs?.chunk)) streamedOutputValue = kwargs?.chunk; - else streamedOutputValue = new AIMessageChunk({ - id: `run-${run.id}`, - content: token - }); - else streamedOutputValue = token; - const patch = new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${runName}/streamed_output_str/-`, - value: token - }, { - op: "add", - path: `/logs/${runName}/streamed_output/-`, - value: streamedOutputValue - }] }); - await this.writer.write(patch); - } -}; - -//#endregion - -//# sourceMappingURL=log_stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js - - -//#region src/outputs.ts -var outputs_exports = {}; -__export(outputs_exports, { - ChatGenerationChunk: () => ChatGenerationChunk, - GenerationChunk: () => GenerationChunk, - RUN_KEY: () => RUN_KEY -}); -const RUN_KEY = "__run"; -/** -* Chunk of a single generation. Used for streaming. -*/ -var GenerationChunk = class GenerationChunk { - text; - generationInfo; - constructor(fields) { - this.text = fields.text; - this.generationInfo = fields.generationInfo; - } - concat(chunk) { - return new GenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo - } - }); - } -}; -var ChatGenerationChunk = class ChatGenerationChunk extends GenerationChunk { - message; - constructor(fields) { - super(fields); - this.message = fields.message; - } - concat(chunk) { - return new ChatGenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo - }, - message: this.message.concat(chunk.message) - }); - } -}; - -//#endregion - -//# sourceMappingURL=outputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js - - - - - -//#region src/utils/async_caller.ts -var async_caller_exports = {}; -__export(async_caller_exports, { AsyncCaller: () => async_caller_AsyncCaller }); -const STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 -]; -const defaultFailedAttemptHandler = (error) => { - if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") throw error; - if (error?.code === "ECONNABORTED") throw error; - const status = error?.response?.status ?? error?.status; - if (status && STATUS_NO_RETRY.includes(+status)) throw error; - if (error?.error?.code === "insufficient_quota") { - const err = new Error(error?.message); - err.name = "InsufficientQuotaError"; - throw err; - } -}; -/** -* A class that can be used to make async calls with concurrency and retry logic. -* -* This is useful for making calls to any kind of "expensive" external resource, -* be it because it's rate-limited, subject to network issues, etc. -* -* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults -* to `Infinity`. This means that by default, all calls will be made in parallel. -* -* Retries are limited by the `maxRetries` parameter, which defaults to 6. This -* means that by default, each call will be retried up to 6 times, with an -* exponential backoff between each attempt. -*/ -var async_caller_AsyncCaller = class { - maxConcurrency; - maxRetries; - onFailedAttempt; - queue; - constructor(params) { - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); - } - call(callable, ...args) { - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - if (error instanceof Error) throw error; - else throw new Error(error); - }), { - onFailedAttempt: this.onFailedAttempt, - retries: this.maxRetries, - randomize: true - }), { throwOnTimeout: true }); - } - callWithOptions(options, callable, ...args) { - if (options.signal) return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(getAbortSignalError(options.signal)); - }); - })]); - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); - } -}; - -//#endregion - -//# sourceMappingURL=async_caller.js.map -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/core.js -/** A special constant with type `never` */ -const NEVER = Object.freeze({ - status: "aborted", -}); -function $constructor(name, initializer, params) { - function init(inst, def) { - var _a; - Object.defineProperty(inst, "_zod", { - value: inst._zod ?? {}, - enumerable: false, - }); - (_a = inst._zod).traits ?? (_a.traits = new Set()); - inst._zod.traits.add(name); - initializer(inst, def); - // support prototype modifications - for (const k in _.prototype) { - if (!(k in inst)) - Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); - } - inst._zod.constr = _; - inst._zod.def = def; - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a = inst._zod).deferred ?? (_a.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = Symbol("zod_brand"); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -const globalConfig = {}; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/util.js -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error(); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / 10 ** decCount; -} -function defineLazy(object, key, getter) { - const set = false; - Object.defineProperty(object, key, { - get() { - if (!set) { - const value = getter(); - object[key] = value; - return value; - } - throw new Error("cached value already set"); - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function esc(str) { - return JSON.stringify(str); -} -const captureStackTrace = Error.captureStackTrace - ? Error.captureStackTrace - : (..._args) => { }; -function isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const allowsEval = cached(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - // modified prototype - const prot = ctor.prototype; - if (isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = new Set(["string", "number", "symbol"]); -const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); -} -const NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}; -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const newShape = {}; - const currDef = schema._zod.def; //.shape; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - // pick key - newShape[key] = currDef.shape[key]; - } - return clone(schema, { - ...schema._zod.def, - shape: newShape, - checks: [], - }); -} -function omit(schema, mask) { - const newShape = { ...schema._zod.def.shape }; - const currDef = schema._zod.def; //.shape; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - return clone(schema, { - ...schema._zod.def, - shape: newShape, - checks: [], - }); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const def = { - ...schema._zod.def, - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - checks: [], // delete existing checks - }; - return clone(schema, def); -} -function merge(a, b) { - return clone(a, { - ...a._zod.def, - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - catchall: b._zod.def.catchall, - checks: [], // delete existing checks - }); -} -function partial(Class, schema, mask) { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - for (const key in oldShape) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - return clone(schema, { - ...schema._zod.def, - shape, - checks: [], - }); -} -function required(Class, schema, mask) { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key in oldShape) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - return clone(schema, { - ...schema._zod.def, - shape, - // optional: [], - checks: [], - }); -} -function aborted(x, startIndex = 0) { - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) - return true; - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -function finalizeIssue(iss, ctx, config) { - const full = { ...iss, path: iss.path ?? [] }; - // for backwards compatibility - if (!iss.message) { - const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"; - full.message = message; - } - // delete (full as any).def; - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// instanceof -class Class { - constructor(..._args) { } -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/errors.js - - -const initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false, - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false, - }); - Object.defineProperty(inst, "message", { - get() { - return JSON.stringify(def, jsonStringifyReplacer, 2); - }, - enumerable: true, - // configurable: false, - }); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false, - }); -}; -const $ZodError = $constructor("$ZodError", initializer); -const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, _mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues })); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, _mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a, _b; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, issue.path)); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, issue.path); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, issue.path); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(path) { - const segs = []; - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/parse.js - - - -const _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; -}; -const parse_parse = /* @__PURE__*/ _parse($ZodRealError); -const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; -}; -const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/registries.js -const $output = Symbol("ZodOutput"); -const $input = Symbol("ZodInput"); -class $ZodRegistry { - constructor() { - this._map = new Map(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - if (this._idmap.has(meta.id)) { - throw new Error(`ID ${meta.id} already exists in the registry`); - } - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new Map(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - return { ...pm, ...this._map.get(schema) }; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registry() { - return new $ZodRegistry(); -} -const globalRegistry = /*@__PURE__*/ registry(); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/checks.js -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_big", - maximum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckGreaterThan = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_small", - minimum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMultipleOf = -/*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? payload.value % def.value === BigInt(0) - : util.floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = regexes.integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inst, - }); - } - }; -}))); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inst, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}))); -const $ZodCheckRegex = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckLowerCase = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = regexes.lowercase); - $ZodCheckStringFormat.init(inst, def); -}))); -const $ZodCheckUpperCase = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = regexes.uppercase); - $ZodCheckStringFormat.init(inst, def); -}))); -const $ZodCheckIncludes = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = util.escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckStartsWith = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckEndsWith = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/versions.js -const versions_version = { - major: 4, - minor: 0, - patch: 0, -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/schemas.js - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const checks = [...(inst._zod.def.checks ?? [])]; - // if inst is itself a checks.$ZodCheck, run it as a check - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } - // - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer - // inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - inst._zod.run = (payload, ctx) => { - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - inst["~standard"] = { - validate: (value) => { - try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } - catch (_) { - return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); - } - }, - vendor: "zod", - version: 1, - }; -}); - -const $ZodString = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - checks.$ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}))); -const $ZodGUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = regexes.guid); - $ZodStringFormat.init(inst, def); -}))); -const $ZodUUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = regexes.uuid(v)); - } - else - def.pattern ?? (def.pattern = regexes.uuid()); - $ZodStringFormat.init(inst, def); -}))); -const $ZodEmail = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = regexes.email); - $ZodStringFormat.init(inst, def); -}))); -const $ZodURL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const orig = payload.value; - const url = new URL(orig); - const href = url.href; - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: regexes.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - } - // payload.value = url.href; - if (!orig.endsWith("/") && href.endsWith("/")) { - payload.value = href.slice(0, -1); - } - else { - payload.value = href; - } - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodEmoji = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = regexes.emoji()); - $ZodStringFormat.init(inst, def); -}))); -const $ZodNanoID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = regexes.nanoid); - $ZodStringFormat.init(inst, def); -}))); -const $ZodCUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = regexes.cuid); - $ZodStringFormat.init(inst, def); -}))); -const $ZodCUID2 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = regexes.cuid2); - $ZodStringFormat.init(inst, def); -}))); -const $ZodULID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = regexes.ulid); - $ZodStringFormat.init(inst, def); -}))); -const $ZodXID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = regexes.xid); - $ZodStringFormat.init(inst, def); -}))); -const $ZodKSUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = regexes.ksuid); - $ZodStringFormat.init(inst, def); -}))); -const $ZodISODateTime = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes.datetime(def)); - $ZodStringFormat.init(inst, def); -}))); -const $ZodISODate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes.date); - $ZodStringFormat.init(inst, def); -}))); -const $ZodISOTime = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes.time(def)); - $ZodStringFormat.init(inst, def); -}))); -const $ZodISODuration = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = regexes.duration); - $ZodStringFormat.init(inst, def); -}))); -const $ZodIPv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = regexes.ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = `ipv4`; - }); -}))); -const $ZodIPv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes.ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = `ipv6`; - }); - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - // return; - } - catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = regexes.cidrv4); - $ZodStringFormat.init(inst, def); -}))); -const $ZodCIDRv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - const [address, prefix] = payload.value.split("/"); - try { - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } - catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}))); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes.base64); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst) => { - inst._zod.bag.contentEncoding = "base64"; - }); - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes.base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes.base64url); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst) => { - inst._zod.bag.contentEncoding = "base64url"; - }); - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodE164 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = regexes.e164); - $ZodStringFormat.init(inst, def); -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? "Infinity" - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}))); -const $ZodNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNumber", (inst, def) => { - checks.$ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checksp -}))); -const $ZodBoolean = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handleObjectResult(result, final, key) { - // if(isOptional) - if (result.issues.length) { - final.issues.push(...util.prefixIssues(key, result.issues)); - } - final.value[key] = result.value; -} -function handleOptionalObjectResult(result, final, key, input) { - if (result.issues.length) { - // validation failed against value schema - if (input[key] === undefined) { - // if input was undefined, ignore the error - if (key in input) { - final.value[key] = undefined; - } - else { - final.value[key] = result.value; - } - } - else { - final.issues.push(...util.prefixIssues(key, result.issues)); - } - } - else if (result.value === undefined) { - // validation returned `undefined` - if (key in input) - final.value[key] = undefined; - } - else { - // non-undefined value - final.value[key] = result.value; - } -} -const $ZodObject = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - const _normalized = util.cached(() => { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!(def.shape[k] instanceof $ZodType)) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - } - } - const okeys = util.optionalKeys(def.shape); - return { - shape: def.shape, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; - }); - util.defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = new Set()); - for (const v of field.values) - propValues[key].add(v); - } - } - return propValues; - }); - const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = util.esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(`const newResult = {}`); - for (const key of normalized.keys) { - if (normalized.optionalKeys.has(key)) { - const id = ids[key]; - doc.write(`const ${id} = ${parseStr(key)};`); - const k = util.esc(key); - doc.write(` - if (${id}.issues.length) { - if (input[${k}] === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - payload.issues = payload.issues.concat( - ${id}.issues.map((iss) => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}], - })) - ); - } - } else if (${id}.value === undefined) { - if (${k} in input) newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } - `); - } - else { - const id = ids[key]; - // const id = ids[key]; - doc.write(`const ${id} = ${parseStr(key)};`); - doc.write(` - if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${util.esc(key)}, ...iss.path] : [${util.esc(key)}] - })));`); - doc.write(`newResult[${util.esc(key)}] = ${id}.value`); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject = util.isObject; - const jit = !core.globalConfig.jitless; - const allowsEval = util.allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - } - else { - payload.value = {}; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - // do not add omitted optional keys - // if (!(key in input)) { - // if (optionalKeys.has(key)) continue; - // payload.issues.push({ - // code: "invalid_type", - // path: [key], - // expected: "nonoptional", - // note: `Missing required key: "${key}"`, - // input, - // inst, - // }); - // } - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; - if (r instanceof Promise) { - proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key))); - } - else if (isOptional) { - handleOptionalObjectResult(r, payload, key, input); - } - else { - handleObjectResult(r, payload, key); - } - } - } - if (!catchall) { - // return payload; - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - const unrecognized = []; - // iterate over input keys - const keySet = value.keySet; - const _catchall = catchall._zod; - const t = _catchall.def.type; - for (const key of Object.keys(input)) { - if (keySet.has(key)) - continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handleObjectResult(r, payload, key))); - } - else { - handleObjectResult(r, payload, key); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); - }; -}))); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - inst._zod.parse = (payload, ctx) => { - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -(/* unused pure expression or super */ null && (core.$constructor("$ZodDiscriminatedUnion", (inst, def) => { - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - util.defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = new Set(); - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - const disc = util.cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util.isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - if (def.unionFallback) { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}))); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - if (left.issues.length) { - result.issues.push(...left.issues); - } - if (right.issues.length) { - result.issues.push(...right.issues); - } - if (aborted(result)) - return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = []; - const proms = []; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload.issues.push({ - input, - inst, - origin: "array", - ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), - }); - return payload; - } - } - let i = -1; - for (const item of items) { - i++; - if (i >= input.length) - if (i >= optStart) - continue; - const result = item._zod.run({ - value: input[i], - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleTupleResult(result, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - if (def.rest) { - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ - value: el, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleTupleResult(result, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodRecord = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util.isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - if (def.keyType._zod.values) { - const values = def.keyType._zod.values; - payload.value = {}; - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!values.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - }); - } - } - else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - origin: "record", - code: "invalid_key", - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - input: key, - path: [key], - inst, - }); - payload.value[keyResult.value] = keyResult.value; - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}))); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_key", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = util.getEnumValues(def.entries); - inst._zod.values = new Set(values); - inst._zod.pattern = new RegExp(`^(${values - .filter((k) => util.propertyKeyTypes.has(typeof k)) - .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o.toString())) - .join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (inst._zod.values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}))); -const $ZodLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.values = new Set(def.values); - inst._zod.pattern = new RegExp(`^(${def.values - .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o ? o.toString() : String(o))) - .join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (inst._zod.values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}))); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const _out = def.transform(payload.value, payload); - if (_ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === undefined) { - return payload; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault always returns the default value immediately. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }, - input: payload.value, - }); - payload.issues = []; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }, - input: payload.value, - }); - payload.issues = []; - } - return payload; - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - inst._zod.parse = (payload, ctx) => { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def, ctx)); - } - return handlePipeResult(left, def, ctx); - }; -}); -function handlePipeResult(left, def, ctx) { - if (aborted(left)) { - return left; - } - return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (part instanceof $ZodType) { - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "template_literal", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazy(inst._zod, "innerType", () => def.getter()); - util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); - util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); - util.defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin); - util.defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}))); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/api.js - - - -function _string(Class, params) { - return new Class({ - type: "string", - ...util.normalizeParams(params), - }); -} -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...util.normalizeParams(params), - }); -} -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...util.normalizeParams(params), - }); -} -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...util.normalizeParams(params), - }); -} -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -const TimePrecision = { - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -}; -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...util.normalizeParams(params), - }); -} -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...util.normalizeParams(params), - }); -} -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...util.normalizeParams(params), - }); -} -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...util.normalizeParams(params), - }); -} -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...util.normalizeParams(params), - }); -} -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...util.normalizeParams(params), - }); -} -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...util.normalizeParams(params), - }); -} -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...util.normalizeParams(params), - }); -} -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -function _undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -function _null(Class, params) { - return new Class({ - type: "null", - ...util.normalizeParams(params), - }); -} -function _any(Class) { - return new Class({ - type: "any", - }); -} -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -function _lt(value, params) { - return new checks.$ZodCheckLessThan({ - check: "less_than", - ...util.normalizeParams(params), - value, - inclusive: false, - }); -} -function _lte(value, params) { - return new checks.$ZodCheckLessThan({ - check: "less_than", - ...util.normalizeParams(params), - value, - inclusive: true, - }); -} - -function _gt(value, params) { - return new checks.$ZodCheckGreaterThan({ - check: "greater_than", - ...util.normalizeParams(params), - value, - inclusive: false, - }); -} -function _gte(value, params) { - return new checks.$ZodCheckGreaterThan({ - check: "greater_than", - ...util.normalizeParams(params), - value, - inclusive: true, - }); -} - -function _positive(params) { - return _gt(0, params); -} -// negative -function _negative(params) { - return _lt(0, params); -} -// nonpositive -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -function _nonnegative(params) { - return _gte(0, params); -} -function _multipleOf(value, params) { - return new checks.$ZodCheckMultipleOf({ - check: "multiple_of", - ...util.normalizeParams(params), - value, - }); -} -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -function _regex(pattern, params) { - return new checks.$ZodCheckRegex({ - check: "string_format", - format: "regex", - ...util.normalizeParams(params), - pattern, - }); -} -function _lowercase(params) { - return new checks.$ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...util.normalizeParams(params), - }); -} -function _uppercase(params) { - return new checks.$ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...util.normalizeParams(params), - }); -} -function _includes(includes, params) { - return new checks.$ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...util.normalizeParams(params), - includes, - }); -} -function _startsWith(prefix, params) { - return new checks.$ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...util.normalizeParams(params), - prefix, - }); -} -function _endsWith(suffix, params) { - return new checks.$ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...util.normalizeParams(params), - suffix, - }); -} -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options, - discriminator, - ...util.normalizeParams(params), - }); -} -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; - }, - }); -} -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), - }); -} -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// export function _refine( -// Class: util.SchemaClass, -// fn: (arg: NoInfer) => util.MaybeAsync, -// _params: string | $ZodCustomParams = {} -// ): checks.$ZodCheck { -// return _custom(Class, fn, _params); -// } -// same as _custom but defaults to abort:false -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Pipe = Classes.Pipe ?? schemas.$ZodPipe; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const _Transform = Classes.Transform ?? schemas.$ZodTransform; - const tx = new _Transform({ - type: "transform", - transform: (input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: tx, - }); - return {}; - } - }, - error: params.error, - }); - // params.error; - const innerPipe = new _Pipe({ - type: "pipe", - in: new _String({ type: "string", error: params.error }), - out: tx, - error: params.error, - }); - const outerPipe = new _Pipe({ - type: "pipe", - in: innerPipe, - out: new _Boolean({ - type: "boolean", - error: params.error, - }), - error: params.error, - }); - return outerPipe; -} -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - ...util.normalizeParams(_params), - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/zod.js - - -//#region src/utils/types/zod.ts -function isZodSchemaV4(schema) { - if (typeof schema !== "object" || schema === null) return false; - const obj = schema; - if (!("_zod" in obj)) return false; - const zod = obj._zod; - return typeof zod === "object" && zod !== null && "def" in zod; -} -function isZodSchemaV3(schema) { - if (typeof schema !== "object" || schema === null) return false; - const obj = schema; - if (!("_def" in obj) || "_zod" in obj) return false; - const def = obj._def; - return typeof def === "object" && def != null && "typeName" in def; -} -/** Backward compatible isZodSchema for Zod 3 */ -function isZodSchema(schema) { - if (isZodSchemaV4(schema)) console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); - return isZodSchemaV3(schema); -} -/** -* Given either a Zod schema, or plain object, determine if the input is a Zod schema. -* -* @param {unknown} input -* @returns {boolean} Whether or not the provided input is a Zod schema. -*/ -function isInteropZodSchema(input) { - if (!input) return false; - if (typeof input !== "object") return false; - if (Array.isArray(input)) return false; - if (isZodSchemaV4(input) || isZodSchemaV3(input)) return true; - return false; -} -function isZodLiteralV3(obj) { - if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodLiteral") return true; - return false; -} -function isZodLiteralV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "literal") return true; - return false; -} -/** -* Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema). -* -* @param obj The value to check. -* @returns {boolean} True if the value is a Zod v3 or v4 literal schema, false otherwise. -*/ -function isInteropZodLiteral(obj) { - if (isZodLiteralV3(obj)) return true; - if (isZodLiteralV4(obj)) return true; - return false; -} -/** -* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. -* This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {Promise>} A promise that resolves to a safe parse result object. -* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. -*/ -async function interopSafeParseAsync(schema, input) { - if (isZodSchemaV4(schema)) try { - const data = await parseAsync(schema, input); - return { - success: true, - data - }; - } catch (error) { - return { - success: false, - error - }; - } - if (isZodSchemaV3(schema)) return await schema.safeParseAsync(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. -* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {Promise} A promise that resolves to the parsed value. -* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. -*/ -async function interopParseAsync(schema, input) { - if (isZodSchemaV4(schema)) return await parseAsync(schema, input); - if (isZodSchemaV3(schema)) return await schema.parseAsync(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object -* indicating success or failure. This function is compatible with both Zod v3 and v4 schemas. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {InteropZodSafeParseResult} An object with either the parsed data (on success) -* or the error (on failure). -* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. -*/ -function interopSafeParse(schema, input) { - if (isZodSchemaV4(schema)) try { - const data = parse_parse(schema, input); - return { - success: true, - data - }; - } catch (error) { - return { - success: false, - error - }; - } - if (isZodSchemaV3(schema)) return schema.safeParse(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. -* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {T} The parsed value. -* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. -*/ -function interopParse(schema, input) { - if (isZodSchemaV4(schema)) return parse_parse(schema, input); - if (isZodSchemaV3(schema)) return schema.parse(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Retrieves the description from a schema definition (v3, v4, or plain object), if available. -* -* @param {unknown} schema - The schema to extract the description from. -* @returns {string | undefined} The description of the schema, or undefined if not present. -*/ -function getSchemaDescription(schema) { - if (isZodSchemaV4(schema)) return globalRegistry.get(schema)?.description; - if (isZodSchemaV3(schema)) return schema.description; - if ("description" in schema && typeof schema.description === "string") return schema.description; - return void 0; -} -/** -* Determines if the provided Zod schema is "shapeless". -* A shapeless schema is one that does not define any object shape, -* such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. -* For ZodObject, it must have no shape keys to be considered shapeless. -* ZodRecord schemas are considered shapeless since they define dynamic -* key-value mappings without fixed keys. -* -* @param schema The Zod schema to check. -* @returns {boolean} True if the schema is shapeless, false otherwise. -*/ -function isShapelessZodSchema(schema) { - if (!isInteropZodSchema(schema)) return false; - if (isZodSchemaV3(schema)) { - const def = schema._def; - if (def.typeName === "ZodObject") { - const obj = schema; - return !obj.shape || Object.keys(obj.shape).length === 0; - } - if (def.typeName === "ZodRecord") return true; - } - if (isZodSchemaV4(schema)) { - const def = schema._zod.def; - if (def.type === "object") { - const obj = schema; - return !obj.shape || Object.keys(obj.shape).length === 0; - } - if (def.type === "record") return true; - } - if (typeof schema === "object" && schema !== null && !("shape" in schema)) return true; - return false; -} -/** -* Determines if the provided Zod schema should be treated as a simple string schema -* that maps to DynamicTool. This aligns with the type-level constraint of -* InteropZodType which only matches basic string schemas. -* If the provided schema is just z.string(), we can make the determination that -* the tool is just a generic string tool that doesn't require any input validation. -* -* This function only returns true for basic ZodString schemas, including: -* - Basic string schemas (z.string()) -* - String schemas with validations (z.string().min(1), z.string().email(), etc.) -* -* This function returns false for everything else, including: -* - String schemas with defaults (z.string().default("value")) -* - Branded string schemas (z.string().brand<"UserId">()) -* - String schemas with catch operations (z.string().catch("default")) -* - Optional/nullable string schemas (z.string().optional()) -* - Transformed schemas (z.string().transform() or z.object().transform()) -* - Object or record schemas, even if they're empty -* - Any other schema type -* -* @param schema The Zod schema to check. -* @returns {boolean} True if the schema is a basic ZodString, false otherwise. -*/ -function isSimpleStringZodSchema(schema) { - if (!isInteropZodSchema(schema)) return false; - if (isZodSchemaV3(schema)) { - const def = schema._def; - return def.typeName === "ZodString"; - } - if (isZodSchemaV4(schema)) { - const def = schema._zod.def; - return def.type === "string"; - } - return false; -} -function isZodObjectV3(obj) { - if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") return true; - return false; -} -function isZodObjectV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") return true; - return false; -} -function isZodArrayV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") return true; - return false; -} -/** -* Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). -* -* @param obj The value to check. -* @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. -*/ -function isInteropZodObject(obj) { - if (isZodObjectV3(obj)) return true; - if (isZodObjectV4(obj)) return true; - return false; -} -/** -* Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @returns {InteropZodObjectShape} The shape of the object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function getInteropZodObjectShape(schema) { - if (isZodSchemaV3(schema)) return schema.shape; - if (isZodSchemaV4(schema)) return schema._zod.def.shape; - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Extends a Zod object schema with additional fields, supporting both Zod v3 and v4. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {InteropZodObjectShape} extension - The fields to add to the schema. -* @returns {InteropZodObject} The extended Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function extendInteropZodObject(schema, extension) { - if (isZodSchemaV3(schema)) return schema.extend(extension); - if (isZodSchemaV4(schema)) return extend(schema, extension); - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a partial version of a Zod object schema, making all fields optional. -* Supports both Zod v3 and v4. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @returns {InteropZodObject} The partial Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectPartial(schema) { - if (isZodSchemaV3(schema)) return schema.partial(); - if (isZodSchemaV4(schema)) return partial($ZodOptional, schema, void 0); - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a strict version of a Zod object schema, disallowing unknown keys. -* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness -* recursively to all nested object schemas and arrays of object schemas. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays. -* @returns {InteropZodObject} The strict Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectStrict(schema, recursive = false) { - if (isZodSchemaV3(schema)) return schema.strict(); - if (isZodObjectV4(schema)) { - const outputShape = schema._zod.def.shape; - if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { - if (isZodObjectV4(keySchema)) { - const outputSchema = interopZodObjectStrict(keySchema, recursive); - outputShape[key] = outputSchema; - } else if (isZodArrayV4(keySchema)) { - let elementSchema = keySchema._zod.def.element; - if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectStrict(elementSchema, recursive); - outputShape[key] = clone(keySchema, { - ...keySchema._zod.def, - element: elementSchema - }); - } else outputShape[key] = keySchema; - const meta$1 = globalRegistry.get(keySchema); - if (meta$1) globalRegistry.add(outputShape[key], meta$1); - } - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape, - catchall: _never($ZodNever) - }); - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(modifiedSchema, meta); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a passthrough version of a Zod object schema, allowing unknown keys. -* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough -* recursively to all nested object schemas and arrays of object schemas. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays. -* @returns {InteropZodObject} The passthrough Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectPassthrough(schema, recursive = false) { - if (isZodObjectV3(schema)) return schema.passthrough(); - if (isZodObjectV4(schema)) { - const outputShape = schema._zod.def.shape; - if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { - if (isZodObjectV4(keySchema)) { - const outputSchema = interopZodObjectPassthrough(keySchema, recursive); - outputShape[key] = outputSchema; - } else if (isZodArrayV4(keySchema)) { - let elementSchema = keySchema._zod.def.element; - if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectPassthrough(elementSchema, recursive); - outputShape[key] = clone(keySchema, { - ...keySchema._zod.def, - element: elementSchema - }); - } else outputShape[key] = keySchema; - const meta$1 = globalRegistry.get(keySchema); - if (meta$1) globalRegistry.add(outputShape[key], meta$1); - } - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape, - catchall: _unknown($ZodUnknown) - }); - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(modifiedSchema, meta); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a getter function for the default value of a Zod schema, if one is defined. -* Supports both Zod v3 and v4 schemas. If the schema has a default value, -* the returned function will return that value when called. If no default is defined, -* returns undefined. -* -* @template T - The type of the Zod schema. -* @param {T} schema - The Zod schema instance (either v3 or v4). -* @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set. -*/ -function getInteropZodDefaultGetter(schema) { - if (isZodSchemaV3(schema)) try { - const defaultValue = schema.parse(void 0); - return () => defaultValue; - } catch { - return void 0; - } - if (isZodSchemaV4(schema)) try { - const defaultValue = parse_parse(schema, void 0); - return () => defaultValue; - } catch { - return void 0; - } - return void 0; -} -function isZodTransformV3(schema) { - return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; -} -function isZodTransformV4(schema) { - return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; -} -/** -* Returns the input type of a Zod transform schema, for both v3 and v4. -* If the schema is not a transform, returns undefined. If `recursive` is true, -* recursively processes nested object schemas and arrays of object schemas. -* -* @param schema - The Zod schema instance (v3 or v4) -* @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays. -* @returns The input Zod schema of the transform, or undefined if not a transform -*/ -function interopZodTransformInputSchema(schema, recursive = false) { - if (isZodSchemaV3(schema)) { - if (isZodTransformV3(schema)) return interopZodTransformInputSchema(schema._def.schema, recursive); - return schema; - } - if (isZodSchemaV4(schema)) { - let outputSchema = schema; - if (isZodTransformV4(schema)) outputSchema = interopZodTransformInputSchema(schema._zod.def.in, recursive); - if (recursive) { - if (isZodObjectV4(outputSchema)) { - const outputShape = outputSchema._zod.def.shape; - for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) outputShape[key] = interopZodTransformInputSchema(keySchema, recursive); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - shape: outputShape - }); - } else if (isZodArrayV4(outputSchema)) { - const elementSchema = interopZodTransformInputSchema(outputSchema._zod.def.element, recursive); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - element: elementSchema - }); - } - } - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(outputSchema, meta); - return outputSchema; - } - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Creates a modified version of a Zod object schema where fields matching a predicate are made optional. -* Supports both Zod v3 and v4 schemas and preserves the original schema version. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {(key: string, value: InteropZodType) => boolean} predicate - Function to determine which fields should be optional. -* @returns {InteropZodObject} The modified Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectMakeFieldsOptional(schema, predicate) { - if (isZodSchemaV3(schema)) { - const shape = getInteropZodObjectShape(schema); - const modifiedShape = {}; - for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) modifiedShape[key] = value.optional(); - else modifiedShape[key] = value; - return schema.extend(modifiedShape); - } - if (isZodSchemaV4(schema)) { - const shape = getInteropZodObjectShape(schema); - const outputShape = { ...schema._zod.def.shape }; - for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) outputShape[key] = new $ZodOptional({ - type: "optional", - innerType: value - }); - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape - }); - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(modifiedSchema, meta); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} - -//#endregion - -//# sourceMappingURL=zod.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js -//#region src/utils/zod-to-json-schema/Options.ts -const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); -const Options_defaultOptions = { - name: void 0, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", - openAiAnyTypeName: "OpenAiAnyType" -}; -const getDefaultOptions = (options) => typeof options === "string" ? { - ...Options_defaultOptions, - name: options -} : { - ...Options_defaultOptions, - ...options -}; - -//#endregion - -//# sourceMappingURL=Options.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js - - -//#region src/utils/zod-to-json-schema/Refs.ts -const getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== void 0 ? [ - ..._options.basePath, - _options.definitionPath, - _options.name - ] : _options.basePath; - return { - ..._options, - flags: { hasReferencedOpenAiAnyType: false }, - currentPath, - propertyPath: void 0, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, { - def: def._def, - path: [ - ..._options.basePath, - _options.definitionPath, - name - ], - jsonSchema: void 0 - }])) - }; -}; - -//#endregion - -//# sourceMappingURL=Refs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js -//#region src/utils/zod-to-json-schema/getRelativePath.ts -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break; - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; - -//#endregion - -//# sourceMappingURL=getRelativePath.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js - - -//#region src/utils/zod-to-json-schema/parsers/any.ts -function parseAnyDef(refs) { - if (refs.target !== "openAi") return {}; - const anyDefinitionPath = [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ]; - refs.flags.hasReferencedOpenAiAnyType = true; - return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; -} - -//#endregion - -//# sourceMappingURL=any.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/errorMessages.js -//#region src/utils/zod-to-json-schema/errorMessages.ts -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) return; - if (errorMessage) res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage - }; -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); -} - -//#endregion - -//# sourceMappingURL=errorMessages.js.map -;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/util.js -var util_util; -(function (util) { - util.assertEqual = (_) => { }; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util_util || (util_util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -const ZodParsedType = util_util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const util_getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/ZodError.js - -const ZodIssueCode = util_util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -class ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util_util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/locales/en.js - - -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util_util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util_util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util_util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util_util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util_util.assertNever(issue); - } - return { message }; -}; -/* harmony default export */ const en = (errorMap); - -;// CONCATENATED MODULE: ./node_modules/zod/v3/errors.js - -let overrideErrorMap = en; - -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/errorUtil.js -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - // biome-ignore lint: - errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/parseUtil.js - - -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -const EMPTY_PATH = (/* unused pure expression or super */ null && ([])); -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, // contextual error map is first priority - ctx.schemaErrorMap, // then schema-bound map if available - overrideMap, // then global override map - overrideMap === en ? undefined : en, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return parseUtil_INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return parseUtil_INVALID; - if (value.status === "aborted") - return parseUtil_INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -const parseUtil_INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -const OK = (value) => ({ status: "valid", value }); -const isAborted = (x) => x.status === "aborted"; -const isDirty = (x) => x.status === "dirty"; -const isValid = (x) => x.status === "valid"; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/types.js - - - - - -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -const handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -class ZodType { - get description() { - return this._def.description; - } - _getType(input) { - return util_getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: util_getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: util_getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: util_getParsedType(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async, - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: util_getParsedType(data), - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }; - } - catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true, - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: util_getParsedType(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data), - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex; -// faster, simpler, safer -const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -// const ipv6Regex = -// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -// https://base64.guru/standards/base64url -const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -// simple -// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; -// no leap year validation -// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; -// with leap year validation -const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function types_isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - // Convert base64url to base64 - const base64 = header - .replace(/-/g, "+") - .replace(/_/g, "/") - .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } - catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "jwt") { - if (!types_isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util_util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message), - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message), - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message), - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message), - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options?.position, - ...errorUtil.errToObj(options?.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message), - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); -}; -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function types_floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / 10 ** decCount; -} -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util_util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (types_floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util_util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_util.isInteger(ch.value))); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } - catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util_util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); -}; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } -} -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_date, - }); - return parseUtil_INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util_util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); -}; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } -} -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } -} -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); -}; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } -} -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); -}; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } -} -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } -} -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); -}; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return ParseStatus.mergeArray(status, result); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } -} -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util_util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") { - } - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - for (const key of util_util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - omit(mask) { - const shape = {}; - for (const key of util_util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util_util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - required(mask) { - const newShape = {}; - for (const key of util_util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util_util.objectKeys(this.shape)); - } -} -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - // return invalid - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); - } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError(issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_INVALID; - } - } - get options() { - return this._def.options; - } -} -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } - else if (type instanceof ZodLiteral) { - return [type.value]; - } - else if (type instanceof ZodEnum) { - return type.options; - } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util_util.objectValues(type.enum); - } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } - else if (type instanceof ZodUndefined) { - return [undefined]; - } - else if (type instanceof ZodNull) { - return [null]; - } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } - else { - return []; - } -}; -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return parseUtil_INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); - } -} -function types_mergeValues(a, b) { - const aType = util_getParsedType(a); - const bType = util_getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } - else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util_util.objectKeys(b); - const sharedKeys = util_util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = types_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = types_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } - else { - return { valid: false }; - } -} -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return parseUtil_INVALID; - } - const merged = types_mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types, - }); - return parseUtil_INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } - } -} -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); -}; -// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return parseUtil_INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } - else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); - } -} -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); -}; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); - } -} -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); -}; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return parseUtil_INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); -}; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(async function (...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); - } -} -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return parseUtil_INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); -} -class ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util_util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return parseUtil_INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, - }); - } -} -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - _parse(input) { - const nativeEnumValues = util_util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util_util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util_util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return parseUtil_INVALID; - } - if (!this._cache) { - this._cache = new Set(util_util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util_util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } -} -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return parseUtil_INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return parseUtil_INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return parseUtil_INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return parseUtil_INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!isValid(base)) - return parseUtil_INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return parseUtil_INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result, - })); - }); - } - } - util_util.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; - -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); -}; -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return parseUtil_INVALID; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -const BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } -} -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } -} -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r) => { - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} - -const late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// requires TS 4.4+ -class types_Class { - constructor(..._) { } -} -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -const stringType = ZodString.create; -const numberType = ZodNumber.create; -const nanType = ZodNaN.create; -const bigIntType = ZodBigInt.create; -const booleanType = ZodBoolean.create; -const dateType = ZodDate.create; -const symbolType = ZodSymbol.create; -const undefinedType = ZodUndefined.create; -const nullType = ZodNull.create; -const anyType = ZodAny.create; -const unknownType = ZodUnknown.create; -const neverType = ZodNever.create; -const voidType = ZodVoid.create; -const arrayType = ZodArray.create; -const objectType = ZodObject.create; -const strictObjectType = ZodObject.strictCreate; -const unionType = ZodUnion.create; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -const intersectionType = ZodIntersection.create; -const tupleType = ZodTuple.create; -const recordType = ZodRecord.create; -const mapType = ZodMap.create; -const setType = ZodSet.create; -const functionType = ZodFunction.create; -const lazyType = ZodLazy.create; -const literalType = ZodLiteral.create; -const enumType = ZodEnum.create; -const nativeEnumType = ZodNativeEnum.create; -const promiseType = ZodPromise.create; -const effectsType = ZodEffects.create; -const optionalType = ZodOptional.create; -const nullableType = ZodNullable.create; -const preprocessType = ZodEffects.createWithPreprocess; -const pipelineType = ZodPipeline.create; -const ostring = () => stringType().optional(); -const onumber = () => numberType().optional(); -const oboolean = () => booleanType().optional(); -const coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; - -const types_NEVER = (/* unused pure expression or super */ null && (INVALID)); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js - - - - -//#region src/utils/zod-to-json-schema/parsers/array.ts -function parseArrayDef(def, refs) { - const res = { type: "array" }; - if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - if (def.minLength) setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); - if (def.maxLength) setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; -} - -//#endregion - -//# sourceMappingURL=array.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/bigint.js - - -//#region src/utils/zod-to-json-schema/parsers/bigint.ts -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64" - }; - if (!def.checks) return res; - for (const check of def.checks) switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMinimum = true; - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMaximum = true; - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - return res; -} - -//#endregion - -//# sourceMappingURL=bigint.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js -//#region src/utils/zod-to-json-schema/parsers/boolean.ts -function parseBooleanDef() { - return { type: "boolean" }; -} - -//#endregion - -//# sourceMappingURL=boolean.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js - - -//#region src/utils/zod-to-json-schema/parsers/branded.ts -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); -} - -//#endregion - -//# sourceMappingURL=branded.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js - - -//#region src/utils/zod-to-json-schema/parsers/catch.ts -const parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -//#endregion - -//# sourceMappingURL=catch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js - - -//#region src/utils/zod-to-json-schema/parsers/date.ts -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; - switch (strategy) { - case "string": - case "format:date-time": return { - type: "string", - format: "date-time" - }; - case "format:date": return { - type: "string", - format: "date" - }; - case "integer": return integerDateParser(def, refs); - } -} -const integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time" - }; - if (refs.target === "openApi3") return res; - for (const check of def.checks) switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - break; - } - return res; -}; - -//#endregion - -//# sourceMappingURL=date.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js - - -//#region src/utils/zod-to-json-schema/parsers/default.ts -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue() - }; -} - -//#endregion - -//# sourceMappingURL=default.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js - - - -//#region src/utils/zod-to-json-schema/parsers/effects.ts -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); -} - -//#endregion - -//# sourceMappingURL=effects.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js -//#region src/utils/zod-to-json-schema/parsers/enum.ts -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values) - }; -} - -//#endregion - -//# sourceMappingURL=enum.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js - - -//#region src/utils/zod-to-json-schema/parsers/intersection.ts -const isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") return false; - return "allOf" in type; -}; -function parseIntersectionDef(def, refs) { - const allOf = [parseDef(def.left._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "0" - ] - }), parseDef(def.right._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "1" - ] - })].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; - const mergedAllOf = []; - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0; - } else { - let nestedSchema = schema; - if ("additionalProperties" in schema && schema.additionalProperties === false) { - const { additionalProperties,...rest } = schema; - nestedSchema = rest; - } else unevaluatedProperties = void 0; - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length ? { - allOf: mergedAllOf, - ...unevaluatedProperties - } : void 0; -} - -//#endregion - -//# sourceMappingURL=intersection.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/literal.js -//#region src/utils/zod-to-json-schema/parsers/literal.ts -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" }; - if (refs.target === "openApi3") return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value] - }; - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value - }; -} - -//#endregion - -//# sourceMappingURL=literal.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js - - -//#region src/utils/zod-to-json-schema/parsers/string.ts -let string_emojiRegex = void 0; -/** -* Generated from the regular expressions found here as of 2024-05-22: -* https://github.com/colinhacks/zod/blob/master/src/types.ts. -* -* Expressions with /i flag have been changed accordingly. -*/ -const zodPatterns = { - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - emoji: () => { - if (string_emojiRegex === void 0) string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - return string_emojiRegex; - }, - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ -}; -function parseStringDef(def, refs) { - const res = { type: "string" }; - if (def.checks) for (const check of def.checks) switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex, check.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "date": - addFormat(res, "date", check.message, refs); - break; - case "time": - addFormat(res, "time", check.message, refs); - break; - case "duration": - addFormat(res, "duration", check.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "includes": - addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); - break; - case "ip": - if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs); - if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs); - break; - case "base64url": - addPattern(res, zodPatterns.base64url, check.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check.message, refs); - break; - case "cidr": - if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); - if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); - break; - case "emoji": - addPattern(res, zodPatterns.emoji(), check.message, refs); - break; - case "ulid": - addPattern(res, zodPatterns.ulid, check.message, refs); - break; - case "base64": - switch (refs.base64Strategy) { - case "format:binary": - addFormat(res, "binary", check.message, refs); - break; - case "contentEncoding:base64": - setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.base64, check.message, refs); - break; - } - break; - case "nanoid": - addPattern(res, zodPatterns.nanoid, check.message, refs); - break; - case "toLowerCase": - case "toUpperCase": - case "trim": break; - default: - /* c8 ignore next */ - ((_) => {})(check); - } - return res; -} -function escapeLiteralCheckValue(literal, refs) { - return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; -} -const ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i = 0; i < source.length; i++) { - if (!ALPHA_NUMERIC.has(source[i])) result += "\\"; - result += source[i]; - } - return result; -} -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) schema.anyOf = []; - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; - } - } - schema.anyOf.push({ - format: value, - ...message && refs.errorMessages && { errorMessage: { format: message } } - }); - } else setResponseValueAndErrors(schema, "format", value, message, refs); -} -function addPattern(schema, regex, message, refs) { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) schema.allOf = []; - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; - } - } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...message && refs.errorMessages && { errorMessage: { pattern: message } } - }); - } else setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); -} -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) return regex.source; - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s") - }; - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } else pattern += `${source[i]}${source[i].toUpperCase()}`; - continue; - } - } else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i] === "^") { - pattern += `(^|(?<=[\r\n]))`; - continue; - } else if (source[i] === "$") { - pattern += `($|(?=[\r\n]))`; - continue; - } - } - if (flags.s && source[i] === ".") { - pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; - continue; - } - pattern += source[i]; - if (source[i] === "\\") isEscaped = true; - else if (inCharGroup && source[i] === "]") inCharGroup = false; - else if (!inCharGroup && source[i] === "[") inCharGroup = true; - } - try { - new RegExp(pattern); - } catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -} - -//#endregion - -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js - - - - - - -//#region src/utils/zod-to-json-schema/parsers/record.ts -function parseRecordDef(def, refs) { - if (refs.target === "openAi") console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "properties", - key - ] - }) ?? parseAnyDef(refs) - }), {}), - additionalProperties: refs.rejectedAdditionalProperties - }; - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? refs.allowedAdditionalProperties - }; - if (refs.target === "openApi3") return schema; - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const { type,...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { - ...schema, - propertyNames: { enum: def.keyType._def.values } - }; - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { - const { type,...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } - return schema; -} - -//#endregion - -//# sourceMappingURL=record.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js - - - - -//#region src/utils/zod-to-json-schema/parsers/map.ts -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") return parseRecordDef(def, refs); - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - "items", - "0" - ] - }) || parseAnyDef(refs); - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - "items", - "1" - ] - }) || parseAnyDef(refs); - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2 - } - }; -} - -//#endregion - -//# sourceMappingURL=map.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js -//#region src/utils/zod-to-json-schema/parsers/nativeEnum.ts -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], - enum: actualValues - }; -} - -//#endregion - -//# sourceMappingURL=nativeEnum.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js - - -//#region src/utils/zod-to-json-schema/parsers/never.ts -function parseNeverDef(refs) { - return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ - ...refs, - currentPath: [...refs.currentPath, "not"] - }) }; -} - -//#endregion - -//# sourceMappingURL=never.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js -//#region src/utils/zod-to-json-schema/parsers/null.ts -function parseNullDef(refs) { - return refs.target === "openApi3" ? { - enum: ["null"], - nullable: true - } : { type: "null" }; -} - -//#endregion - -//# sourceMappingURL=null.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js - - -//#region src/utils/zod-to-json-schema/parsers/union.ts -const primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null" -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { - const types = options.reduce((types$1, x) => { - const type = primitiveMappings[x._def.typeName]; - return type && !types$1.includes(type) ? [...types$1, type] : types$1; - }, []); - return { type: types.length > 1 ? types : types[0] }; - } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": return [...acc, type]; - case "bigint": return [...acc, "integer"]; - case "object": - if (x._def.value === null) return [...acc, "null"]; - return acc; - case "symbol": - case "undefined": - case "function": - default: return acc; - } - }, []); - if (types.length === options.length) { - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []) - }; - } - } else if (options.every((x) => x._def.typeName === "ZodEnum")) return { - type: "string", - enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x$1) => !acc.includes(x$1))], []) - }; - return asAnyOf(def, refs); -} -const asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - `${i}` - ] - })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); - return anyOf.length ? { anyOf } : void 0; -}; - -//#endregion - -//# sourceMappingURL=union.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nullable.js - - - -//#region src/utils/zod-to-json-schema/parsers/nullable.ts -function parseNullableDef(def, refs) { - if ([ - "ZodString", - "ZodNumber", - "ZodBigInt", - "ZodBoolean", - "ZodNull" - ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true - }; - return { type: [primitiveMappings[def.innerType._def.typeName], "null"] }; - } - if (refs.target === "openApi3") { - const base$1 = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath] - }); - if (base$1 && "$ref" in base$1) return { - allOf: [base$1], - nullable: true - }; - return base$1 && { - ...base$1, - nullable: true - }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - "0" - ] - }); - return base && { anyOf: [base, { type: "null" }] }; -} - -//#endregion - -//# sourceMappingURL=nullable.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/number.js - - -//#region src/utils/zod-to-json-schema/parsers/number.ts -function parseNumberDef(def, refs) { - const res = { type: "number" }; - if (!def.checks) return res; - for (const check of def.checks) switch (check.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMinimum = true; - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMaximum = true; - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - return res; -} - -//#endregion - -//# sourceMappingURL=number.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js - - -//#region src/utils/zod-to-json-schema/parsers/object.ts -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {} - }; - const required = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === void 0 || propDef._def === void 0) continue; - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef._def.typeName === "ZodOptional") propDef = propDef._def.innerType; - if (!propDef.isNullable()) propDef = propDef.nullable(); - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "properties", - propName - ], - propertyPath: [ - ...refs.currentPath, - "properties", - propName - ] - }); - if (parsedDef === void 0) continue; - result.properties[propName] = parsedDef; - if (!propOptional) required.push(propName); - } - if (required.length) result.required = required; - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== void 0) result.additionalProperties = additionalProperties; - return result; -} -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }); - switch (def.unknownKeys) { - case "passthrough": return refs.allowedAdditionalProperties; - case "strict": return refs.rejectedAdditionalProperties; - case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; - } -} -function safeIsOptional(schema) { - try { - return schema.isOptional(); - } catch { - return true; - } -} - -//#endregion - -//# sourceMappingURL=object.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js - - - -//#region src/utils/zod-to-json-schema/parsers/optional.ts -const parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs); - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - "1" - ] - }); - return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs); -}; - -//#endregion - -//# sourceMappingURL=optional.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js - - -//#region src/utils/zod-to-json-schema/parsers/pipeline.ts -const parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs); - else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs); - const a = parseDef(def.in._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "0" - ] - }); - const b = parseDef(def.out._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - a ? "1" : "0" - ] - }); - return { allOf: [a, b].filter((x) => x !== void 0) }; -}; - -//#endregion - -//# sourceMappingURL=pipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js - - -//#region src/utils/zod-to-json-schema/parsers/promise.ts -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); -} - -//#endregion - -//# sourceMappingURL=promise.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js - - - -//#region src/utils/zod-to-json-schema/parsers/set.ts -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - const schema = { - type: "array", - uniqueItems: true, - items - }; - if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - return schema; -} - -//#endregion - -//# sourceMappingURL=set.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js - - -//#region src/utils/zod-to-json-schema/parsers/tuple.ts -function parseTupleDef(def, refs) { - if (def.rest) return { - type: "array", - minItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - `${i}` - ] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"] - }) - }; - else return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - `${i}` - ] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) - }; -} - -//#endregion - -//# sourceMappingURL=tuple.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js - - -//#region src/utils/zod-to-json-schema/parsers/undefined.ts -function parseUndefinedDef(refs) { - return { not: parseAnyDef(refs) }; -} - -//#endregion - -//# sourceMappingURL=undefined.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js - - -//#region src/utils/zod-to-json-schema/parsers/unknown.ts -function parseUnknownDef(refs) { - return parseAnyDef(refs); -} - -//#endregion - -//# sourceMappingURL=unknown.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js - - -//#region src/utils/zod-to-json-schema/parsers/readonly.ts -const parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -//#endregion - -//# sourceMappingURL=readonly.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//#region src/utils/zod-to-json-schema/selectParser.ts -const selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs); - case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; - case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs); - case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs); - case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs); - case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: return void 0; - default: - /* c8 ignore next */ - return ((_) => void 0)(typeName); - } -}; - -//#endregion - -//# sourceMappingURL=selectParser.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js - - - - - -//#region src/utils/zod-to-json-schema/parseDef.ts -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) return overrideResult; - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== void 0) return seenSchema; - } - const newItem = { - def, - path: refs.currentPath, - jsonSchema: void 0 - }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; - if (jsonSchema) addMeta(def, refs, jsonSchema); - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -const get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": return { $ref: item.path.join("/") }; - case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": - if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return parseAnyDef(refs); - } - return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; - } -}; -const addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) jsonSchema.markdownDescription = def.description; - } - return jsonSchema; -}; - -//#endregion - -//# sourceMappingURL=parseDef.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js - - - - -//#region src/utils/zod-to-json-schema/zodToJsonSchema.ts -const zodToJsonSchema_zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name$1, schema$1]) => ({ - ...acc, - [name$1]: parseDef(schema$1._def, { - ...refs, - currentPath: [ - ...refs.basePath, - refs.definitionPath, - name$1 - ] - }, true) ?? parseAnyDef(refs) - }), {}) : void 0; - const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; - const main = parseDef(schema._def, name === void 0 ? refs : { - ...refs, - currentPath: [ - ...refs.basePath, - refs.definitionPath, - name - ] - }, false) ?? parseAnyDef(refs); - const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; - if (title !== void 0) main.title = title; - if (refs.flags.hasReferencedOpenAiAnyType) { - if (!definitions) definitions = {}; - if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = { - type: [ - "string", - "number", - "integer", - "boolean", - "array", - "null" - ], - items: { $ref: refs.$refStrategy === "relative" ? "1" : [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ].join("/") } - }; - } - const combined = name === void 0 ? definitions ? { - ...main, - [refs.definitionPath]: definitions - } : main : { - $ref: [ - ...refs.$refStrategy === "relative" ? [] : refs.basePath, - refs.definitionPath, - name - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main - } - }; - if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#"; - else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - return combined; -}; - -//#endregion - -//# sourceMappingURL=zodToJsonSchema.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/to-json-schema.js - - -class JSONSchemaGenerator { - constructor(params) { - this.counter = 0; - this.metadataRegistry = params?.metadata ?? globalRegistry; - this.target = params?.target ?? "draft-2020-12"; - this.unrepresentable = params?.unrepresentable ?? "throw"; - this.override = params?.override ?? (() => { }); - this.io = params?.io ?? "output"; - this.seen = new Map(); - } - process(schema, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set - }; - // check for schema in seens - const seen = this.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - this.seen.set(schema, result); - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - const parent = schema._zod.parent; - if (parent) { - // schema was cloned from another schema - result.ref = parent; - this.process(parent, params); - this.seen.get(parent).isParent = true; - } - else { - const _json = result.schema; - switch (def.type) { - case "string": { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json.pattern = regexes[0].source; - else if (regexes.length > 1) { - result.schema.allOf = [ - ...regexes.map((regex) => ({ - ...(this.target === "draft-7" ? { type: "string" } : {}), - pattern: regex.source, - })), - ]; - } - } - break; - } - case "number": { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - if (typeof exclusiveMinimum === "number") - json.exclusiveMinimum = exclusiveMinimum; - if (typeof minimum === "number") { - json.minimum = minimum; - if (typeof exclusiveMinimum === "number") { - if (exclusiveMinimum >= minimum) - delete json.minimum; - else - delete json.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") - json.exclusiveMaximum = exclusiveMaximum; - if (typeof maximum === "number") { - json.maximum = maximum; - if (typeof exclusiveMaximum === "number") { - if (exclusiveMaximum <= maximum) - delete json.maximum; - else - delete json.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json.multipleOf = multipleOf; - break; - } - case "boolean": { - const json = _json; - json.type = "boolean"; - break; - } - case "bigint": { - if (this.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } - break; - } - case "symbol": { - if (this.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } - break; - } - case "null": { - _json.type = "null"; - break; - } - case "any": { - break; - } - case "unknown": { - break; - } - case "undefined": { - if (this.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } - break; - } - case "void": { - if (this.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } - break; - } - case "never": { - _json.not = {}; - break; - } - case "date": { - if (this.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } - break; - } - case "array": { - const json = _json; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); - break; - } - case "object": { - const json = _json; - json.type = "object"; - json.properties = {}; - const shape = def.shape; // params.shapeCache.get(schema)!; - for (const key in shape) { - json.properties[key] = this.process(shape[key], { - ...params, - path: [...params.path, "properties", key], - }); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - // const optionalKeys = new Set(def.optional); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (this.io === "input") { - return v.optin === undefined; - } - else { - return v.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (this.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = this.process(def.catchall, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - break; - } - case "union": { - const json = _json; - json.anyOf = def.options.map((x, i) => this.process(x, { - ...params, - path: [...params.path, "anyOf", i], - })); - break; - } - case "intersection": { - const json = _json; - const a = this.process(def.left, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = this.process(def.right, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - break; - } - case "tuple": { - const json = _json; - json.type = "array"; - const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); - if (this.target === "draft-2020-12") { - json.prefixItems = prefixItems; - } - else { - json.items = prefixItems; - } - if (def.rest) { - const rest = this.process(def.rest, { - ...params, - path: [...params.path, "items"], - }); - if (this.target === "draft-2020-12") { - json.items = rest; - } - else { - json.additionalItems = rest; - } - } - // additionalItems - if (def.rest) { - json.items = this.process(def.rest, { - ...params, - path: [...params.path, "items"], - }); - } - // length - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - break; - } - case "record": { - const json = _json; - json.type = "object"; - json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); - json.additionalProperties = this.process(def.valueType, { - ...params, - path: [...params.path, "additionalProperties"], - }); - break; - } - case "map": { - if (this.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } - break; - } - case "set": { - if (this.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } - break; - } - case "enum": { - const json = _json; - const values = getEnumValues(def.entries); - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; - break; - } - case "literal": { - const json = _json; - const vals = []; - for (const val of def.values) { - if (val === undefined) { - if (this.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } - else { - // do not add to vals - } - } - else if (typeof val === "bigint") { - if (this.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } - else { - vals.push(Number(val)); - } - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - json.const = val; - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "string"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } - break; - } - case "file": { - const json = _json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(json, file); - } - else { - json.anyOf = mime.map((m) => { - const mFile = { ...file, contentMediaType: m }; - return mFile; - }); - } - } - else { - Object.assign(json, file); - } - // if (this.unrepresentable === "throw") { - // throw new Error("File cannot be represented in JSON Schema"); - // } - break; - } - case "transform": { - if (this.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } - break; - } - case "nullable": { - const inner = this.process(def.innerType, params); - _json.anyOf = [inner, { type: "null" }]; - break; - } - case "nonoptional": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "success": { - const json = _json; - json.type = "boolean"; - break; - } - case "default": { - this.process(def.innerType, params); - result.ref = def.innerType; - _json.default = JSON.parse(JSON.stringify(def.defaultValue)); - break; - } - case "prefault": { - this.process(def.innerType, params); - result.ref = def.innerType; - if (this.io === "input") - _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); - break; - } - case "catch": { - // use conditionals - this.process(def.innerType, params); - result.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - _json.default = catchValue; - break; - } - case "nan": { - if (this.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } - break; - } - case "template_literal": { - const json = _json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - json.type = "string"; - json.pattern = pattern.source; - break; - } - case "pipe": { - const innerType = this.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; - this.process(innerType, params); - result.ref = innerType; - break; - } - case "readonly": { - this.process(def.innerType, params); - result.ref = def.innerType; - _json.readOnly = true; - break; - } - // passthrough types - case "promise": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "optional": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "lazy": { - const innerType = schema._zod.innerType; - this.process(innerType, params); - result.ref = innerType; - break; - } - case "custom": { - if (this.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } - break; - } - default: { - def; - } - } - } - } - // metadata - const meta = this.metadataRegistry.get(schema); - if (meta) - Object.assign(result.schema, meta); - if (this.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (this.io === "input" && result.schema._prefault) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from this.seen in case it was overwritten - const _result = this.seen.get(schema); - return _result.schema; - } - emit(schema, _params) { - const params = { - cycles: _params?.cycles ?? "ref", - reused: _params?.reused ?? "inline", - // unrepresentable: _params?.unrepresentable ?? "throw", - // uri: _params?.uri ?? ((id) => `${id}`), - external: _params?.external ?? undefined, - }; - // iterate over seen map; - const root = this.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // initialize result with root schema fields - // Object.assign(result, seen.cached); - // returns a ref to the schema - // defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes - // multiple schemas map to the same seen object. - // e.g. lazy - // external is configured - const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; - if (params.external) { - const externalId = params.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${this.counter++}`; - // check if schema is in the external registry - const uriGenerator = params.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - // self-contained schema - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${this.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - // stored cached version in `def` property - // remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (params.cycles === "throw") { - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of this.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (params.external) { - const ext = params.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = this.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (params.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - // flatten _refs - const flattenRef = (zodSchema, params) => { - const seen = this.seen.get(zodSchema); - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - // already seen - if (seen.ref === null) { - return; - } - // flatten ref if defined - const ref = seen.ref; - seen.ref = null; // prevent recursion - if (ref) { - flattenRef(ref, params); - // merge referenced schema into current - const refSchema = this.seen.get(ref).schema; - if (refSchema.$ref && params.target === "draft-7") { - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - Object.assign(schema, refSchema); - Object.assign(schema, _cached); // prevent overwriting any fields in the original schema - } - } - // execute overrides - if (!seen.isParent) - this.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - for (const entry of [...this.seen.entries()].reverse()) { - flattenRef(entry[0], { target: this.target }); - } - const result = {}; - if (this.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (this.target === "draft-7") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else { - console.warn(`Invalid target: ${this.target}`); - } - if (params.external?.uri) { - const id = params.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = params.external.uri(id); - } - Object.assign(result, root.def); - // build defs object - const defs = params.external?.defs ?? {}; - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } - } - // set definitions in result - if (params.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (this.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed - // each call to .emit() is functionally independent - // though the seen map is shared - return JSON.parse(JSON.stringify(result)); - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } - } -} -function toJSONSchema(input, _params) { - if (input instanceof $ZodRegistry) { - const gen = new JSONSchemaGenerator(_params); - const defs = {}; - for (const entry of input._idmap.entries()) { - const [_, schema] = entry; - gen.process(schema); - } - const schemas = {}; - const external = { - registry: input, - uri: _params?.uri, - defs, - }; - for (const entry of input._idmap.entries()) { - const [key, schema] = entry; - schemas[key] = gen.emit(schema, { - ..._params, - external, - }); - } - if (Object.keys(defs).length > 0) { - const defsSegment = gen.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - const gen = new JSONSchemaGenerator(_params); - gen.process(input); - return gen.emit(input, _params); -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const schema = _schema; - const def = schema._zod.def; - switch (def.type) { - case "string": - case "number": - case "bigint": - case "boolean": - case "date": - case "symbol": - case "undefined": - case "null": - case "any": - case "unknown": - case "never": - case "void": - case "literal": - case "enum": - case "nan": - case "file": - case "template_literal": - return false; - case "array": { - return isTransforming(def.element, ctx); - } - case "object": { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - case "union": { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - case "intersection": { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - case "tuple": { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - case "record": { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - case "map": { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - case "set": { - return isTransforming(def.valueType, ctx); - } - // inner types - case "promise": - case "optional": - case "nonoptional": - case "nullable": - case "readonly": - return isTransforming(def.innerType, ctx); - case "lazy": - return isTransforming(def.getter(), ctx); - case "default": { - return isTransforming(def.innerType, ctx); - } - case "prefault": { - return isTransforming(def.innerType, ctx); - } - case "custom": { - return false; - } - case "transform": { - return true; - } - case "pipe": { - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - case "success": { - return false; - } - case "catch": { - return false; - } - default: - def; - } - throw new Error(`Unknown schema type: ${def.type}`); -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js -function deepCompareStrict(a, b) { - const typeofa = typeof a; - if (typeofa !== typeof b) { - return false; - } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - const length = a.length; - if (length !== b.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (!deepCompareStrict(a[i], b[i])) { - return false; - } - } - return true; - } - if (typeofa === 'object') { - if (!a || !b) { - return a === b; - } - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - const length = aKeys.length; - if (length !== bKeys.length) { - return false; - } - for (const k of aKeys) { - if (!deepCompareStrict(a[k], b[k])) { - return false; - } - } - return true; - } - return a === b; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/pointer.js -function encodePointer(p) { - return encodeURI(escapePointer(p)); -} -function escapePointer(p) { - return p.replace(/~/g, '~0').replace(/\//g, '~1'); -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js - -const schemaKeyword = { - additionalItems: true, - unevaluatedItems: true, - items: true, - contains: true, - additionalProperties: true, - unevaluatedProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true -}; -const schemaArrayKeyword = { - prefixItems: true, - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; -const schemaMapKeyword = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependentSchemas: true -}; -const ignoredKeyword = { - id: true, - $id: true, - $ref: true, - $schema: true, - $anchor: true, - $vocabulary: true, - $comment: true, - default: true, - enum: true, - const: true, - required: true, - type: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; -let initialBaseURI = typeof self !== 'undefined' && - self.location && - self.location.origin !== 'null' - ? - new URL(self.location.origin + self.location.pathname + location.search) - : new URL('https://github.com/cfworker'); -function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { - if (schema && typeof schema === 'object' && !Array.isArray(schema)) { - const id = schema.$id || schema.id; - if (id) { - const url = new URL(id, baseURI.href); - if (url.hash.length > 1) { - lookup[url.href] = schema; - } - else { - url.hash = ''; - if (basePointer === '') { - baseURI = url; - } - else { - dereference(schema, lookup, baseURI); - } - } - } - } - else if (schema !== true && schema !== false) { - return lookup; - } - const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); - if (lookup[schemaURI] !== undefined) { - throw new Error(`Duplicate schema URI "${schemaURI}".`); - } - lookup[schemaURI] = schema; - if (schema === true || schema === false) { - return lookup; - } - if (schema.__absolute_uri__ === undefined) { - Object.defineProperty(schema, '__absolute_uri__', { - enumerable: false, - value: schemaURI - }); - } - if (schema.$ref && schema.__absolute_ref__ === undefined) { - const url = new URL(schema.$ref, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { - const url = new URL(schema.$recursiveRef, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_recursive_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$anchor) { - const url = new URL('#' + schema.$anchor, baseURI.href); - lookup[url.href] = schema; - } - for (let key in schema) { - if (ignoredKeyword[key]) { - continue; - } - const keyBase = `${basePointer}/${encodePointer(key)}`; - const subSchema = schema[key]; - if (Array.isArray(subSchema)) { - if (schemaArrayKeyword[key]) { - const length = subSchema.length; - for (let i = 0; i < length; i++) { - dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); - } - } - } - else if (schemaMapKeyword[key]) { - for (let subKey in subSchema) { - dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); - } - } - else { - dereference(subSchema, lookup, baseURI, keyBase); - } - } - return lookup; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js -const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; -const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; -const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; -const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; -const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; -const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; -const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; -const EMAIL = (input) => { - if (input[0] === '"') - return false; - const [name, host, ...rest] = input.split('@'); - if (!name || - !host || - rest.length !== 0 || - name.length > 64 || - host.length > 253) - return false; - if (name[0] === '.' || name.endsWith('.') || name.includes('..')) - return false; - if (!/^[a-z0-9.-]+$/i.test(host) || - !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) - return false; - return host - .split('.') - .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); -}; -const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; -const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; -const DURATION = (input) => input.length > 1 && - input.length < 80 && - (/^P\d+([.,]\d+)?W$/.test(input) || - (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && - /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); -function bind(r) { - return r.test.bind(r); -} -const format = { - date, - time: time.bind(undefined, false), - 'date-time': date_time, - duration: DURATION, - uri, - 'uri-reference': bind(URIREF), - 'uri-template': bind(URITEMPLATE), - url: bind(URL_), - email: EMAIL, - hostname: bind(HOSTNAME), - ipv4: bind(IPV4), - ipv6: bind(IPV6), - regex: regex, - uuid: bind(UUID), - 'json-pointer': bind(JSON_POINTER), - 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), - 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) -}; -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function date(str) { - const matches = str.match(DATE); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return (month >= 1 && - month <= 12 && - day >= 1 && - day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); -} -function time(full, str) { - const matches = str.match(TIME); - if (!matches) - return false; - const hour = +matches[1]; - const minute = +matches[2]; - const second = +matches[3]; - const timeZone = !!matches[5]; - return (((hour <= 23 && minute <= 59 && second <= 59) || - (hour == 23 && minute == 59 && second == 60)) && - (!full || timeZone)); -} -const DATE_TIME_SEPARATOR = /t|\s/i; -function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); -} -const NOT_URI_FRAGMENT = /\/|:/; -const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); -} -const Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str, 'u'); - return true; - } - catch (e) { - return false; - } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js -var OutputFormat; -(function (OutputFormat) { - OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; - OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; - OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; -})(OutputFormat || (OutputFormat = {})); - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js -function ucs2length(s) { - let result = 0; - let length = s.length; - let index = 0; - let charCode; - while (index < length) { - result++; - charCode = s.charCodeAt(index++); - if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) { - charCode = s.charCodeAt(index); - if ((charCode & 0xfc00) == 0xdc00) { - index++; - } - } - } - return result; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js - - - - - -function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { - if (schema === true) { - return { valid: true, errors: [] }; - } - if (schema === false) { - return { - valid: false, - errors: [ - { - instanceLocation, - keyword: 'false', - keywordLocation: instanceLocation, - error: 'False boolean schema.' - } - ] - }; - } - const rawInstanceType = typeof instance; - let instanceType; - switch (rawInstanceType) { - case 'boolean': - case 'number': - case 'string': - instanceType = rawInstanceType; - break; - case 'object': - if (instance === null) { - instanceType = 'null'; - } - else if (Array.isArray(instance)) { - instanceType = 'array'; - } - else { - instanceType = 'object'; - } - break; - default: - throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); - } - const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; - const errors = []; - if ($recursiveAnchor === true && recursiveAnchor === null) { - recursiveAnchor = schema; - } - if ($recursiveRef === '#') { - const refSchema = recursiveAnchor === null - ? lookup[__absolute_recursive_ref__] - : recursiveAnchor; - const keywordLocation = `${schemaLocation}/$recursiveRef`; - const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$recursiveRef', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); - } - } - if ($ref !== undefined) { - const uri = __absolute_ref__ || $ref; - const refSchema = lookup[uri]; - if (refSchema === undefined) { - let message = `Unresolved $ref "${$ref}".`; - if (__absolute_ref__ && __absolute_ref__ !== $ref) { - message += ` Absolute URI "${__absolute_ref__}".`; - } - message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; - throw new Error(message); - } - const keywordLocation = `${schemaLocation}/$ref`; - const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$ref', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); - } - if (draft === '4' || draft === '7') { - return { valid: errors.length === 0, errors }; - } - } - if (Array.isArray($type)) { - let length = $type.length; - let valid = false; - for (let i = 0; i < length; i++) { - if (instanceType === $type[i] || - ($type[i] === 'integer' && - instanceType === 'number' && - instance % 1 === 0 && - instance === instance)) { - valid = true; - break; - } - } - if (!valid) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` - }); - } - } - else if ($type === 'integer') { - if (instanceType !== 'number' || instance % 1 || instance !== instance) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); - } - } - else if ($type !== undefined && instanceType !== $type) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); - } - if ($const !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!deepCompareStrict(instance, $const)) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } - } - else if (instance !== $const) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } - } - if ($enum !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!$enum.some(value => deepCompareStrict(instance, value))) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - else if (!$enum.some(value => instance === value)) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - if ($not !== undefined) { - const keywordLocation = `${schemaLocation}/not`; - const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); - if (result.valid) { - errors.push({ - instanceLocation, - keyword: 'not', - keywordLocation, - error: 'Instance matched "not" schema.' - }); - } - } - let subEvaluateds = []; - if ($anyOf !== undefined) { - const keywordLocation = `${schemaLocation}/anyOf`; - const errorsLength = errors.length; - let anyValid = false; - for (let i = 0; i < $anyOf.length; i++) { - const subSchema = $anyOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - anyValid = anyValid || result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - } - if (anyValid) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'anyOf', - keywordLocation, - error: 'Instance does not match any subschemas.' - }); - } - } - if ($allOf !== undefined) { - const keywordLocation = `${schemaLocation}/allOf`; - const errorsLength = errors.length; - let allValid = true; - for (let i = 0; i < $allOf.length; i++) { - const subSchema = $allOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - allValid = allValid && result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - } - if (allValid) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'allOf', - keywordLocation, - error: `Instance does not match every subschema.` - }); - } - } - if ($oneOf !== undefined) { - const keywordLocation = `${schemaLocation}/oneOf`; - const errorsLength = errors.length; - const matches = $oneOf.filter((subSchema, i) => { - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - return result.valid; - }).length; - if (matches === 1) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'oneOf', - keywordLocation, - error: `Instance does not match exactly one subschema (${matches} matches).` - }); - } - } - if (instanceType === 'object' || instanceType === 'array') { - Object.assign(evaluated, ...subEvaluateds); - } - if ($if !== undefined) { - const keywordLocation = `${schemaLocation}/if`; - const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; - if (conditionResult) { - if ($then !== undefined) { - const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); - if (!thenResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "then" schema.` - }, ...thenResult.errors); - } - } - } - else if ($else !== undefined) { - const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); - if (!elseResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "else" schema.` - }, ...elseResult.errors); - } - } - } - if (instanceType === 'object') { - if ($required !== undefined) { - for (const key of $required) { - if (!(key in instance)) { - errors.push({ - instanceLocation, - keyword: 'required', - keywordLocation: `${schemaLocation}/required`, - error: `Instance does not have required property "${key}".` - }); - } - } - } - const keys = Object.keys(instance); - if ($minProperties !== undefined && keys.length < $minProperties) { - errors.push({ - instanceLocation, - keyword: 'minProperties', - keywordLocation: `${schemaLocation}/minProperties`, - error: `Instance does not have at least ${$minProperties} properties.` - }); - } - if ($maxProperties !== undefined && keys.length > $maxProperties) { - errors.push({ - instanceLocation, - keyword: 'maxProperties', - keywordLocation: `${schemaLocation}/maxProperties`, - error: `Instance does not have at least ${$maxProperties} properties.` - }); - } - if ($propertyNames !== undefined) { - const keywordLocation = `${schemaLocation}/propertyNames`; - for (const key in instance) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'propertyNames', - keywordLocation, - error: `Property name "${key}" does not match schema.` - }, ...result.errors); - } - } - } - if ($dependentRequired !== undefined) { - const keywordLocation = `${schemaLocation}/dependantRequired`; - for (const key in $dependentRequired) { - if (key in instance) { - const required = $dependentRequired[key]; - for (const dependantKey of required) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependentRequired', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } - } - } - if ($dependentSchemas !== undefined) { - for (const key in $dependentSchemas) { - const keywordLocation = `${schemaLocation}/dependentSchemas`; - if (key in instance) { - const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependentSchemas', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } - } - if ($dependencies !== undefined) { - const keywordLocation = `${schemaLocation}/dependencies`; - for (const key in $dependencies) { - if (key in instance) { - const propsOrSchema = $dependencies[key]; - if (Array.isArray(propsOrSchema)) { - for (const dependantKey of propsOrSchema) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } - else { - const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } - } - } - const thisEvaluated = Object.create(null); - let stop = false; - if ($properties !== undefined) { - const keywordLocation = `${schemaLocation}/properties`; - for (const key in $properties) { - if (!(key in instance)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'properties', - keywordLocation, - error: `Property "${key}" does not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if (!stop && $patternProperties !== undefined) { - const keywordLocation = `${schemaLocation}/patternProperties`; - for (const pattern in $patternProperties) { - const regex = new RegExp(pattern, 'u'); - const subSchema = $patternProperties[pattern]; - for (const key in instance) { - if (!regex.test(key)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'patternProperties', - keywordLocation, - error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` - }, ...result.errors); - } - } - } - } - if (!stop && $additionalProperties !== undefined) { - const keywordLocation = `${schemaLocation}/additionalProperties`; - for (const key in instance) { - if (thisEvaluated[key]) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalProperties', - keywordLocation, - error: `Property "${key}" does not match additional properties schema.` - }, ...result.errors); - } - } - } - else if (!stop && $unevaluatedProperties !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedProperties`; - for (const key in instance) { - if (!evaluated[key]) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - errors.push({ - instanceLocation, - keyword: 'unevaluatedProperties', - keywordLocation, - error: `Property "${key}" does not match unevaluated properties schema.` - }, ...result.errors); - } - } - } - } - } - else if (instanceType === 'array') { - if ($maxItems !== undefined && instance.length > $maxItems) { - errors.push({ - instanceLocation, - keyword: 'maxItems', - keywordLocation: `${schemaLocation}/maxItems`, - error: `Array has too many items (${instance.length} > ${$maxItems}).` - }); - } - if ($minItems !== undefined && instance.length < $minItems) { - errors.push({ - instanceLocation, - keyword: 'minItems', - keywordLocation: `${schemaLocation}/minItems`, - error: `Array has too few items (${instance.length} < ${$minItems}).` - }); - } - const length = instance.length; - let i = 0; - let stop = false; - if ($prefixItems !== undefined) { - const keywordLocation = `${schemaLocation}/prefixItems`; - const length2 = Math.min($prefixItems.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'prefixItems', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if ($items !== undefined) { - const keywordLocation = `${schemaLocation}/items`; - if (Array.isArray($items)) { - const length2 = Math.min($items.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - else { - for (; i < length; i++) { - const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if (!stop && $additionalItems !== undefined) { - const keywordLocation = `${schemaLocation}/additionalItems`; - for (; i < length; i++) { - const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalItems', - keywordLocation, - error: `Items did not match additional items schema.` - }, ...result.errors); - } - } - } - } - if ($contains !== undefined) { - if (length === 0 && $minContains === undefined) { - errors.push({ - instanceLocation, - keyword: 'contains', - keywordLocation: `${schemaLocation}/contains`, - error: `Array is empty. It must contain at least one item matching the schema.` - }); - } - else if ($minContains !== undefined && length < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array has less items (${length}) than minContains (${$minContains}).` - }); - } - else { - const keywordLocation = `${schemaLocation}/contains`; - const errorsLength = errors.length; - let contained = 0; - for (let j = 0; j < length; j++) { - const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); - if (result.valid) { - evaluated[j] = true; - contained++; - } - else { - errors.push(...result.errors); - } - } - if (contained >= ($minContains || 0)) { - errors.length = errorsLength; - } - if ($minContains === undefined && - $maxContains === undefined && - contained === 0) { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'contains', - keywordLocation, - error: `Array does not contain item matching schema.` - }); - } - else if ($minContains !== undefined && contained < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` - }); - } - else if ($maxContains !== undefined && contained > $maxContains) { - errors.push({ - instanceLocation, - keyword: 'maxContains', - keywordLocation: `${schemaLocation}/maxContains`, - error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` - }); - } - } - } - if (!stop && $unevaluatedItems !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedItems`; - for (i; i < length; i++) { - if (evaluated[i]) { - continue; - } - const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'unevaluatedItems', - keywordLocation, - error: `Items did not match unevaluated items schema.` - }, ...result.errors); - } - } - } - if ($uniqueItems) { - for (let j = 0; j < length; j++) { - const a = instance[j]; - const ao = typeof a === 'object' && a !== null; - for (let k = 0; k < length; k++) { - if (j === k) { - continue; - } - const b = instance[k]; - const bo = typeof b === 'object' && b !== null; - if (a === b || (ao && bo && deepCompareStrict(a, b))) { - errors.push({ - instanceLocation, - keyword: 'uniqueItems', - keywordLocation: `${schemaLocation}/uniqueItems`, - error: `Duplicate items at indexes ${j} and ${k}.` - }); - j = Number.MAX_SAFE_INTEGER; - k = Number.MAX_SAFE_INTEGER; - } - } - } - } - } - else if (instanceType === 'number') { - if (draft === '4') { - if ($minimum !== undefined && - (($exclusiveMinimum === true && instance <= $minimum) || - instance < $minimum)) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` - }); - } - if ($maximum !== undefined && - (($exclusiveMaximum === true && instance >= $maximum) || - instance > $maximum)) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` - }); - } - } - else { - if ($minimum !== undefined && instance < $minimum) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$minimum}.` - }); - } - if ($maximum !== undefined && instance > $maximum) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$maximum}.` - }); - } - if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMinimum', - keywordLocation: `${schemaLocation}/exclusiveMinimum`, - error: `${instance} is less than ${$exclusiveMinimum}.` - }); - } - if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMaximum', - keywordLocation: `${schemaLocation}/exclusiveMaximum`, - error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` - }); - } - } - if ($multipleOf !== undefined) { - const remainder = instance % $multipleOf; - if (Math.abs(0 - remainder) >= 1.1920929e-7 && - Math.abs($multipleOf - remainder) >= 1.1920929e-7) { - errors.push({ - instanceLocation, - keyword: 'multipleOf', - keywordLocation: `${schemaLocation}/multipleOf`, - error: `${instance} is not a multiple of ${$multipleOf}.` - }); - } - } - } - else if (instanceType === 'string') { - const length = $minLength === undefined && $maxLength === undefined - ? 0 - : ucs2length(instance); - if ($minLength !== undefined && length < $minLength) { - errors.push({ - instanceLocation, - keyword: 'minLength', - keywordLocation: `${schemaLocation}/minLength`, - error: `String is too short (${length} < ${$minLength}).` - }); - } - if ($maxLength !== undefined && length > $maxLength) { - errors.push({ - instanceLocation, - keyword: 'maxLength', - keywordLocation: `${schemaLocation}/maxLength`, - error: `String is too long (${length} > ${$maxLength}).` - }); - } - if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { - errors.push({ - instanceLocation, - keyword: 'pattern', - keywordLocation: `${schemaLocation}/pattern`, - error: `String does not match pattern.` - }); - } - if ($format !== undefined && - format[$format] && - !format[$format](instance)) { - errors.push({ - instanceLocation, - keyword: 'format', - keywordLocation: `${schemaLocation}/format`, - error: `String does not match format "${$format}".` - }); - } - } - return { valid: errors.length === 0, errors }; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js - - -class Validator { - schema; - draft; - shortCircuit; - lookup; - constructor(schema, draft = '2019-09', shortCircuit = true) { - this.schema = schema; - this.draft = draft; - this.shortCircuit = shortCircuit; - this.lookup = dereference(schema); - } - validate(instance) { - return validate_validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); - } - addSchema(schema, id) { - if (id) { - schema = { ...schema, $id: id }; - } - dereference(schema, this.lookup); - } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_schema.js - - - - - - - -//#region src/utils/json_schema.ts -var json_schema_exports = {}; -__export(json_schema_exports, { - Validator: () => Validator, - deepCompareStrict: () => deepCompareStrict, - toJsonSchema: () => toJsonSchema, - validatesOnlyStrings: () => validatesOnlyStrings -}); -/** -* Converts a Zod schema or JSON schema to a JSON schema. -* @param schema - The schema to convert. -* @returns The converted schema. -*/ -function toJsonSchema(schema) { - if (isZodSchemaV4(schema)) { - const inputSchema = interopZodTransformInputSchema(schema, true); - if (isZodObjectV4(inputSchema)) { - const strictSchema = interopZodObjectStrict(inputSchema, true); - return toJSONSchema(strictSchema); - } else return toJSONSchema(schema); - } - if (isZodSchemaV3(schema)) return zodToJsonSchema_zodToJsonSchema(schema); - return schema; -} -/** -* Validates if a JSON schema validates only strings. May return false negatives in some edge cases -* (like recursive or unresolvable refs). -* -* @param schema - The schema to validate. -* @returns `true` if the schema validates only strings, `false` otherwise. -*/ -function validatesOnlyStrings(schema) { - if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) return false; - if ("type" in schema) { - if (typeof schema.type === "string") return schema.type === "string"; - if (Array.isArray(schema.type)) return schema.type.every((t) => t === "string"); - return false; - } - if ("enum" in schema) return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); - if ("const" in schema) return typeof schema.const === "string"; - if ("allOf" in schema && Array.isArray(schema.allOf)) return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); - if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { - const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; - return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); - } - if ("not" in schema) return false; - if ("$ref" in schema && typeof schema.$ref === "string") { - const ref = schema.$ref; - const resolved = dereference(schema); - if (resolved[ref]) return validatesOnlyStrings(resolved[ref]); - return false; - } - return false; -} - -//#endregion - -//# sourceMappingURL=json_schema.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js -//#region src/runnables/utils.ts -function isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; -} -/** -* Utility to filter the root event in the streamEvents implementation. -* This is simply binding the arguments to the namespace to make save on -* a bit of typing in the streamEvents implementation. -* -* TODO: Refactor and remove. -*/ -var _RootEventFilter = class { - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - constructor(fields) { - this.includeNames = fields.includeNames; - this.includeTypes = fields.includeTypes; - this.includeTags = fields.includeTags; - this.excludeNames = fields.excludeNames; - this.excludeTypes = fields.excludeTypes; - this.excludeTags = fields.excludeTags; - } - includeEvent(event, rootType) { - let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; - const eventTags = event.tags ?? []; - if (this.includeNames !== void 0) include = include || this.includeNames.includes(event.name); - if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(rootType); - if (this.includeTags !== void 0) include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); - if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(event.name); - if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(rootType); - if (this.excludeTags !== void 0) include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } -}; - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js -//#region src/runnables/graph_mermaid.ts -function _escapeNodeLabel(nodeLabel) { - return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); -} -const MARKDOWN_SPECIAL_CHARS = [ - "*", - "_", - "`" -]; -function _generateMermaidGraphStyles(nodeColors) { - let styles = ""; - for (const [className, color] of Object.entries(nodeColors)) styles += `\tclassDef ${className} ${color};\n`; - return styles; -} -/** -* Draws a Mermaid graph using the provided graph data -*/ -function drawMermaid(nodes, edges, config) { - const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config ?? {}; - let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` : "graph TD;\n"; - if (withStyles) { - const defaultClassLabel = "default"; - const formatDict = { [defaultClassLabel]: "{0}({1})" }; - if (firstNode !== void 0) formatDict[firstNode] = "{0}([{1}]):::first"; - if (lastNode !== void 0) formatDict[lastNode] = "{0}([{1}]):::last"; - for (const [key, node] of Object.entries(nodes)) { - const nodeName = node.name.split(":").pop() ?? ""; - const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; - let finalLabel = label; - if (Object.keys(node.metadata ?? {}).length) finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join("\n")}`; - const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); - mermaidGraph += `\t${nodeLabel}\n`; - } - } - const edgeGroups = {}; - for (const edge of edges) { - const srcParts = edge.source.split(":"); - const tgtParts = edge.target.split(":"); - const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); - if (!edgeGroups[commonPrefix]) edgeGroups[commonPrefix] = []; - edgeGroups[commonPrefix].push(edge); - } - const seenSubgraphs = /* @__PURE__ */ new Set(); - function addSubgraph(edges$1, prefix) { - const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target; - if (prefix && !selfLoop) { - const subgraph = prefix.split(":").pop(); - if (seenSubgraphs.has(subgraph)) throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); - seenSubgraphs.add(subgraph); - mermaidGraph += `\tsubgraph ${subgraph}\n`; - } - for (const edge of edges$1) { - const { source, target, data, conditional } = edge; - let edgeLabel = ""; - if (data !== void 0) { - let edgeData = data; - const words = edgeData.split(" "); - if (words.length > wrapLabelNWords) edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); - edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; - } else edgeLabel = conditional ? " -.-> " : " --> "; - mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; - } - for (const nestedPrefix in edgeGroups) if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); - if (prefix && !selfLoop) mermaidGraph += " end\n"; - } - addSubgraph(edgeGroups[""] ?? [], ""); - for (const prefix in edgeGroups) if (!prefix.includes(":") && prefix !== "") addSubgraph(edgeGroups[prefix], prefix); - if (withStyles) mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); - return mermaidGraph; -} -/** -* Renders Mermaid graph using the Mermaid.INK API. -* -* @example -* ```javascript -* const image = await drawMermaidImage(mermaidSyntax, { -* backgroundColor: "white", -* imageType: "png", -* }); -* fs.writeFileSync("image.png", image); -* ``` -* -* @param mermaidSyntax - The Mermaid syntax to render. -* @param config - The configuration for the image. -* @returns The image as a Blob. -*/ -async function drawMermaidImage(mermaidSyntax, config) { - let backgroundColor = config?.backgroundColor ?? "white"; - const imageType = config?.imageType ?? "png"; - const mermaidSyntaxEncoded = btoa(mermaidSyntax); - if (backgroundColor !== void 0) { - const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; - if (!hexColorPattern.test(backgroundColor)) backgroundColor = `!${backgroundColor}`; - } - const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`; - const res = await fetch(imageUrl); - if (!res.ok) throw new Error([ - `Failed to render the graph using the Mermaid.INK API.`, - `Status code: ${res.status}`, - `Status text: ${res.statusText}` - ].join("\n")); - const content = await res.blob(); - return content; -} - -//#endregion - -//# sourceMappingURL=graph_mermaid.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js - - - - - - -//#region src/runnables/graph.ts -var graph_exports = {}; -__export(graph_exports, { Graph: () => Graph }); -function nodeDataStr(id, data) { - if (id !== void 0 && !wrapper_validate(id)) return id; - else if (isRunnableInterface(data)) try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); - } - else return data.name ?? "UnknownSchema"; -} -function nodeDataJson(node) { - if (isRunnableInterface(node.data)) return { - type: "runnable", - data: { - id: node.data.lc_id, - name: node.data.getName() - } - }; - else return { - type: "schema", - data: { - ...toJsonSchema(node.data.schema), - title: node.data.name - } - }; -} -var Graph = class Graph { - nodes = {}; - edges = []; - constructor(params) { - this.nodes = params?.nodes ?? this.nodes; - this.edges = params?.edges ?? this.edges; - } - toJSON() { - const stableNodeIds = {}; - Object.values(this.nodes).forEach((node, i) => { - stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; - }); - return { - nodes: Object.values(this.nodes).map((node) => ({ - id: stableNodeIds[node.id], - ...nodeDataJson(node) - })), - edges: this.edges.map((edge) => { - const item = { - source: stableNodeIds[edge.source], - target: stableNodeIds[edge.target] - }; - if (typeof edge.data !== "undefined") item.data = edge.data; - if (typeof edge.conditional !== "undefined") item.conditional = edge.conditional; - return item; - }) - }; - } - addNode(data, id, metadata) { - if (id !== void 0 && this.nodes[id] !== void 0) throw new Error(`Node with id ${id} already exists`); - const nodeId = id ?? v4(); - const node = { - id: nodeId, - data, - name: nodeDataStr(id, data), - metadata - }; - this.nodes[nodeId] = node; - return node; - } - removeNode(node) { - delete this.nodes[node.id]; - this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); - } - addEdge(source, target, data, conditional) { - if (this.nodes[source.id] === void 0) throw new Error(`Source node ${source.id} not in graph`); - if (this.nodes[target.id] === void 0) throw new Error(`Target node ${target.id} not in graph`); - const edge = { - source: source.id, - target: target.id, - data, - conditional - }; - this.edges.push(edge); - return edge; - } - firstNode() { - return _firstNode(this); - } - lastNode() { - return _lastNode(this); - } - /** - * Add all nodes and edges from another graph. - * Note this doesn't check for duplicates, nor does it connect the graphs. - */ - extend(graph, prefix = "") { - let finalPrefix = prefix; - const nodeIds = Object.values(graph.nodes).map((node) => node.id); - if (nodeIds.every(wrapper_validate)) finalPrefix = ""; - const prefixed = (id) => { - return finalPrefix ? `${finalPrefix}:${id}` : id; - }; - Object.entries(graph.nodes).forEach(([key, value]) => { - this.nodes[prefixed(key)] = { - ...value, - id: prefixed(key) - }; - }); - const newEdges = graph.edges.map((edge) => { - return { - ...edge, - source: prefixed(edge.source), - target: prefixed(edge.target) - }; - }); - this.edges = [...this.edges, ...newEdges]; - const first = graph.firstNode(); - const last = graph.lastNode(); - return [first ? { - id: prefixed(first.id), - data: first.data - } : void 0, last ? { - id: prefixed(last.id), - data: last.data - } : void 0]; - } - trimFirstNode() { - const firstNode = this.firstNode(); - if (firstNode && _firstNode(this, [firstNode.id])) this.removeNode(firstNode); - } - trimLastNode() { - const lastNode = this.lastNode(); - if (lastNode && _lastNode(this, [lastNode.id])) this.removeNode(lastNode); - } - /** - * Return a new graph with all nodes re-identified, - * using their unique, readable names where possible. - */ - reid() { - const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); - const nodeLabelCounts = /* @__PURE__ */ new Map(); - Object.values(nodeLabels).forEach((label) => { - nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); - }); - const getNodeId = (nodeId) => { - const label = nodeLabels[nodeId]; - if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) return label; - else return nodeId; - }; - return new Graph({ - nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), { - ...node, - id: getNodeId(id) - }])), - edges: this.edges.map((edge) => ({ - ...edge, - source: getNodeId(edge.source), - target: getNodeId(edge.target) - })) - }); - } - drawMermaid(params) { - const { withStyles, curveStyle, nodeColors = { - default: "fill:#f2f0ff,line-height:1.2", - first: "fill-opacity:0", - last: "fill:#bfb6fc" - }, wrapLabelNWords } = params ?? {}; - const graph = this.reid(); - const firstNode = graph.firstNode(); - const lastNode = graph.lastNode(); - return drawMermaid(graph.nodes, graph.edges, { - firstNode: firstNode?.id, - lastNode: lastNode?.id, - withStyles, - curveStyle, - nodeColors, - wrapLabelNWords - }); - } - async drawMermaidPng(params) { - const mermaidSyntax = this.drawMermaid(params); - return drawMermaidImage(mermaidSyntax, { backgroundColor: params?.backgroundColor }); - } -}; -/** -* Find the single node that is not a target of any edge. -* Exclude nodes/sources with ids in the exclude list. -* If there is no such node, or there are multiple, return undefined. -* When drawing the graph, this node would be the origin. -*/ -function _firstNode(graph, exclude = []) { - const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); - const found = []; - for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !targets.has(node.id)) found.push(node); - return found.length === 1 ? found[0] : void 0; -} -/** -* Find the single node that is not a source of any edge. -* Exclude nodes/targets with ids in the exclude list. -* If there is no such node, or there are multiple, return undefined. -* When drawing the graph, this node would be the destination. -*/ -function _lastNode(graph, exclude = []) { - const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); - const found = []; - for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !sources.has(node.id)) found.push(node); - return found.length === 1 ? found[0] : void 0; -} - -//#endregion - -//# sourceMappingURL=graph.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js - - - - - -//#region src/tracers/event_stream.ts -function assignName({ name, serialized }) { - if (name !== void 0) return name; - if (serialized?.name !== void 0) return serialized.name; - else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) return serialized.id[serialized.id.length - 1]; - return "Unnamed"; -} -const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; -/** -* Class that extends the `BaseTracer` class from the -* `langchain.callbacks.tracers.base` module. It represents a callback -* handler that logs the execution of runs and emits `RunLog` instances to a -* `RunLogStream`. -*/ -var EventStreamCallbackHandler = class extends BaseTracer { - autoClose = true; - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - runInfoMap = /* @__PURE__ */ new Map(); - tappedPromises = /* @__PURE__ */ new Map(); - transformStream; - writer; - receiveStream; - name = "event_stream_tracer"; - lc_prefer_streaming = true; - constructor(fields) { - super({ - _awaitHandler: true, - ...fields - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) {} - _includeRun(run) { - const runTags = run.tags ?? []; - let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; - if (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name); - if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.runType); - if (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; - if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name); - if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.runType); - if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } - async *tapOutputIterable(runId, outputStream) { - const firstChunk = await outputStream.next(); - if (firstChunk.done) return; - const runInfo = this.runInfoMap.get(runId); - if (runInfo === void 0) { - yield firstChunk.value; - return; - } - function _formatOutputChunk(eventType, data) { - if (eventType === "llm" && typeof data === "string") return new GenerationChunk({ text: data }); - return data; - } - let tappedPromise = this.tappedPromises.get(runId); - if (tappedPromise === void 0) { - let tappedPromiseResolver; - tappedPromise = new Promise((resolve) => { - tappedPromiseResolver = resolve; - }); - this.tappedPromises.set(runId, tappedPromise); - try { - const event = { - event: `on_${runInfo.runType}_stream`, - run_id: runId, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - data: {} - }; - await this.send({ - ...event, - data: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) } - }, runInfo); - yield firstChunk.value; - for await (const chunk of outputStream) { - if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") await this.send({ - ...event, - data: { chunk: _formatOutputChunk(runInfo.runType, chunk) } - }, runInfo); - yield chunk; - } - } finally { - tappedPromiseResolver?.(); - } - } else { - yield firstChunk.value; - for await (const chunk of outputStream) yield chunk; - } - } - async send(payload, run) { - if (this._includeRun(run)) await this.writer.write(payload); - } - async sendEndEvent(payload, run) { - const tappedPromise = this.tappedPromises.get(payload.run_id); - if (tappedPromise !== void 0) tappedPromise.then(() => { - this.send(payload, run); - }); - else await this.send(payload, run); - } - async onLLMStart(run) { - const runName = assignName(run); - const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: run.inputs - }; - this.runInfoMap.set(run.id, runInfo); - const eventName = `on_${runType}_start`; - await this.send({ - event: eventName, - data: { input: run.inputs }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onLLMNewToken(run, token, kwargs) { - const runInfo = this.runInfoMap.get(run.id); - let chunk; - let eventName; - if (runInfo === void 0) throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); - if (this.runInfoMap.size === 1) return; - if (runInfo.runType === "chat_model") { - eventName = "on_chat_model_stream"; - if (kwargs?.chunk === void 0) chunk = new AIMessageChunk({ - content: token, - id: `run-${run.id}` - }); - else chunk = kwargs.chunk.message; - } else if (runInfo.runType === "llm") { - eventName = "on_llm_stream"; - if (kwargs?.chunk === void 0) chunk = new GenerationChunk({ text: token }); - else chunk = kwargs.chunk; - } else throw new Error(`Unexpected run type ${runInfo.runType}`); - await this.send({ - event: eventName, - data: { chunk }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onLLMEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - let eventName; - if (runInfo === void 0) throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); - const generations = run.outputs?.generations; - let output; - if (runInfo.runType === "chat_model") { - for (const generation of generations ?? []) { - if (output !== void 0) break; - output = generation[0]?.message; - } - eventName = "on_chat_model_end"; - } else if (runInfo.runType === "llm") { - output = { - generations: generations?.map((generation) => { - return generation.map((chunk) => { - return { - text: chunk.text, - generationInfo: chunk.generationInfo - }; - }); - }), - llmOutput: run.outputs?.llmOutput ?? {} - }; - eventName = "on_llm_end"; - } else throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); - await this.sendEndEvent({ - event: eventName, - data: { - output, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onChainStart(run) { - const runName = assignName(run); - const runType = run.run_type ?? "chain"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: run.run_type - }; - let eventData = {}; - if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { - eventData = {}; - runInfo.inputs = {}; - } else if (run.inputs.input !== void 0) { - eventData.input = run.inputs.input; - runInfo.inputs = run.inputs.input; - } else { - eventData.input = run.inputs; - runInfo.inputs = run.inputs; - } - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: `on_${runType}_start`, - data: eventData, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onChainEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); - const eventName = `on_${run.run_type}_end`; - const inputs = run.inputs ?? runInfo.inputs ?? {}; - const outputs = run.outputs?.output ?? run.outputs; - const data = { - output: outputs, - input: inputs - }; - if (inputs.input && Object.keys(inputs).length === 1) { - data.input = inputs.input; - runInfo.inputs = inputs.input; - } - await this.sendEndEvent({ - event: eventName, - data, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata ?? {} - }, runInfo); - } - async onToolStart(run) { - const runName = assignName(run); - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: "tool", - inputs: run.inputs ?? {} - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_tool_start", - data: { input: run.inputs ?? {} }, - name: runName, - run_id: run.id, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onToolEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); - if (runInfo.inputs === void 0) throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); - const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output; - await this.sendEndEvent({ - event: "on_tool_end", - data: { - output, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onRetrieverStart(run) { - const runName = assignName(run); - const runType = "retriever"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: { query: run.inputs.query } - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_retriever_start", - data: { input: { query: run.inputs.query } }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onRetrieverEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); - await this.sendEndEvent({ - event: "on_retriever_end", - data: { - output: run.outputs?.documents ?? run.outputs, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async handleCustomEvent(eventName, data, runId) { - const runInfo = this.runInfoMap.get(runId); - if (runInfo === void 0) throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); - await this.send({ - event: "on_custom_event", - run_id: runId, - name: eventName, - tags: runInfo.tags, - metadata: runInfo.metadata, - data - }, runInfo); - } - async finish() { - const pendingPromises = [...this.tappedPromises.values()]; - Promise.all(pendingPromises).finally(() => { - this.writer.close(); - }); - } -}; - -//#endregion - -//# sourceMappingURL=event_stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js - - -//#region src/tracers/root_listener.ts -var RootListenersTracer = class extends BaseTracer { - name = "RootListenersTracer"; - /** The Run's ID. Type UUID */ - rootId; - config; - argOnStart; - argOnEnd; - argOnError; - constructor({ config, onStart, onEnd, onError }) { - super({ _awaitHandler: true }); - this.config = config; - this.argOnStart = onStart; - this.argOnEnd = onEnd; - this.argOnError = onError; - } - /** - * This is a legacy method only called once for an entire run tree - * therefore not useful here - * @param {Run} _ Not used - */ - persistRun(_) { - return Promise.resolve(); - } - async onRunCreate(run) { - if (this.rootId) return; - this.rootId = run.id; - if (this.argOnStart) await this.argOnStart(run, this.config); - } - async onRunUpdate(run) { - if (run.id !== this.rootId) return; - if (!run.error) { - if (this.argOnEnd) await this.argOnEnd(run, this.config); - } else if (this.argOnError) await this.argOnError(run, this.config); - } -}; - -//#endregion - -//# sourceMappingURL=root_listener.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js - - -//#region src/runnables/wrappers.ts -function convertToHttpEventStream(stream) { - const encoder = new TextEncoder(); - const finalStream = new ReadableStream({ async start(controller) { - for await (const chunk of stream) controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); - controller.enqueue(encoder.encode("event: end\n\n")); - controller.close(); - } }); - return IterableReadableStream.fromReadableStream(finalStream); -} - -//#endregion - -//# sourceMappingURL=wrappers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js - - - - -//#region src/runnables/iter.ts -function isIterableIterator(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && typeof thing.next === "function"; -} -const isIterator = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function"; -function isAsyncIterable(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; -} -function* consumeIteratorInContext(context, iter) { - while (true) { - const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(context), iter.next.bind(iter), true); - if (done) break; - else yield value; - } -} -async function* consumeAsyncIterableInContext(context, iter) { - const iterator = iter[Symbol.asyncIterator](); - while (true) { - const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(context), iterator.next.bind(iter), true); - if (done) break; - else yield value; - } -} - -//#endregion - -//# sourceMappingURL=iter.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js - - - - - - - - - - - - - - - - - - - - - -//#region src/runnables/base.ts -function base_coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -/** -* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or -* transformed. -*/ -var Runnable = class extends Serializable { - lc_runnable = true; - name; - getName(suffix) { - const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name; - return suffix ? `${name}${suffix}` : name; - } - /** - * Add retry logic to an existing runnable. - * @param fields.stopAfterAttempt The number of attempts to retry. - * @param fields.onFailedAttempt A function that is called when a retry fails. - * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. - */ - withRetry(fields) { - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - /** - * Bind config to a Runnable, returning a new Runnable. - * @param config New configuration parameters to attach to the new runnable. - * @returns A new RunnableBinding with a config matching what's passed. - */ - withConfig(config) { - return new RunnableBinding({ - bound: this, - config, - kwargs: {} - }); - } - /** - * Create a new runnable from the current one that will try invoking - * other passed fallback runnables if the initial invocation fails. - * @param fields.fallbacks Other runnables to call if the runnable errors. - * @returns A new RunnableWithFallbacks. - */ - withFallbacks(fields) { - const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; - return new RunnableWithFallbacks({ - runnable: this, - fallbacks - }); - } - _getOptionsList(options, length = 0) { - if (Array.isArray(options) && options.length !== length) throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); - if (Array.isArray(options)) return options.map(ensureConfig); - if (length > 1 && !Array.isArray(options) && options.runId) { - console.warn("Provided runId will be used only for the first element of the batch."); - const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); - return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); - } - return Array.from({ length }, () => ensureConfig(options)); - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const caller = new async_caller_AsyncCaller({ - maxConcurrency, - onFailedAttempt: (e) => { - throw e; - } - }); - const batchCalls = inputs.map((input, i) => caller.call(async () => { - try { - const result = await this.invoke(input, configList[i]); - return result; - } catch (e) { - if (batchOptions?.returnExceptions) return e; - throw e; - } - })); - return Promise.all(batchCalls); - } - /** - * Default streaming implementation. - * Subclasses should override this method if they support streaming output. - * @param input - * @param options - */ - async *_streamIterator(input, options) { - yield this.invoke(input, options); - } - /** - * Stream output in chunks. - * @param input - * @param options - * @returns A readable stream that is also an iterable. - */ - async stream(input, options) { - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this._streamIterator(input, config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - _separateRunnableConfigFromCallOptions(options) { - let runnableConfig; - if (options === void 0) runnableConfig = ensureConfig(options); - else runnableConfig = ensureConfig({ - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - runName: options.runName, - configurable: options.configurable, - recursionLimit: options.recursionLimit, - maxConcurrency: options.maxConcurrency, - runId: options.runId, - timeout: options.timeout, - signal: options.signal - }); - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - delete callOptions.runName; - delete callOptions.configurable; - delete callOptions.recursionLimit; - delete callOptions.maxConcurrency; - delete callOptions.runId; - delete callOptions.timeout; - delete callOptions.signal; - return [runnableConfig, callOptions]; - } - async _callWithConfig(func, input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName()); - delete config.runId; - let output; - try { - const promise = func.call(this, input, config, runManager); - output = await raceWithSignal(promise, options?.signal); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; - } - /** - * Internal method that handles batching and configuration for a runnable - * It takes a function, input values, and optional configuration, and - * returns a promise that resolves to the output values. - * @param func The function to be executed for each input value. - * @param input The input values to be processed. - * @param config Optional configuration for the function execution. - * @returns A promise that resolves to the output values. - */ - async _batchWithConfig(func, inputs, options, batchOptions) { - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName()); - delete optionsList[i].runId; - return handleStartRes; - })); - let outputs; - try { - const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); - outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); - } catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); - return outputs; - } - /** @internal */ - _concatOutputChunks(first, second) { - return concat(first, second); - } - /** - * Helper method to transform an Iterator of Input values into an Iterator of - * Output values, with callbacks. - * Use this to implement `stream()` or `transform()` in Runnable subclasses. - */ - async *_transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const outerThis = this; - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (finalInputSupported) if (finalInput === void 0) finalInput = chunk; - else try { - finalInput = outerThis._concatOutputChunks(finalInput, chunk); - } catch { - finalInput = void 0; - finalInputSupported = false; - } - yield chunk; - } - } - let runManager; - try { - const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName()), options?.signal, config); - delete config.runId; - runManager = pipe.setup; - const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); - let iterator = pipe.output; - if (streamEventsHandler !== void 0 && runManager !== void 0) iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); - const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); - if (streamLogHandler !== void 0 && runManager !== void 0) iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); - for await (const chunk of iterator) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - } catch (e) { - await runManager?.handleChainError(e, void 0, void 0, void 0, { inputs: base_coerceToDict(finalInput, "input") }); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: base_coerceToDict(finalInput, "input") }); - } - getGraph(_) { - const graph = new Graph(); - const inputNode = graph.addNode({ - name: `${this.getName()}Input`, - schema: anyType() - }); - const runnableNode = graph.addNode(this); - const outputNode = graph.addNode({ - name: `${this.getName()}Output`, - schema: anyType() - }); - graph.addEdge(inputNode, runnableNode); - graph.addEdge(runnableNode, outputNode); - return graph; - } - /** - * Create a new runnable sequence that runs each individual runnable in series, - * piping the output of one runnable into another runnable or runnable-like. - * @param coerceable A runnable, function, or object whose values are functions or runnables. - * @returns A new runnable sequence. - */ - pipe(coerceable) { - return new RunnableSequence({ - first: this, - last: _coerceToRunnable(coerceable) - }); - } - /** - * Pick keys from the dict output of this runnable. Returns a new runnable. - */ - pick(keys) { - return this.pipe(new RunnablePick(keys)); - } - /** - * Assigns new fields to the dict output of this runnable. Returns a new runnable. - */ - assign(mapping) { - return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); - } - /** - * Default implementation of transform, which buffers input and then calls stream. - * Subclasses should override this method if they can start producing output while - * input is still being generated. - * @param generator - * @param options - */ - async *transform(generator, options) { - let finalChunk; - for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; - else finalChunk = this._concatOutputChunks(finalChunk, chunk); - yield* this._streamIterator(finalChunk, ensureConfig(options)); - } - /** - * Stream all output from a runnable, as reported to the callback system. - * This includes all inner runs of LLMs, Retrievers, Tools, etc. - * Output is streamed as Log objects, which include a list of - * jsonpatch ops that describe how the state of the run has changed in each - * step, and the final state of the run. - * The jsonpatch ops can be applied in order to construct state. - * @param input - * @param options - * @param streamOptions - */ - async *streamLog(input, options, streamOptions) { - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "original" - }); - const config = ensureConfig(options); - yield* this._streamLog(input, logStreamCallbackHandler, config); - } - async *_streamLog(input, logStreamCallbackHandler, config) { - const { callbacks } = config; - if (callbacks === void 0) config.callbacks = [logStreamCallbackHandler]; - else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat([logStreamCallbackHandler]); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(logStreamCallbackHandler, true); - config.callbacks = copiedCallbacks; - } - const runnableStreamPromise = this.stream(input, config); - async function consumeRunnableStream() { - try { - const runnableStream = await runnableStreamPromise; - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ ops: [{ - op: "add", - path: "/streamed_output/-", - value: chunk - }] }); - await logStreamCallbackHandler.writer.write(patch); - } - } finally { - await logStreamCallbackHandler.writer.close(); - } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - try { - for await (const log of logStreamCallbackHandler) yield log; - } finally { - await runnableStreamConsumePromise; - } - } - streamEvents(input, options, streamOptions) { - let stream; - if (options.version === "v1") stream = this._streamEventsV1(input, options, streamOptions); - else if (options.version === "v2") stream = this._streamEventsV2(input, options, streamOptions); - else throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); - if (options.encoding === "text/event-stream") return convertToHttpEventStream(stream); - else return IterableReadableStream.fromAsyncGenerator(stream); - } - async *_streamEventsV2(input, options, streamOptions) { - const eventStreamer = new EventStreamCallbackHandler({ - ...streamOptions, - autoClose: false - }); - const config = ensureConfig(options); - const runId = config.runId ?? v4(); - config.runId = runId; - const callbacks = config.callbacks; - if (callbacks === void 0) config.callbacks = [eventStreamer]; - else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(eventStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(eventStreamer, true); - config.callbacks = copiedCallbacks; - } - const abortController = new AbortController(); - const outerThis = this; - async function consumeRunnableStream() { - let signal; - let listener = null; - try { - if (options?.signal) if ("any" in AbortSignal) signal = AbortSignal.any([abortController.signal, options.signal]); - else { - signal = options.signal; - listener = () => { - abortController.abort(); - }; - options.signal.addEventListener("abort", listener, { once: true }); - } - else signal = abortController.signal; - const runnableStream = await outerThis.stream(input, { - ...config, - signal - }); - const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); - for await (const _ of tappedStream) if (abortController.signal.aborted) break; - } finally { - await eventStreamer.finish(); - if (signal && listener) signal.removeEventListener("abort", listener); - } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - let firstEventSent = false; - let firstEventRunId; - try { - for await (const event of eventStreamer) { - if (!firstEventSent) { - event.data.input = input; - firstEventSent = true; - firstEventRunId = event.run_id; - yield event; - continue; - } - if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { - if (event.data?.input) delete event.data.input; - } - yield event; - } - } finally { - abortController.abort(); - await runnableStreamConsumePromise; - } - } - async *_streamEventsV1(input, options, streamOptions) { - let runLog; - let hasEncounteredStartEvent = false; - const config = ensureConfig(options); - const rootTags = config.tags ?? []; - const rootMetadata = config.metadata ?? {}; - const rootName = config.runName ?? this.getName(); - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "streaming_events" - }); - const rootEventFilter = new _RootEventFilter({ ...streamOptions }); - const logStream = this._streamLog(input, logStreamCallbackHandler, config); - for await (const log of logStream) { - if (!runLog) runLog = RunLog.fromRunLogPatch(log); - else runLog = runLog.concat(log); - if (runLog.state === void 0) throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); - if (!hasEncounteredStartEvent) { - hasEncounteredStartEvent = true; - const state$2 = { ...runLog.state }; - const event = { - run_id: state$2.id, - event: `on_${state$2.type}_start`, - name: rootName, - tags: rootTags, - metadata: rootMetadata, - data: { input } - }; - if (rootEventFilter.includeEvent(event, state$2.type)) yield event; - } - const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); - const dedupedPaths = [...new Set(paths)]; - for (const path of dedupedPaths) { - let eventType; - let data = {}; - const logEntry = runLog.state.logs[path]; - if (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = "stream"; - else eventType = "start"; - else eventType = "end"; - if (eventType === "start") { - if (logEntry.inputs !== void 0) data.input = logEntry.inputs; - } else if (eventType === "end") { - if (logEntry.inputs !== void 0) data.input = logEntry.inputs; - data.output = logEntry.final_output; - } else if (eventType === "stream") { - const chunkCount = logEntry.streamed_output.length; - if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); - data = { chunk: logEntry.streamed_output[0] }; - logEntry.streamed_output = []; - } - yield { - event: `on_${logEntry.type}_${eventType}`, - name: logEntry.name, - run_id: logEntry.id, - tags: logEntry.tags, - metadata: logEntry.metadata, - data - }; - } - const { state: state$1 } = runLog; - if (state$1.streamed_output.length > 0) { - const chunkCount = state$1.streamed_output.length; - if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state$1.name}"`); - const data = { chunk: state$1.streamed_output[0] }; - state$1.streamed_output = []; - const event = { - event: `on_${state$1.type}_stream`, - run_id: state$1.id, - tags: rootTags, - metadata: rootMetadata, - name: rootName, - data - }; - if (rootEventFilter.includeEvent(event, state$1.type)) yield event; - } - } - const state = runLog?.state; - if (state !== void 0) { - const event = { - event: `on_${state.type}_end`, - name: rootName, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - data: { output: state.final_output } - }; - if (rootEventFilter.includeEvent(event, state.type)) yield event; - } - } - static isRunnable(thing) { - return isRunnableInterface(thing); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableBinding({ - bound: this, - config: {}, - configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ - config, - onStart, - onEnd, - onError - })] })] - }); - } - /** - * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` - * which contains the runnable, name, description and schema. - * - * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. - * - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ - asTool(fields) { - return convertRunnableToTool(this, fields); - } -}; -/** -* Wraps a runnable and applies partial config upon invocation. -* -* @example -* ```typescript -* import { -* type RunnableConfig, -* RunnableLambda, -* } from "@langchain/core/runnables"; -* -* const enhanceProfile = ( -* profile: Record, -* config?: RunnableConfig -* ) => { -* if (config?.configurable?.role) { -* return { ...profile, role: config.configurable.role }; -* } -* return profile; -* }; -* -* const runnable = RunnableLambda.from(enhanceProfile); -* -* // Bind configuration to the runnable to set the user's role dynamically -* const adminRunnable = runnable.withConfig({ configurable: { role: "Admin" } }); -* const userRunnable = runnable.withConfig({ configurable: { role: "User" } }); -* -* const result1 = await adminRunnable.invoke({ -* name: "Alice", -* email: "alice@example.com" -* }); -* -* // { name: "Alice", email: "alice@example.com", role: "Admin" } -* -* const result2 = await userRunnable.invoke({ -* name: "Bob", -* email: "bob@example.com" -* }); -* -* // { name: "Bob", email: "bob@example.com", role: "User" } -* ``` -*/ -var RunnableBinding = class RunnableBinding extends Runnable { - static lc_name() { - return "RunnableBinding"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - bound; - config; - kwargs; - configFactories; - constructor(fields) { - super(fields); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - this.configFactories = fields.configFactories; - } - getName(suffix) { - return this.bound.getName(suffix); - } - async _mergeConfig(...options) { - const config = mergeConfigs(this.config, ...options); - return mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []); - } - withConfig(config) { - return new this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { - ...this.config, - ...config - } - }); - } - withRetry(fields) { - return new RunnableRetry({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - async invoke(input, options) { - return this.bound.invoke(input, await this._mergeConfig(options, this.kwargs)); - } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); - return this.bound.batch(inputs, mergedOptions, batchOptions); - } - /** @internal */ - _concatOutputChunks(first, second) { - return this.bound._concatOutputChunks(first, second); - } - async *_streamIterator(input, options) { - yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async stream(input, options) { - return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async *transform(generator, options) { - yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - streamEvents(input, options, streamOptions) { - const outerThis = this; - const generator = async function* () { - yield* outerThis.bound.streamEvents(input, { - ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), - version: options.version - }, streamOptions); - }; - return IterableReadableStream.fromAsyncGenerator(generator()); - } - static isRunnableBinding(thing) { - return thing.bound && Runnable.isRunnable(thing.bound); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableBinding({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ - config, - onStart, - onEnd, - onError - })] })] - }); - } -}; -/** -* A runnable that delegates calls to another runnable -* with each element of the input sequence. -* @example -* ```typescript -* import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; -* -* const toUpperCase = (input: string): string => input.toUpperCase(); -* const addGreeting = (input: string): string => `Hello, ${input}!`; -* -* const upperCaseLambda = RunnableLambda.from(toUpperCase); -* const greetingLambda = RunnableLambda.from(addGreeting); -* -* const chain = new RunnableEach({ -* bound: upperCaseLambda.pipe(greetingLambda), -* }); -* -* const result = await chain.invoke(["alice", "bob", "carol"]) -* -* // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] -* ``` -*/ -var RunnableEach = class RunnableEach extends Runnable { - static lc_name() { - return "RunnableEach"; - } - lc_serializable = true; - lc_namespace = ["langchain_core", "runnables"]; - bound; - constructor(fields) { - super(fields); - this.bound = fields.bound; - } - /** - * Invokes the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(inputs, config) { - return this._callWithConfig(this._invoke.bind(this), inputs, config); - } - /** - * A helper method that is used to invoke the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async _invoke(inputs, config, runManager) { - return this.bound.batch(inputs, config_patchConfig(config, { callbacks: runManager?.getChild() })); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableEach({ bound: this.bound.withListeners({ - onStart, - onEnd, - onError - }) }); - } -}; -/** -* Base class for runnables that can be retried a -* specified number of times. -* @example -* ```typescript -* import { -* RunnableLambda, -* RunnableRetry, -* } from "@langchain/core/runnables"; -* -* // Simulate an API call that fails -* const simulateApiCall = (input: string): string => { -* console.log(`Attempting API call with input: ${input}`); -* throw new Error("API call failed due to network issue"); -* }; -* -* const apiCallLambda = RunnableLambda.from(simulateApiCall); -* -* // Apply retry logic using the .withRetry() method -* const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); -* -* // Alternatively, create a RunnableRetry instance manually -* const manualRetry = new RunnableRetry({ -* bound: apiCallLambda, -* maxAttemptNumber: 3, -* config: {}, -* }); -* -* // Example invocation using the .withRetry() method -* const res = await apiCallWithRetry -* .invoke("Request 1") -* .catch((error) => { -* console.error("Failed after multiple retries:", error.message); -* }); -* -* // Example invocation using the manual retry instance -* const res2 = await manualRetry -* .invoke("Request 2") -* .catch((error) => { -* console.error("Failed after multiple retries:", error.message); -* }); -* ``` -*/ -var RunnableRetry = class extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - lc_namespace = ["langchain_core", "runnables"]; - maxAttemptNumber = 3; - onFailedAttempt = () => {}; - constructor(fields) { - super(fields); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; - } - _patchConfigForRetry(attempt, config, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0; - return config_patchConfig(config, { callbacks: runManager?.getChild(tag) }); - } - async _invoke(input, config, runManager) { - return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { - onFailedAttempt: (error) => this.onFailedAttempt(error, input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } - /** - * Method that invokes the runnable with the specified input, run manager, - * and config. It handles the retry logic by catching any errors and - * recursively invoking itself with the updated config for the next retry - * attempt. - * @param input The input for the runnable. - * @param runManager The run manager for the runnable. - * @param config The config for the runnable. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(input, config) { - return this._callWithConfig(this._invoke.bind(this), input, config); - } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; - try { - await p_retry(async (attemptNumber) => { - const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i) => inputs[i]); - const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true - }); - let firstException; - for (let i = 0; i < results.length; i += 1) { - const result = results[i]; - const resultMapIndex = remainingIndexes[i]; - if (result instanceof Error) { - if (firstException === void 0) { - firstException = result; - firstException.input = remainingInputs[i]; - } - } - resultsMap[resultMapIndex.toString()] = result; - } - if (firstException) throw firstException; - return results; - }, { - onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } catch (e) { - if (batchOptions?.returnExceptions !== true) throw e; - } - return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); - } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); - } -}; -/** -* A sequence of runnables, where the output of each is the input of the next. -* @example -* ```typescript -* const promptTemplate = PromptTemplate.fromTemplate( -* "Tell me a joke about {topic}", -* ); -* const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]); -* const result = await chain.invoke({ topic: "bears" }); -* ``` -*/ -var RunnableSequence = class RunnableSequence extends Runnable { - static lc_name() { - return "RunnableSequence"; - } - first; - middle = []; - last; - omitSequenceTags = false; - lc_serializable = true; - lc_namespace = ["langchain_core", "runnables"]; - constructor(fields) { - super(fields); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - this.name = fields.name; - this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; - } - get steps() { - return [ - this.first, - ...this.middle, - this.last - ]; - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, void 0, void 0, void 0, config?.runName); - delete config.runId; - let nextStepInput = input; - let finalOutput; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0; i < initialSteps.length; i += 1) { - const step = initialSteps[i]; - const promise = step.invoke(nextStepInput, config_patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); - nextStepInput = await raceWithSignal(promise, options?.signal); - } - if (options?.signal?.aborted) throw getAbortSignalError(options.signal); - finalOutput = await this.last.invoke(nextStepInput, config_patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) })); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); - return finalOutput; - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - let nextStepInputs = inputs; - try { - for (let i = 0; i < this.steps.length; i += 1) { - const step = this.steps[i]; - const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { - const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`); - return config_patchConfig(configList[j], { callbacks: childRunManager }); - }), batchOptions); - nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); - } - } catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); - return nextStepInputs; - } - /** @internal */ - _concatOutputChunks(first, second) { - return this.last._concatOutputChunks(first, second); - } - async *_streamIterator(input, options) { - const callbackManager_ = await getCallbackManagerForConfig(options); - const { runId,...otherOptions } = options ?? {}; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName); - const steps = [ - this.first, - ...this.middle, - this.last - ]; - let concatSupported = true; - let finalOutput; - async function* inputGenerator() { - yield input; - } - try { - let finalGenerator = steps[0].transform(inputGenerator(), config_patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) })); - for (let i = 1; i < steps.length; i += 1) { - const step = steps[i]; - finalGenerator = await step.transform(finalGenerator, config_patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); - } - for await (const chunk of finalGenerator) { - options?.signal?.throwIfAborted(); - yield chunk; - if (concatSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = void 0; - concatSupported = false; - } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); - } - getGraph(config) { - const graph = new Graph(); - let currentLastNode = null; - this.steps.forEach((step, index) => { - const stepGraph = step.getGraph(config); - if (index !== 0) stepGraph.trimFirstNode(); - if (index !== this.steps.length - 1) stepGraph.trimLastNode(); - graph.extend(stepGraph); - const stepFirstNode = stepGraph.firstNode(); - if (!stepFirstNode) throw new Error(`Runnable ${step} has no first node`); - if (currentLastNode) graph.addEdge(currentLastNode, stepFirstNode); - currentLastNode = stepGraph.lastNode(); - }); - return graph; - } - pipe(coerceable) { - if (RunnableSequence.isRunnableSequence(coerceable)) return new RunnableSequence({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle - ]), - last: coerceable.last, - name: this.name ?? coerceable.name - }); - else return new RunnableSequence({ - first: this.first, - middle: [...this.middle, this.last], - last: _coerceToRunnable(coerceable), - name: this.name - }); - } - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && Runnable.isRunnable(thing); - } - static from([first, ...runnables], nameOrFields) { - let extra = {}; - if (typeof nameOrFields === "string") extra.name = nameOrFields; - else if (nameOrFields !== void 0) extra = nameOrFields; - return new RunnableSequence({ - ...extra, - first: _coerceToRunnable(first), - middle: runnables.slice(0, -1).map(_coerceToRunnable), - last: _coerceToRunnable(runnables[runnables.length - 1]) - }); - } -}; -/** -* A runnable that runs a mapping of runnables in parallel, -* and returns a mapping of their outputs. -* @example -* ```typescript -* const mapChain = RunnableMap.from({ -* joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( -* new ChatAnthropic({}), -* ), -* poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( -* new ChatAnthropic({}), -* ), -* }); -* const result = await mapChain.invoke({ topic: "bear" }); -* ``` -*/ -var RunnableMap = class RunnableMap extends Runnable { - static lc_name() { - return "RunnableMap"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - steps; - getStepsKeys() { - return Object.keys(this.steps); - } - constructor(fields) { - super(fields); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) this.steps[key] = _coerceToRunnable(value); - } - static from(steps) { - return new RunnableMap({ steps }); - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input }, config.runId, void 0, void 0, void 0, config?.runName); - delete config.runId; - const output = {}; - try { - const promises = Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) })); - }); - await raceWithSignal(Promise.all(promises), options?.signal); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(output); - return output; - } - async *_transform(generator, runManager, options) { - const steps = { ...this.steps }; - const inputCopies = atee(generator, Object.keys(steps).length); - const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { - const gen = runnable.transform(inputCopies[i], config_patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); - return [key, gen.next().then((result) => ({ - key, - gen, - result - }))]; - })); - while (tasks.size) { - const promise = Promise.race(tasks.values()); - const { key, result, gen } = await raceWithSignal(promise, options?.signal); - tasks.delete(key); - if (!result.done) { - yield { [key]: result.value }; - tasks.set(key, gen.next().then((result$1) => ({ - key, - gen, - result: result$1 - }))); - } - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -/** -* A runnable that wraps a traced LangSmith function. -*/ -var RunnableTraceable = class RunnableTraceable extends Runnable { - lc_serializable = false; - lc_namespace = ["langchain_core", "runnables"]; - func; - constructor(fields) { - super(fields); - if (!isTraceableFunction(fields.func)) throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); - this.func = fields.func; - } - async invoke(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const callbacks = await getCallbackManagerForConfig(config); - const promise = this.func(config_patchConfig(config, { callbacks }), input); - return raceWithSignal(promise, config?.signal); - } - async *_streamIterator(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const result = await this.invoke(input, options); - if (isAsyncIterable(result)) { - for await (const item of result) { - config?.signal?.throwIfAborted(); - yield item; - } - return; - } - if (isIterator(result)) { - while (true) { - config?.signal?.throwIfAborted(); - const state = result.next(); - if (state.done) break; - yield state.value; - } - return; - } - yield result; - } - static from(func) { - return new RunnableTraceable({ func }); - } -}; -function assertNonTraceableFunction(func) { - if (isTraceableFunction(func)) throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); -} -/** -* A runnable that wraps an arbitrary function that takes a single argument. -* @example -* ```typescript -* import { RunnableLambda } from "@langchain/core/runnables"; -* -* const add = (input: { x: number; y: number }) => input.x + input.y; -* -* const multiply = (input: { value: number; multiplier: number }) => -* input.value * input.multiplier; -* -* // Create runnables for the functions -* const addLambda = RunnableLambda.from(add); -* const multiplyLambda = RunnableLambda.from(multiply); -* -* // Chain the lambdas for a mathematical operation -* const chainedLambda = addLambda.pipe((result) => -* multiplyLambda.invoke({ value: result, multiplier: 2 }) -* ); -* -* // Example invocation of the chainedLambda -* const result = await chainedLambda.invoke({ x: 2, y: 3 }); -* -* // Will log "10" (since (2 + 3) * 2 = 10) -* ``` -*/ -var RunnableLambda = class RunnableLambda extends Runnable { - static lc_name() { - return "RunnableLambda"; - } - lc_namespace = ["langchain_core", "runnables"]; - func; - constructor(fields) { - if (isTraceableFunction(fields.func)) return RunnableTraceable.from(fields.func); - super(fields); - assertNonTraceableFunction(fields.func); - this.func = fields.func; - } - static from(func) { - return new RunnableLambda({ func }); - } - async _invoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = config_patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - let output = await this.func(input, { ...childConfig }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); - output = await output.invoke(input, { - ...childConfig, - recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - } else if (isAsyncIterable(output)) { - let finalOutput; - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = chunk; - } - } - output = finalOutput; - } else if (isIterableIterator(output)) { - let finalOutput; - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = chunk; - } - } - output = finalOutput; - } - resolve(output); - } catch (e) { - reject(e); - } - }); - }); - } - async invoke(input, options) { - return this._callWithConfig(this._invoke.bind(this), input, options); - } - async *_transform(generator, runManager, config) { - let finalChunk; - for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; - else try { - finalChunk = this._concatOutputChunks(finalChunk, chunk); - } catch { - finalChunk = chunk; - } - const childConfig = config_patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - const output = await new Promise((resolve, reject) => { - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - const res = await this.func(finalChunk, { - ...childConfig, - config: childConfig - }); - resolve(res); - } catch (e) { - reject(e); - } - }); - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); - const stream = await output.stream(finalChunk, childConfig); - for await (const chunk of stream) yield chunk; - } else if (isAsyncIterable(output)) for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } - else if (isIterableIterator(output)) for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } - else yield output; - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -/** -* A runnable that runs a mapping of runnables in parallel, -* and returns a mapping of their outputs. -* @example -* ```typescript -* import { -* RunnableLambda, -* RunnableParallel, -* } from "@langchain/core/runnables"; -* -* const addYears = (age: number): number => age + 5; -* const yearsToFifty = (age: number): number => 50 - age; -* const yearsToHundred = (age: number): number => 100 - age; -* -* const addYearsLambda = RunnableLambda.from(addYears); -* const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); -* const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); -* -* // Pipe will coerce objects into RunnableParallel by default, but we -* // explicitly instantiate one here to demonstrate -* const sequence = addYearsLambda.pipe( -* RunnableParallel.from({ -* years_to_fifty: milestoneFiftyLambda, -* years_to_hundred: milestoneHundredLambda, -* }) -* ); -* -* // Invoke the sequence with a single age input -* const res = await sequence.invoke(25); -* -* // { years_to_fifty: 20, years_to_hundred: 70 } -* ``` -*/ -var RunnableParallel = class extends RunnableMap {}; -/** -* A Runnable that can fallback to other Runnables if it fails. -* External APIs (e.g., APIs for a language model) may at times experience -* degraded performance or even downtime. -* -* In these cases, it can be useful to have a fallback Runnable that can be -* used in place of the original Runnable (e.g., fallback to another LLM provider). -* -* Fallbacks can be defined at the level of a single Runnable, or at the level -* of a chain of Runnables. Fallbacks are tried in order until one succeeds or -* all fail. -* -* While you can instantiate a `RunnableWithFallbacks` directly, it is usually -* more convenient to use the `withFallbacks` method on an existing Runnable. -* -* When streaming, fallbacks will only be called on failures during the initial -* stream creation. Errors that occur after a stream starts will not fallback -* to the next Runnable. -* -* @example -* ```typescript -* import { -* RunnableLambda, -* RunnableWithFallbacks, -* } from "@langchain/core/runnables"; -* -* const primaryOperation = (input: string): string => { -* if (input !== "safe") { -* throw new Error("Primary operation failed due to unsafe input"); -* } -* return `Processed: ${input}`; -* }; -* -* // Define a fallback operation that processes the input differently -* const fallbackOperation = (input: string): string => -* `Fallback processed: ${input}`; -* -* const primaryRunnable = RunnableLambda.from(primaryOperation); -* const fallbackRunnable = RunnableLambda.from(fallbackOperation); -* -* // Apply the fallback logic using the .withFallbacks() method -* const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); -* -* // Alternatively, create a RunnableWithFallbacks instance manually -* const manualFallbackChain = new RunnableWithFallbacks({ -* runnable: primaryRunnable, -* fallbacks: [fallbackRunnable], -* }); -* -* // Example invocation using .withFallbacks() -* const res = await runnableWithFallback -* .invoke("unsafe input") -* .catch((error) => { -* console.error("Failed after all attempts:", error.message); -* }); -* -* // "Fallback processed: unsafe input" -* -* // Example invocation using manual instantiation -* const res = await manualFallbackChain -* .invoke("safe") -* .catch((error) => { -* console.error("Failed after all attempts:", error.message); -* }); -* -* // "Processed: safe" -* ``` -*/ -var RunnableWithFallbacks = class extends Runnable { - static lc_name() { - return "RunnableWithFallbacks"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - runnable; - fallbacks; - constructor(fields) { - super(fields); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; - } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) yield fallback; - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId,...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); - const childConfig = config_patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); - const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { - let firstError; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - try { - const output = await runnable.invoke(input, childConfig); - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; - } catch (e) { - if (firstError === void 0) firstError = e; - } - } - if (firstError === void 0) throw new Error("No error stored at end of fallback."); - await runManager?.handleChainError(firstError); - throw firstError; - }); - return res; - } - async *_streamIterator(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId,...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); - let firstError; - let stream; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - const childConfig = config_patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); - try { - const originalStream = await runnable.stream(input, childConfig); - stream = consumeAsyncIterableInContext(childConfig, originalStream); - break; - } catch (e) { - if (firstError === void 0) firstError = e; - } - } - if (stream === void 0) { - const error = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback."); - await runManager?.handleChainError(error); - throw error; - } - let output; - try { - for await (const chunk of stream) { - yield chunk; - try { - output = output === void 0 ? output : this._concatOutputChunks(output, chunk); - } catch { - output = void 0; - } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) throw new Error("Not implemented."); - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - let firstError; - for (const runnable of this.runnables()) { - configList[0].signal?.throwIfAborted(); - try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => config_patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions); - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); - return outputs; - } catch (e) { - if (firstError === void 0) firstError = e; - } - } - if (!firstError) throw new Error("No error stored at end of fallbacks."); - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; - } -}; -function _coerceToRunnable(coerceable) { - if (typeof coerceable === "function") return new RunnableLambda({ func: coerceable }); - else if (Runnable.isRunnable(coerceable)) return coerceable; - else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) runnables[key] = _coerceToRunnable(value); - return new RunnableMap({ steps: runnables }); - } else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); -} -/** -* A runnable that assigns key-value pairs to inputs of type `Record`. -* @example -* ```typescript -* import { -* RunnableAssign, -* RunnableLambda, -* RunnableParallel, -* } from "@langchain/core/runnables"; -* -* const calculateAge = (x: { birthYear: number }): { age: number } => { -* const currentYear = new Date().getFullYear(); -* return { age: currentYear - x.birthYear }; -* }; -* -* const createGreeting = (x: { name: string }): { greeting: string } => { -* return { greeting: `Hello, ${x.name}!` }; -* }; -* -* const mapper = RunnableParallel.from({ -* age_step: RunnableLambda.from(calculateAge), -* greeting_step: RunnableLambda.from(createGreeting), -* }); -* -* const runnableAssign = new RunnableAssign({ mapper }); -* -* const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); -* -* // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } -* ``` -*/ -var RunnableAssign = class extends Runnable { - static lc_name() { - return "RunnableAssign"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - mapper; - constructor(fields) { - if (fields instanceof RunnableMap) fields = { mapper: fields }; - super(fields); - this.mapper = fields.mapper; - } - async invoke(input, options) { - const mapperResult = await this.mapper.invoke(input, options); - return { - ...input, - ...mapperResult - }; - } - async *_transform(generator, runManager, options) { - const mapperKeys = this.mapper.getStepsKeys(); - const [forPassthrough, forMapper] = atee(generator); - const mapperOutput = this.mapper.transform(forMapper, config_patchConfig(options, { callbacks: runManager?.getChild() })); - const firstMapperChunkPromise = mapperOutput.next(); - for await (const chunk of forPassthrough) { - if (typeof chunk !== "object" || Array.isArray(chunk)) throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); - const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); - if (Object.keys(filtered).length > 0) yield filtered; - } - yield (await firstMapperChunkPromise).value; - for await (const chunk of mapperOutput) yield chunk; - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -/** -* A runnable that assigns key-value pairs to inputs of type `Record`. -* Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. -* @example -* ```typescript -* import { RunnablePick } from "@langchain/core/runnables"; -* -* const inputData = { -* name: "John", -* age: 30, -* city: "New York", -* country: "USA", -* email: "john.doe@example.com", -* phone: "+1234567890", -* }; -* -* const basicInfoRunnable = new RunnablePick(["name", "city"]); -* -* // Example invocation -* const res = await basicInfoRunnable.invoke(inputData); -* -* // { name: 'John', city: 'New York' } -* ``` -*/ -var RunnablePick = class extends Runnable { - static lc_name() { - return "RunnablePick"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - keys; - constructor(fields) { - if (typeof fields === "string" || Array.isArray(fields)) fields = { keys: fields }; - super(fields); - this.keys = fields.keys; - } - async _pick(input) { - if (typeof this.keys === "string") return input[this.keys]; - else { - const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== void 0); - return picked.length === 0 ? void 0 : Object.fromEntries(picked); - } - } - async invoke(input, options) { - return this._callWithConfig(this._pick.bind(this), input, options); - } - async *_transform(generator) { - for await (const chunk of generator) { - const picked = await this._pick(chunk); - if (picked !== void 0) yield picked; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -var RunnableToolLike = class extends RunnableBinding { - name; - description; - schema; - constructor(fields) { - const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => { - let toolInput; - if (_isToolCall(input)) try { - toolInput = await interopParseAsync(this.schema, input.args); - } catch { - throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); - } - else toolInput = input; - return toolInput; - }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name }); - super({ - bound: sequence, - config: fields.config ?? {} - }); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - static lc_name() { - return "RunnableToolLike"; - } -}; -/** -* Given a runnable and a Zod schema, convert the runnable to a tool. -* -* @template RunInput The input type for the runnable. -* @template RunOutput The output type for the runnable. -* -* @param {Runnable} runnable The runnable to convert to a tool. -* @param fields -* @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. -* @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. -* @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. -* @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. -*/ -function convertRunnableToTool(runnable, fields) { - const name = fields.name ?? runnable.getName(); - const description = fields.description ?? getSchemaDescription(fields.schema); - if (isSimpleStringZodSchema(fields.schema)) return new RunnableToolLike({ - name, - description, - schema: objectType({ input: stringType() }).transform((input) => input.input), - bound: runnable - }); - return new RunnableToolLike({ - name, - description, - schema: fields.schema, - bound: runnable - }); -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js - - - - - - - - - - - -//#region src/messages/transformers.ts -const _isMessageType = (msg, types) => { - const typesAsStrings = [...new Set(types?.map((t) => { - if (typeof t === "string") return t; - const instantiatedMsgClass = new t({}); - if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") throw new Error("Invalid type provided."); - return instantiatedMsgClass.getType(); - }))]; - const msgType = msg.getType(); - return typesAsStrings.some((t) => t === msgType); -}; -function filterMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) return _filterMessages(messagesOrOptions, options); - return RunnableLambda.from((input) => { - return _filterMessages(input, messagesOrOptions); - }); -} -function _filterMessages(messages, options = {}) { - const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; - const filtered = []; - for (const msg of messages) { - if (excludeNames && msg.name && excludeNames.includes(msg.name)) continue; - else if (excludeTypes && _isMessageType(msg, excludeTypes)) continue; - else if (excludeIds && msg.id && excludeIds.includes(msg.id)) continue; - if (!(includeTypes || includeIds || includeNames)) filtered.push(msg); - else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) filtered.push(msg); - else if (includeTypes && _isMessageType(msg, includeTypes)) filtered.push(msg); - else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) filtered.push(msg); - } - return filtered; -} -function mergeMessageRuns(messages) { - if (Array.isArray(messages)) return _mergeMessageRuns(messages); - return RunnableLambda.from(_mergeMessageRuns); -} -function _mergeMessageRuns(messages) { - if (!messages.length) return []; - const merged = []; - for (const msg of messages) { - const curr = msg; - const last = merged.pop(); - if (!last) merged.push(curr); - else if (curr.getType() === "tool" || !(curr.getType() === last.getType())) merged.push(last, curr); - else { - const lastChunk = convertToChunk(last); - const currChunk = convertToChunk(curr); - const mergedChunks = lastChunk.concat(currChunk); - if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; - merged.push(_chunkToMsg(mergedChunks)); - } - } - return merged; -} -function trimMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - const messages = messagesOrOptions; - if (!options) throw new Error("Options parameter is required when providing messages."); - return _trimMessagesHelper(messages, options); - } else { - const trimmerOptions = messagesOrOptions; - return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: "trim_messages" }); - } -} -async function _trimMessagesHelper(messages, options) { - const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; - if (startOn && strategy === "first") throw new Error("`startOn` should only be specified if `strategy` is 'last'."); - if (includeSystem && strategy === "first") throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); - let listTokenCounter; - if ("getNumTokens" in tokenCounter) listTokenCounter = async (msgs) => { - const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); - return tokenCounts.reduce((sum, count) => sum + count, 0); - }; - else listTokenCounter = async (msgs) => tokenCounter(msgs); - let textSplitterFunc = defaultTextSplitter; - if (textSplitter) if ("splitText" in textSplitter) textSplitterFunc = textSplitter.splitText; - else textSplitterFunc = async (text) => textSplitter(text); - if (strategy === "first") return _firstMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - partialStrategy: allowPartial ? "first" : void 0, - endOn - }); - else if (strategy === "last") return _lastMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - allowPartial, - includeSystem, - startOn, - endOn - }); - else throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); -} -async function _firstMaxTokens(messages, options) { - const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; - let messagesCopy = [...messages]; - let idx = 0; - for (let i = 0; i < messagesCopy.length; i += 1) { - const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; - if (await tokenCounter(remainingMessages) <= maxTokens) { - idx = messagesCopy.length - i; - break; - } - } - if (idx < messagesCopy.length && partialStrategy) { - let includedPartial = false; - if (Array.isArray(messagesCopy[idx].content)) { - const excluded = messagesCopy[idx]; - if (typeof excluded.content === "string") throw new Error("Expected content to be an array."); - const numBlock = excluded.content.length; - const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; - for (let i = 1; i <= numBlock; i += 1) { - const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); - const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - const updatedMessage = _switchTypeToMessage(excluded.getType(), { - ...fields, - content: partialContent - }); - const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; - if (await tokenCounter(slicedMessages) <= maxTokens) { - messagesCopy = slicedMessages; - idx += 1; - includedPartial = true; - } else break; - } - if (includedPartial && partialStrategy === "last") excluded.content = [...reversedContent].reverse(); - } - if (!includedPartial) { - const excluded = messagesCopy[idx]; - let text; - if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) { - const textBlock = excluded.content.find((block) => block.type === "text" && block.text); - text = textBlock?.text; - } else if (typeof excluded.content === "string") text = excluded.content; - if (text) { - const splitTexts = await textSplitter(text); - const numSplits = splitTexts.length; - if (partialStrategy === "last") splitTexts.reverse(); - for (let _ = 0; _ < numSplits - 1; _ += 1) { - splitTexts.pop(); - excluded.content = splitTexts.join(""); - if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { - if (partialStrategy === "last") excluded.content = [...splitTexts].reverse().join(""); - messagesCopy = [...messagesCopy.slice(0, idx), excluded]; - idx += 1; - break; - } - } - } - } - } - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) idx -= 1; - } - return messagesCopy.slice(0, idx); -} -async function _lastMaxTokens(messages, options) { - const { allowPartial = false, includeSystem = false, endOn, startOn,...rest } = options; - let messagesCopy = messages.map((message) => { - const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); - }); - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) messagesCopy = messagesCopy.slice(0, -1); - } - const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; - let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); - reversed_ = await _firstMaxTokens(reversed_, { - ...rest, - partialStrategy: allowPartial ? "last" : void 0, - endOn: startOn - }); - if (swappedSystem) return [reversed_[0], ...reversed_.slice(1).reverse()]; - else return reversed_.reverse(); -} -const _MSG_CHUNK_MAP = { - human: { - message: HumanMessage, - messageChunk: HumanMessageChunk - }, - ai: { - message: AIMessage, - messageChunk: AIMessageChunk - }, - system: { - message: SystemMessage, - messageChunk: SystemMessageChunk - }, - developer: { - message: SystemMessage, - messageChunk: SystemMessageChunk - }, - tool: { - message: ToolMessage, - messageChunk: ToolMessageChunk - }, - function: { - message: FunctionMessage, - messageChunk: FunctionMessageChunk - }, - generic: { - message: ChatMessage, - messageChunk: ChatMessageChunk - }, - remove: { - message: RemoveMessage, - messageChunk: RemoveMessage - } -}; -function _switchTypeToMessage(messageType, fields, returnChunk) { - let chunk; - let msg; - switch (messageType) { - case "human": - if (returnChunk) chunk = new HumanMessageChunk(fields); - else msg = new HumanMessage(fields); - break; - case "ai": - if (returnChunk) { - let aiChunkFields = { ...fields }; - if ("tool_calls" in aiChunkFields) aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: void 0, - args: JSON.stringify(tc.args) - })) - }; - chunk = new AIMessageChunk(aiChunkFields); - } else msg = new AIMessage(fields); - break; - case "system": - if (returnChunk) chunk = new SystemMessageChunk(fields); - else msg = new SystemMessage(fields); - break; - case "developer": - if (returnChunk) chunk = new SystemMessageChunk({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer" - } - }); - else msg = new SystemMessage({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer" - } - }); - break; - case "tool": - if ("tool_call_id" in fields) if (returnChunk) chunk = new ToolMessageChunk(fields); - else msg = new ToolMessage(fields); - else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); - break; - case "function": - if (returnChunk) chunk = new FunctionMessageChunk(fields); - else { - if (!fields.name) throw new Error("FunctionMessage must have a 'name' field"); - msg = new FunctionMessage(fields); - } - break; - case "generic": - if ("role" in fields) if (returnChunk) chunk = new ChatMessageChunk(fields); - else msg = new ChatMessage(fields); - else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); - break; - default: throw new Error(`Unrecognized message type ${messageType}`); - } - if (returnChunk && chunk) return chunk; - if (msg) return msg; - throw new Error(`Unrecognized message type ${messageType}`); -} -function _chunkToMsg(chunk) { - const chunkType = chunk.getType(); - let msg; - const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); - if (chunkType in _MSG_CHUNK_MAP) msg = _switchTypeToMessage(chunkType, fields); - if (!msg) throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); - return msg; -} -/** -* The default text splitter function that splits text by newlines. -* -* @param {string} text -* @returns A promise that resolves to an array of strings split by newlines. -*/ -function defaultTextSplitter(text) { - const splits = text.split("\n"); - return Promise.resolve([...splits.slice(0, -1).map((s) => `${s}\n`), splits[splits.length - 1]]); -} - -//#endregion - -//# sourceMappingURL=transformers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/tools.js -//#region src/messages/content/tools.ts -const KNOWN_BLOCK_TYPES = [ - "tool_call", - "tool_call_chunk", - "invalid_tool_call", - "server_tool_call", - "server_tool_call_chunk", - "server_tool_call_result" -]; - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/multimodal.js -//#region src/messages/content/multimodal.ts -const multimodal_KNOWN_BLOCK_TYPES = [ - "image", - "video", - "audio", - "text-plain", - "file" -]; - -//#endregion - -//# sourceMappingURL=multimodal.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/index.js - - - -//#region src/messages/content/index.ts -const KNOWN_BLOCK_TYPES$2 = [ - "text", - "reasoning", - ...KNOWN_BLOCK_TYPES, - ...multimodal_KNOWN_BLOCK_TYPES -]; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js - - - - - - - - - - - - - - - - -//#region src/messages/index.ts -var messages_exports = {}; -__export(messages_exports, { - AIMessage: () => AIMessage, - AIMessageChunk: () => AIMessageChunk, - BaseMessage: () => BaseMessage, - BaseMessageChunk: () => BaseMessageChunk, - ChatMessage: () => ChatMessage, - ChatMessageChunk: () => ChatMessageChunk, - FunctionMessage: () => FunctionMessage, - FunctionMessageChunk: () => FunctionMessageChunk, - HumanMessage: () => HumanMessage, - HumanMessageChunk: () => HumanMessageChunk, - KNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES$2, - RemoveMessage: () => RemoveMessage, - SystemMessage: () => SystemMessage, - SystemMessageChunk: () => SystemMessageChunk, - ToolMessage: () => ToolMessage, - ToolMessageChunk: () => ToolMessageChunk, - _isMessageFieldWithRole: () => _isMessageFieldWithRole, - _mergeDicts: () => _mergeDicts, - _mergeLists: () => _mergeLists, - _mergeObj: () => _mergeObj, - _mergeStatus: () => _mergeStatus, - coerceMessageLikeToMessage: () => utils_coerceMessageLikeToMessage, - convertToChunk: () => convertToChunk, - convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, - convertToProviderContentBlock: () => convertToProviderContentBlock, - defaultTextSplitter: () => defaultTextSplitter, - defaultToolCallParser: () => defaultToolCallParser, - filterMessages: () => filterMessages, - getBufferString: () => getBufferString, - iife: () => utils_iife, - isAIMessage: () => isAIMessage, - isAIMessageChunk: () => isAIMessageChunk, - isBase64ContentBlock: () => isBase64ContentBlock, - isBaseMessage: () => isBaseMessage, - isBaseMessageChunk: () => isBaseMessageChunk, - isChatMessage: () => isChatMessage, - isChatMessageChunk: () => isChatMessageChunk, - isDataContentBlock: () => isDataContentBlock, - isDirectToolOutput: () => isDirectToolOutput, - isFunctionMessage: () => isFunctionMessage, - isFunctionMessageChunk: () => isFunctionMessageChunk, - isHumanMessage: () => isHumanMessage, - isHumanMessageChunk: () => isHumanMessageChunk, - isIDContentBlock: () => isIDContentBlock, - isMessage: () => isMessage, - isOpenAIToolCallArray: () => isOpenAIToolCallArray, - isPlainTextContentBlock: () => isPlainTextContentBlock, - isSystemMessage: () => isSystemMessage, - isSystemMessageChunk: () => isSystemMessageChunk, - isToolMessage: () => isToolMessage, - isToolMessageChunk: () => isToolMessageChunk, - isURLContentBlock: () => isURLContentBlock, - mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, - mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, - mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, - mergeContent: () => mergeContent, - mergeMessageRuns: () => mergeMessageRuns, - mergeResponseMetadata: () => mergeResponseMetadata, - mergeUsageMetadata: () => mergeUsageMetadata, - parseBase64DataUrl: () => parseBase64DataUrl, - parseMimeType: () => parseMimeType, - trimMessages: () => trimMessages -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/chat_history.js - - - - - - -//#region src/chat_history.ts -var chat_history_exports = {}; -__export(chat_history_exports, { - BaseChatMessageHistory: () => BaseChatMessageHistory, - BaseListChatMessageHistory: () => BaseListChatMessageHistory, - InMemoryChatMessageHistory: () => InMemoryChatMessageHistory -}); -/** -* Base class for all chat message histories. All chat message histories -* should extend this class. -*/ -var BaseChatMessageHistory = class extends Serializable { - /** - * Add a list of messages. - * - * Implementations should override this method to handle bulk addition of messages - * in an efficient manner to avoid unnecessary round-trips to the underlying store. - * - * @param messages - A list of BaseMessage objects to store. - */ - async addMessages(messages) { - for (const message of messages) await this.addMessage(message); - } -}; -/** -* Base class for all list chat message histories. All list chat message -* histories should extend this class. -*/ -var BaseListChatMessageHistory = class extends Serializable { - /** - * This is a convenience method for adding a human message string to the store. - * Please note that this is a convenience method. Code should favor the - * bulk addMessages interface instead to save on round-trips to the underlying - * persistence layer. - * This method may be deprecated in a future release. - */ - addUserMessage(message) { - return this.addMessage(new HumanMessage(message)); - } - /** - * This is a convenience method for adding an AI message string to the store. - * Please note that this is a convenience method. Code should favor the bulk - * addMessages interface instead to save on round-trips to the underlying - * persistence layer. - * This method may be deprecated in a future release. - */ - addAIMessage(message) { - return this.addMessage(new AIMessage(message)); - } - /** - * Add a list of messages. - * - * Implementations should override this method to handle bulk addition of messages - * in an efficient manner to avoid unnecessary round-trips to the underlying store. - * - * @param messages - A list of BaseMessage objects to store. - */ - async addMessages(messages) { - for (const message of messages) await this.addMessage(message); - } - /** - * Remove all messages from the store. - */ - clear() { - throw new Error("Not implemented."); - } -}; -/** -* Class for storing chat message history in-memory. It extends the -* BaseListChatMessageHistory class and provides methods to get, add, and -* clear messages. -*/ -var InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { - lc_namespace = [ - "langchain", - "stores", - "message", - "in_memory" - ]; - messages = []; - constructor(messages) { - super(...arguments); - this.messages = messages ?? []; - } - /** - * Method to get all the messages stored in the ChatMessageHistory - * instance. - * @returns Array of stored BaseMessage instances. - */ - async getMessages() { - return this.messages; - } - /** - * Method to add a new message to the ChatMessageHistory instance. - * @param message The BaseMessage instance to add. - * @returns A promise that resolves when the message has been added. - */ - async addMessage(message) { - this.messages.push(message); - } - /** - * Method to clear all the messages from the ChatMessageHistory instance. - * @returns A promise that resolves when all messages have been cleared. - */ - async clear() { - this.messages = []; - } -}; - -//#endregion - -//# sourceMappingURL=chat_history.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/embeddings.js - - - -//#region src/embeddings.ts -var embeddings_exports = {}; -__export(embeddings_exports, { Embeddings: () => Embeddings }); -/** -* An abstract class that provides methods for embedding documents and -* queries using LangChain. -*/ -var Embeddings = class { - /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. - */ - caller; - constructor(params) { - this.caller = new async_caller_AsyncCaller(params ?? {}); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/index.js -//#region src/index.ts -var src_exports = {}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/memory.js - - -//#region src/memory.ts -var memory_exports = {}; -__export(memory_exports, { - BaseMemory: () => BaseMemory, - getInputValue: () => getInputValue, - getOutputValue: () => getOutputValue, - getPromptInputKey: () => getPromptInputKey -}); -/** -* Abstract base class for memory in LangChain's Chains. Memory refers to -* the state in Chains. It can be used to store information about past -* executions of a Chain and inject that information into the inputs of -* future executions of the Chain. -*/ -var BaseMemory = class {}; -const getValue = (values, key) => { - if (key !== void 0) return values[key]; - const keys = Object.keys(values); - if (keys.length === 1) return values[keys[0]]; -}; -/** -* This function is used by memory classes to select the input value -* to use for the memory. If there is only one input value, it is used. -* If there are multiple input values, the inputKey must be specified. -*/ -const getInputValue = (inputValues, inputKey) => { - const value = getValue(inputValues, inputKey); - if (!value) { - const keys = Object.keys(inputValues); - throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); - } - return value; -}; -/** -* This function is used by memory classes to select the output value -* to use for the memory. If there is only one output value, it is used. -* If there are multiple output values, the outputKey must be specified. -* If no outputKey is specified, an error is thrown. -*/ -const getOutputValue = (outputValues, outputKey) => { - const value = getValue(outputValues, outputKey); - if (!value && value !== "") { - const keys = Object.keys(outputValues); - throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); - } - return value; -}; -/** -* Function used by memory classes to get the key of the prompt input, -* excluding any keys that are memory variables or the "stop" key. If -* there is not exactly one prompt input key, an error is thrown. -*/ -function getPromptInputKey(inputs, memoryVariables) { - const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); - if (promptInputKeys.length !== 1) throw new Error(`One input key expected, but got ${promptInputKeys.length}`); - return promptInputKeys[0]; -} - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js - - - - - -//#region src/prompt_values.ts -var prompt_values_exports = {}; -__export(prompt_values_exports, { - BasePromptValue: () => BasePromptValue, - ChatPromptValue: () => ChatPromptValue, - ImagePromptValue: () => ImagePromptValue, - StringPromptValue: () => StringPromptValue -}); -/** -* Base PromptValue class. All prompt values should extend this class. -*/ -var BasePromptValue = class extends Serializable {}; -/** -* Represents a prompt value as a string. It extends the BasePromptValue -* class and overrides the toString and toChatMessages methods. -*/ -var StringPromptValue = class extends BasePromptValue { - static lc_name() { - return "StringPromptValue"; - } - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - value; - constructor(value) { - super({ value }); - this.value = value; - } - toString() { - return this.value; - } - toChatMessages() { - return [new HumanMessage(this.value)]; - } -}; -/** -* Class that represents a chat prompt value. It extends the -* BasePromptValue and includes an array of BaseMessage instances. -*/ -var ChatPromptValue = class extends BasePromptValue { - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - static lc_name() { - return "ChatPromptValue"; - } - messages; - constructor(fields) { - if (Array.isArray(fields)) fields = { messages: fields }; - super(fields); - this.messages = fields.messages; - } - toString() { - return getBufferString(this.messages); - } - toChatMessages() { - return this.messages; - } -}; -/** -* Class that represents an image prompt value. It extends the -* BasePromptValue and includes an ImageURL instance. -*/ -var ImagePromptValue = class extends BasePromptValue { - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - static lc_name() { - return "ImagePromptValue"; - } - imageUrl; - /** @ignore */ - value; - constructor(fields) { - if (!("imageUrl" in fields)) fields = { imageUrl: fields }; - super(fields); - this.imageUrl = fields.imageUrl; - } - toString() { - return this.imageUrl.url; - } - toChatMessages() { - return [new HumanMessage({ content: [{ - type: "image_url", - image_url: { - detail: this.imageUrl.detail, - url: this.imageUrl.url - } - }] })]; - } -}; - -//#endregion - -//# sourceMappingURL=prompt_values.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/stores.js - - - -//#region src/stores.ts -var stores_exports = {}; -__export(stores_exports, { - BaseStore: () => BaseStore, - InMemoryStore: () => InMemoryStore -}); -/** -* Abstract interface for a key-value store. -*/ -var BaseStore = class extends Serializable {}; -/** -* In-memory implementation of the BaseStore using a dictionary. Used for -* storing key-value pairs in memory. -* @example -* ```typescript -* const store = new InMemoryStore(); -* await store.mset( -* Array.from({ length: 5 }).map((_, index) => [ -* `message:id:${index}`, -* index % 2 === 0 -* ? new AIMessage("ai stuff...") -* : new HumanMessage("human stuff..."), -* ]), -* ); -* -* const retrievedMessages = await store.mget(["message:id:0", "message:id:1"]); -* await store.mdelete(await store.yieldKeys("message:id:").toArray()); -* ``` -*/ -var InMemoryStore = class extends BaseStore { - lc_namespace = ["langchain", "storage"]; - store = {}; - /** - * Retrieves the values associated with the given keys from the store. - * @param keys Keys to retrieve values for. - * @returns Array of values associated with the given keys. - */ - async mget(keys) { - return keys.map((key) => this.store[key]); - } - /** - * Sets the values for the given keys in the store. - * @param keyValuePairs Array of key-value pairs to set in the store. - * @returns Promise that resolves when all key-value pairs have been set. - */ - async mset(keyValuePairs) { - for (const [key, value] of keyValuePairs) this.store[key] = value; - } - /** - * Deletes the given keys and their associated values from the store. - * @param keys Keys to delete from the store. - * @returns Promise that resolves when all keys have been deleted. - */ - async mdelete(keys) { - for (const key of keys) delete this.store[key]; - } - /** - * Asynchronous generator that yields keys from the store. If a prefix is - * provided, it only yields keys that start with the prefix. - * @param prefix Optional prefix to filter keys. - * @returns AsyncGenerator that yields keys from the store. - */ - async *yieldKeys(prefix) { - const keys = Object.keys(this.store); - for (const key of keys) if (prefix === void 0 || key.startsWith(prefix)) yield key; - } -}; - -//#endregion - -//# sourceMappingURL=stores.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/retrievers/index.js - - - - - -//#region src/retrievers/index.ts -var retrievers_exports = {}; -__export(retrievers_exports, { BaseRetriever: () => BaseRetriever }); -/** -* Abstract base class for a document retrieval system, designed to -* process string queries and return the most relevant documents from a source. -* -* `BaseRetriever` provides common properties and methods for derived retrievers, -* such as callbacks, tagging, and verbose logging. Custom retrieval systems -* should extend this class and implement `_getRelevantDocuments` to define -* the specific retrieval logic. -* -* @template Metadata - The type of metadata associated with each document, -* defaulting to `Record`. -*/ -var BaseRetriever = class extends Runnable { - /** - * Optional callbacks to handle various events in the retrieval process. - */ - callbacks; - /** - * Tags to label or categorize the retrieval operation. - */ - tags; - /** - * Metadata to provide additional context or information about the retrieval - * operation. - */ - metadata; - /** - * If set to `true`, enables verbose logging for the retrieval process. - */ - verbose; - /** - * Constructs a new `BaseRetriever` instance with optional configuration fields. - * - * @param fields - Optional input configuration that can include `callbacks`, - * `tags`, `metadata`, and `verbose` settings for custom retriever behavior. - */ - constructor(fields) { - super(fields); - this.callbacks = fields?.callbacks; - this.tags = fields?.tags ?? []; - this.metadata = fields?.metadata ?? {}; - this.verbose = fields?.verbose ?? false; - } - /** - * TODO: This should be an abstract method, but we'd like to avoid breaking - * changes to people currently using subclassed custom retrievers. - * Change it on next major release. - */ - /** - * Placeholder method for retrieving relevant documents based on a query. - * - * This method is intended to be implemented by subclasses and will be - * converted to an abstract method in the next major release. Currently, it - * throws an error if not implemented, ensuring that custom retrievers define - * the specific retrieval logic. - * - * @param _query - The query string used to search for relevant documents. - * @param _callbacks - (optional) Callback manager for managing callbacks - * during retrieval. - * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query. - * @throws {Error} Throws an error indicating the method is not implemented. - */ - _getRelevantDocuments(_query, _callbacks) { - throw new Error("Not implemented!"); - } - /** - * Executes a retrieval operation. - * - * @param input - The query string used to search for relevant documents. - * @param options - (optional) Configuration options for the retrieval run, - * which may include callbacks, tags, and metadata. - * @returns A promise that resolves to an array of `DocumentInterface` instances - * representing the most relevant documents to the query. - */ - async invoke(input, options) { - const parsedConfig = ensureConfig(parseCallbackConfigArg(options)); - const callbackManager_ = await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); - const runManager = await callbackManager_?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, void 0, void 0, void 0, parsedConfig.runName); - try { - const results = await this._getRelevantDocuments(input, runManager); - await runManager?.handleRetrieverEnd(results); - return results; - } catch (error) { - await runManager?.handleRetrieverError(error); - throw error; - } - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/vectorstores.js - - - - -//#region src/vectorstores.ts -var vectorstores_exports = {}; -__export(vectorstores_exports, { - SaveableVectorStore: () => SaveableVectorStore, - VectorStore: () => VectorStore, - VectorStoreRetriever: () => VectorStoreRetriever -}); -/** -* Class for retrieving documents from a `VectorStore` based on vector similarity -* or maximal marginal relevance (MMR). -* -* `VectorStoreRetriever` extends `BaseRetriever`, implementing methods for -* adding documents to the underlying vector store and performing document -* retrieval with optional configurations. -* -* @class VectorStoreRetriever -* @extends BaseRetriever -* @implements VectorStoreRetrieverInterface -* @template V - Type of vector store implementing `VectorStoreInterface`. -*/ -var VectorStoreRetriever = class extends BaseRetriever { - static lc_name() { - return "VectorStoreRetriever"; - } - get lc_namespace() { - return ["langchain_core", "vectorstores"]; - } - /** - * The instance of `VectorStore` used for storing and retrieving document embeddings. - * This vector store must implement the `VectorStoreInterface` to be compatible - * with the retriever’s operations. - */ - vectorStore; - /** - * Specifies the number of documents to retrieve for each search query. - * Defaults to 4 if not specified, providing a basic result count for similarity or MMR searches. - */ - k = 4; - /** - * Determines the type of search operation to perform on the vector store. - * - * - `"similarity"` (default): Conducts a similarity search based purely on vector similarity - * to the query. - * - `"mmr"`: Executes a maximal marginal relevance (MMR) search, balancing relevance and - * diversity in the retrieved results. - */ - searchType = "similarity"; - /** - * Additional options specific to maximal marginal relevance (MMR) search, applicable - * only if `searchType` is set to `"mmr"`. - * - * Includes: - * - `fetchK`: The initial number of documents fetched before applying the MMR algorithm, - * allowing for a larger selection from which to choose the most diverse results. - * - `lambda`: A parameter between 0 and 1 to adjust the relevance-diversity balance, - * where 0 prioritizes diversity and 1 prioritizes relevance. - */ - searchKwargs; - /** - * Optional filter applied to search results, defined by the `FilterType` of the vector store. - * Allows for refined, targeted results by restricting the returned documents based - * on specified filter criteria. - */ - filter; - /** - * Returns the type of vector store, as defined by the `vectorStore` instance. - * - * @returns {string} The vector store type. - */ - _vectorstoreType() { - return this.vectorStore._vectorstoreType(); - } - /** - * Initializes a new instance of `VectorStoreRetriever` with the specified configuration. - * - * This constructor configures the retriever to interact with a given `VectorStore` - * and supports different retrieval strategies, including similarity search and maximal - * marginal relevance (MMR) search. Various options allow customization of the number - * of documents retrieved per query, filtering based on conditions, and fine-tuning - * MMR-specific parameters. - * - * @param fields - Configuration options for setting up the retriever: - * - * - `vectorStore` (required): The `VectorStore` instance implementing `VectorStoreInterface` - * that will be used to store and retrieve document embeddings. This is the core component - * of the retriever, enabling vector-based similarity and MMR searches. - * - * - `k` (optional): Specifies the number of documents to retrieve per search query. If not - * provided, defaults to 4. This count determines the number of most relevant documents returned - * for each search operation, balancing performance with comprehensiveness. - * - * - `searchType` (optional): Defines the search approach used by the retriever, allowing for - * flexibility between two methods: - * - `"similarity"` (default): A similarity-based search, retrieving documents with high vector - * similarity to the query. This type prioritizes relevance and is often used when diversity - * among results is less critical. - * - `"mmr"`: Maximal Marginal Relevance search, which combines relevance with diversity. MMR - * is useful for scenarios where varied content is essential, as it selects results that - * both match the query and introduce content diversity. - * - * - `filter` (optional): A filter of type `FilterType`, defined by the vector store, that allows - * for refined and targeted search results. This filter applies specified conditions to limit - * which documents are eligible for retrieval, offering control over the scope of results. - * - * - `searchKwargs` (optional, applicable only if `searchType` is `"mmr"`): Additional settings - * for configuring MMR-specific behavior. These parameters allow further tuning of the MMR - * search process: - * - `fetchK`: The initial number of documents fetched from the vector store before the MMR - * algorithm is applied. Fetching a larger set enables the algorithm to select a more - * diverse subset of documents. - * - `lambda`: A parameter controlling the relevance-diversity balance, where 0 emphasizes - * diversity and 1 prioritizes relevance. Intermediate values provide a blend of the two, - * allowing customization based on the importance of content variety relative to query relevance. - */ - constructor(fields) { - super(fields); - this.vectorStore = fields.vectorStore; - this.k = fields.k ?? this.k; - this.searchType = fields.searchType ?? this.searchType; - this.filter = fields.filter; - if (fields.searchType === "mmr") this.searchKwargs = fields.searchKwargs; - } - /** - * Retrieves relevant documents based on the specified query, using either - * similarity or maximal marginal relevance (MMR) search. - * - * If `searchType` is set to `"mmr"`, performs an MMR search to balance - * similarity and diversity among results. If `searchType` is `"similarity"`, - * retrieves results purely based on similarity to the query. - * - * @param query - The query string used to find relevant documents. - * @param runManager - Optional callback manager for tracking retrieval progress. - * @returns A promise that resolves to an array of `DocumentInterface` instances - * representing the most relevant documents to the query. - * @throws {Error} Throws an error if MMR search is requested but not supported - * by the vector store. - * @protected - */ - async _getRelevantDocuments(query, runManager) { - if (this.searchType === "mmr") { - if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`); - return this.vectorStore.maxMarginalRelevanceSearch(query, { - k: this.k, - filter: this.filter, - ...this.searchKwargs - }, runManager?.getChild("vectorstore")); - } - return this.vectorStore.similaritySearch(query, this.k, this.filter, runManager?.getChild("vectorstore")); - } - /** - * Adds an array of documents to the vector store, embedding them as part of - * the storage process. - * - * This method delegates document embedding and storage to the `addDocuments` - * method of the underlying vector store. - * - * @param documents - An array of documents to embed and add to the vector store. - * @param options - Optional settings to customize document addition. - * @returns A promise that resolves to an array of document IDs or `void`, - * depending on the vector store's implementation. - */ - async addDocuments(documents, options) { - return this.vectorStore.addDocuments(documents, options); - } -}; -/** -* Abstract class representing a vector storage system for performing -* similarity searches on embedded documents. -* -* `VectorStore` provides methods for adding precomputed vectors or documents, -* removing documents based on criteria, and performing similarity searches -* with optional scoring. Subclasses are responsible for implementing specific -* storage mechanisms and the exact behavior of certain abstract methods. -* -* @abstract -* @extends Serializable -* @implements VectorStoreInterface -*/ -var VectorStore = class extends Serializable { - /** - * Namespace within LangChain to uniquely identify this vector store's - * location, based on the vector store type. - * - * @internal - */ - lc_namespace = [ - "langchain", - "vectorstores", - this._vectorstoreType() - ]; - /** - * Embeddings interface for generating vector embeddings from text queries, - * enabling vector-based similarity searches. - */ - embeddings; - /** - * Initializes a new vector store with embeddings and database configuration. - * - * @param embeddings - Instance of `EmbeddingsInterface` used to embed queries. - * @param dbConfig - Configuration settings for the database or storage system. - */ - constructor(embeddings, dbConfig) { - super(dbConfig); - this.embeddings = embeddings; - } - /** - * Deletes documents from the vector store based on the specified parameters. - * - * @param _params - Flexible key-value pairs defining conditions for document deletion. - * @returns A promise that resolves once the deletion is complete. - */ - async delete(_params) { - throw new Error("Not implemented."); - } - /** - * Searches for documents similar to a text query by embedding the query and - * performing a similarity search on the resulting vector. - * - * @param query - Text query for finding similar documents. - * @param k - Number of similar results to return. Defaults to 4. - * @param filter - Optional filter based on `FilterType`. - * @param _callbacks - Optional callbacks for monitoring search progress - * @returns A promise resolving to an array of `DocumentInterface` instances representing similar documents. - */ - async similaritySearch(query, k = 4, filter = void 0, _callbacks = void 0) { - const results = await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); - return results.map((result) => result[0]); - } - /** - * Searches for documents similar to a text query by embedding the query, - * and returns results with similarity scores. - * - * @param query - Text query for finding similar documents. - * @param k - Number of similar results to return. Defaults to 4. - * @param filter - Optional filter based on `FilterType`. - * @param _callbacks - Optional callbacks for monitoring search progress - * @returns A promise resolving to an array of tuples, each containing a - * document and its similarity score. - */ - async similaritySearchWithScore(query, k = 4, filter = void 0, _callbacks = void 0) { - return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); - } - /** - * Creates a `VectorStore` instance from an array of text strings and optional - * metadata, using the specified embeddings and database configuration. - * - * Subclasses must implement this method to define how text and metadata - * are embedded and stored in the vector store. Throws an error if not overridden. - * - * @param _texts - Array of strings representing the text documents to be stored. - * @param _metadatas - Metadata for the texts, either as an array (one for each text) - * or a single object (applied to all texts). - * @param _embeddings - Instance of `EmbeddingsInterface` to embed the texts. - * @param _dbConfig - Database configuration settings. - * @returns A promise that resolves to a new `VectorStore` instance. - * @throws {Error} Throws an error if this method is not overridden by a subclass. - */ - static fromTexts(_texts, _metadatas, _embeddings, _dbConfig) { - throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); - } - /** - * Creates a `VectorStore` instance from an array of documents, using the specified - * embeddings and database configuration. - * - * Subclasses must implement this method to define how documents are embedded - * and stored. Throws an error if not overridden. - * - * @param _docs - Array of `DocumentInterface` instances representing the documents to be stored. - * @param _embeddings - Instance of `EmbeddingsInterface` to embed the documents. - * @param _dbConfig - Database configuration settings. - * @returns A promise that resolves to a new `VectorStore` instance. - * @throws {Error} Throws an error if this method is not overridden by a subclass. - */ - static fromDocuments(_docs, _embeddings, _dbConfig) { - throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); - } - /** - * Creates a `VectorStoreRetriever` instance with flexible configuration options. - * - * @param kOrFields - * - If a number is provided, it sets the `k` parameter (number of items to retrieve). - * - If an object is provided, it should contain various configuration options. - * @param filter - * - Optional filter criteria to limit the items retrieved based on the specified filter type. - * @param callbacks - * - Optional callbacks that may be triggered at specific stages of the retrieval process. - * @param tags - * - Tags to categorize or label the `VectorStoreRetriever`. Defaults to an empty array if not provided. - * @param metadata - * - Additional metadata as key-value pairs to add contextual information for the retrieval process. - * @param verbose - * - If `true`, enables detailed logging for the retrieval process. Defaults to `false`. - * - * @returns - * - A configured `VectorStoreRetriever` instance based on the provided parameters. - * - * @example - * Basic usage with a `k` value: - * ```typescript - * const retriever = myVectorStore.asRetriever(5); - * ``` - * - * Usage with a configuration object: - * ```typescript - * const retriever = myVectorStore.asRetriever({ - * k: 10, - * filter: myFilter, - * tags: ['example', 'test'], - * verbose: true, - * searchType: 'mmr', - * searchKwargs: { alpha: 0.5 }, - * }); - * ``` - */ - asRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) { - if (typeof kOrFields === "number") return new VectorStoreRetriever({ - vectorStore: this, - k: kOrFields, - filter, - tags: [...tags ?? [], this._vectorstoreType()], - metadata, - verbose, - callbacks - }); - else { - const params = { - vectorStore: this, - k: kOrFields?.k, - filter: kOrFields?.filter, - tags: [...kOrFields?.tags ?? [], this._vectorstoreType()], - metadata: kOrFields?.metadata, - verbose: kOrFields?.verbose, - callbacks: kOrFields?.callbacks, - searchType: kOrFields?.searchType - }; - if (kOrFields?.searchType === "mmr") return new VectorStoreRetriever({ - ...params, - searchKwargs: kOrFields.searchKwargs - }); - return new VectorStoreRetriever({ ...params }); - } - } -}; -/** -* Abstract class extending `VectorStore` that defines a contract for saving -* and loading vector store instances. -* -* The `SaveableVectorStore` class allows vector store implementations to -* persist their data and retrieve it when needed.The format for saving and -* loading data is left to the implementing subclass. -* -* Subclasses must implement the `save` method to handle their custom -* serialization logic, while the `load` method enables reconstruction of a -* vector store from saved data, requiring compatible embeddings through the -* `EmbeddingsInterface`. -* -* @abstract -* @extends VectorStore -*/ -var SaveableVectorStore = class extends VectorStore { - /** - * Loads a vector store instance from the specified directory, using the - * provided embeddings to ensure compatibility. - * - * This static method reconstructs a `SaveableVectorStore` from previously - * saved data. Implementations should interpret the saved data format to - * recreate the vector store instance. - * - * @param _directory - The directory path from which the vector store - * data will be loaded. - * @param _embeddings - An instance of `EmbeddingsInterface` to align - * the embeddings with the loaded vector data. - * @returns A promise that resolves to a `SaveableVectorStore` instance - * constructed from the saved data. - */ - static load(_directory, _embeddings) { - throw new Error("Not implemented"); - } -}; - -//#endregion - -//# sourceMappingURL=vectorstores.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha256/hash.js - - -//#region src/utils/js-sha256/hash.ts -var HEX_CHARS = "0123456789abcdef".split(""); -var EXTRA = [ - -2147483648, - 8388608, - 32768, - 128 -]; -var SHIFT = [ - 24, - 16, - 8, - 0 -]; -var K = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]; -var blocks = []; -function Sha256(is224, sharedMemory) { - if (sharedMemory) { - blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - this.blocks = blocks; - } else this.blocks = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - if (is224) { - this.h0 = 3238371032; - this.h1 = 914150663; - this.h2 = 812702999; - this.h3 = 4144912697; - this.h4 = 4290775857; - this.h5 = 1750603025; - this.h6 = 1694076839; - this.h7 = 3204075428; - } else { - this.h0 = 1779033703; - this.h1 = 3144134277; - this.h2 = 1013904242; - this.h3 = 2773480762; - this.h4 = 1359893119; - this.h5 = 2600822924; - this.h6 = 528734635; - this.h7 = 1541459225; - } - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; - this.is224 = is224; -} -Sha256.prototype.update = function(message) { - if (this.finalized) return; - var notString, type = typeof message; - if (type !== "string") { - if (type === "object") { - if (message === null) throw new Error(ERROR); - else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message); - else if (!Array.isArray(message)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) throw new Error(ERROR); - } - } else throw new Error(ERROR); - notString = true; - } - var code, index = 0, i, length = message.length, blocks$1 = this.blocks; - while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks$1[0] = this.block; - this.block = blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0; - } - if (notString) for (i = this.start; index < length && i < 64; ++index) blocks$1[i >>> 2] |= message[index] << SHIFT[i++ & 3]; - else for (i = this.start; index < length && i < 64; ++index) { - code = message.charCodeAt(index); - if (code < 128) blocks$1[i >>> 2] |= code << SHIFT[i++ & 3]; - else if (code < 2048) { - blocks$1[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } else if (code < 55296 || code >= 57344) { - blocks$1[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } else { - code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); - blocks$1[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } - } - this.lastByteIndex = i; - this.bytes += i - this.start; - if (i >= 64) { - this.block = blocks$1[16]; - this.start = i - 64; - this.hash(); - this.hashed = true; - } else this.start = i; - } - if (this.bytes > 4294967295) { - this.hBytes += this.bytes / 4294967296 << 0; - this.bytes = this.bytes % 4294967296; - } - return this; -}; -Sha256.prototype.finalize = function() { - if (this.finalized) return; - this.finalized = true; - var blocks$1 = this.blocks, i = this.lastByteIndex; - blocks$1[16] = this.block; - blocks$1[i >>> 2] |= EXTRA[i & 3]; - this.block = blocks$1[16]; - if (i >= 56) { - if (!this.hashed) this.hash(); - blocks$1[0] = this.block; - blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0; - } - blocks$1[14] = this.hBytes << 3 | this.bytes >>> 29; - blocks$1[15] = this.bytes << 3; - this.hash(); -}; -Sha256.prototype.hash = function() { - var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks$1 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; - for (j = 16; j < 64; ++j) { - t1 = blocks$1[j - 15]; - s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; - t1 = blocks$1[j - 2]; - s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - blocks$1[j] = blocks$1[j - 16] + s0 + blocks$1[j - 7] + s1 << 0; - } - bc = b & c; - for (j = 0; j < 64; j += 4) { - if (this.first) { - if (this.is224) { - ab = 300032; - t1 = blocks$1[0] - 1413257819; - h = t1 - 150054599 << 0; - d = t1 + 24177077 << 0; - } else { - ab = 704751109; - t1 = blocks$1[0] - 210244248; - h = t1 - 1521486534 << 0; - d = t1 + 143694565 << 0; - } - this.first = false; - } else { - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ab = a & b; - maj = ab ^ a & c ^ bc; - ch = e & f ^ ~e & g; - t1 = h + s1 + ch + K[j] + blocks$1[j]; - t2 = s0 + maj; - h = d + t1 << 0; - d = t1 + t2 << 0; - } - s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); - s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); - da = d & a; - maj = da ^ d & b ^ ab; - ch = g & h ^ ~g & e; - t1 = f + s1 + ch + K[j + 1] + blocks$1[j + 1]; - t2 = s0 + maj; - g = c + t1 << 0; - c = t1 + t2 << 0; - s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); - s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); - cd = c & d; - maj = cd ^ c & a ^ da; - ch = f & g ^ ~f & h; - t1 = e + s1 + ch + K[j + 2] + blocks$1[j + 2]; - t2 = s0 + maj; - f = b + t1 << 0; - b = t1 + t2 << 0; - s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); - s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7); - bc = b & c; - maj = bc ^ b & d ^ cd; - ch = f & g ^ ~f & h; - t1 = e + s1 + ch + K[j + 3] + blocks$1[j + 3]; - t2 = s0 + maj; - e = a + t1 << 0; - a = t1 + t2 << 0; - this.chromeBugWorkAround = true; - } - this.h0 = this.h0 + a << 0; - this.h1 = this.h1 + b << 0; - this.h2 = this.h2 + c << 0; - this.h3 = this.h3 + d << 0; - this.h4 = this.h4 + e << 0; - this.h5 = this.h5 + f << 0; - this.h6 = this.h6 + g << 0; - this.h7 = this.h7 + h << 0; -}; -Sha256.prototype.hex = function() { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; - var hex = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; - if (!this.is224) hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; - return hex; -}; -Sha256.prototype.toString = Sha256.prototype.hex; -Sha256.prototype.digest = function() { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; - var arr = [ - h0 >>> 24 & 255, - h0 >>> 16 & 255, - h0 >>> 8 & 255, - h0 & 255, - h1 >>> 24 & 255, - h1 >>> 16 & 255, - h1 >>> 8 & 255, - h1 & 255, - h2 >>> 24 & 255, - h2 >>> 16 & 255, - h2 >>> 8 & 255, - h2 & 255, - h3 >>> 24 & 255, - h3 >>> 16 & 255, - h3 >>> 8 & 255, - h3 & 255, - h4 >>> 24 & 255, - h4 >>> 16 & 255, - h4 >>> 8 & 255, - h4 & 255, - h5 >>> 24 & 255, - h5 >>> 16 & 255, - h5 >>> 8 & 255, - h5 & 255, - h6 >>> 24 & 255, - h6 >>> 16 & 255, - h6 >>> 8 & 255, - h6 & 255 - ]; - if (!this.is224) arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); - return arr; -}; -Sha256.prototype.array = Sha256.prototype.digest; -Sha256.prototype.arrayBuffer = function() { - this.finalize(); - var buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32); - var dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - dataView.setUint32(20, this.h5); - dataView.setUint32(24, this.h6); - if (!this.is224) dataView.setUint32(28, this.h7); - return buffer; -}; -const sha256 = (...strings) => { - return new Sha256(false, true).update(strings.join("")).hex(); -}; - -//#endregion - -//# sourceMappingURL=hash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js - - - -//#region src/utils/hash.ts -var hash_exports = {}; -__export(hash_exports, { sha256: () => sha256 }); - -//#endregion - -//# sourceMappingURL=hash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/base.js - - - - - -//#region src/caches/base.ts -var caches_base_base_exports = {}; -__export(caches_base_base_exports, { - BaseCache: () => base_BaseCache, - InMemoryCache: () => InMemoryCache, - defaultHashKeyEncoder: () => defaultHashKeyEncoder, - deserializeStoredGeneration: () => deserializeStoredGeneration, - serializeGeneration: () => serializeGeneration -}); -const defaultHashKeyEncoder = (...strings) => sha256(strings.join("_")); -function deserializeStoredGeneration(storedGeneration) { - if (storedGeneration.message !== void 0) return { - text: storedGeneration.text, - message: mapStoredMessageToChatMessage(storedGeneration.message) - }; - else return { text: storedGeneration.text }; -} -function serializeGeneration(generation) { - const serializedValue = { text: generation.text }; - if (generation.message !== void 0) serializedValue.message = generation.message.toDict(); - return serializedValue; -} -/** -* Base class for all caches. All caches should extend this class. -*/ -var base_BaseCache = class { - keyEncoder = defaultHashKeyEncoder; - /** - * Sets a custom key encoder function for the cache. - * This function should take a prompt and an LLM key and return a string - * that will be used as the cache key. - * @param keyEncoderFn The custom key encoder function. - */ - makeDefaultKeyEncoder(keyEncoderFn) { - this.keyEncoder = keyEncoderFn; - } -}; -const GLOBAL_MAP = /* @__PURE__ */ new Map(); -/** -* A cache for storing LLM generations that stores data in memory. -*/ -var InMemoryCache = class InMemoryCache extends base_BaseCache { - cache; - constructor(map) { - super(); - this.cache = map ?? /* @__PURE__ */ new Map(); - } - /** - * Retrieves data from the cache using a prompt and an LLM key. If the - * data is not found, it returns null. - * @param prompt The prompt used to find the data. - * @param llmKey The LLM key used to find the data. - * @returns The data corresponding to the prompt and LLM key, or null if not found. - */ - lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); - } - /** - * Updates the cache with new data using a prompt and an LLM key. - * @param prompt The prompt used to store the data. - * @param llmKey The LLM key used to store the data. - * @param value The data to be stored. - */ - async update(prompt, llmKey, value) { - this.cache.set(this.keyEncoder(prompt, llmKey), value); - } - /** - * Returns a global instance of InMemoryCache using a predefined global - * map as the initial cache. - * @returns A global instance of InMemoryCache. - */ - static global() { - return new InMemoryCache(GLOBAL_MAP); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/document_loaders/base.js - - -//#region src/document_loaders/base.ts -var document_loaders_base_base_exports = {}; -__export(document_loaders_base_base_exports, { BaseDocumentLoader: () => BaseDocumentLoader }); -/** -* Abstract class that provides a default implementation for the -* loadAndSplit() method from the DocumentLoader interface. The load() -* method is left abstract and needs to be implemented by subclasses. -*/ -var BaseDocumentLoader = class {}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/document_loaders/langsmith.js - - - - -//#region src/document_loaders/langsmith.ts -var langsmith_exports = {}; -__export(langsmith_exports, { LangSmithLoader: () => LangSmithLoader }); -/** -* Document loader integration with LangSmith. -* -* ## [Constructor args](https://api.js.langchain.com/interfaces/_langchain_core.document_loaders_langsmith.LangSmithLoaderFields.html) -* -*
-* Load -* -* ```typescript -* import { LangSmithLoader } from '@langchain/core/document_loaders/langsmith'; -* import { Client } from 'langsmith'; -* -* const langSmithClient = new Client({ -* apiKey: process.env.LANGSMITH_API_KEY, -* }) -* -* const loader = new LangSmithLoader({ -* datasetId: "9a3b36f7-b308-40a5-9b46-6613853b6330", -* limit: 1, -* }); -* -* const docs = await loader.load(); -* ``` -* -* ```txt -* [ -* { -* pageContent: '{\n "input_key_str": "string",\n "input_key_bool": true\n}', -* metadata: { -* id: '8523d9e9-c123-4b23-9b46-21021nds289e', -* created_at: '2024-08-19T17:09:14.806441+00:00', -* modified_at: '2024-08-19T17:09:14.806441+00:00', -* name: '#8517 @ brace-test-dataset', -* dataset_id: '9a3b36f7-b308-40a5-9b46-6613853b6330', -* source_run_id: null, -* metadata: [Object], -* inputs: [Object], -* outputs: [Object] -* } -* } -* ] -* ``` -*
-*/ -var LangSmithLoader = class extends BaseDocumentLoader { - datasetId; - datasetName; - exampleIds; - asOf; - splits; - inlineS3Urls; - offset; - limit; - metadata; - filter; - contentKey; - formatContent; - client; - constructor(fields) { - super(); - if (fields.client && fields.clientConfig) throw new Error("client and clientConfig cannot both be provided."); - this.client = fields.client ?? new Client(fields?.clientConfig); - this.contentKey = fields.contentKey ? fields.contentKey.split(".") : []; - this.formatContent = fields.formatContent ?? _stringify; - this.datasetId = fields.datasetId; - this.datasetName = fields.datasetName; - this.exampleIds = fields.exampleIds; - this.asOf = fields.asOf; - this.splits = fields.splits; - this.inlineS3Urls = fields.inlineS3Urls; - this.offset = fields.offset; - this.limit = fields.limit; - this.metadata = fields.metadata; - this.filter = fields.filter; - } - async load() { - const documents = []; - for await (const example of this.client.listExamples({ - datasetId: this.datasetId, - datasetName: this.datasetName, - exampleIds: this.exampleIds, - asOf: this.asOf, - splits: this.splits, - inlineS3Urls: this.inlineS3Urls, - offset: this.offset, - limit: this.limit, - metadata: this.metadata, - filter: this.filter - })) { - let content = example.inputs; - for (const key of this.contentKey) content = content[key]; - const contentStr = this.formatContent(content); - const metadata = example; - ["created_at", "modified_at"].forEach((k) => { - if (k in metadata) { - if (typeof metadata[k] === "object") metadata[k] = metadata[k].toString(); - } - }); - documents.push({ - pageContent: contentStr, - metadata - }); - } - return documents; - } -}; -function _stringify(x) { - if (typeof x === "string") return x; - else try { - return JSON.stringify(x, null, 2); - } catch { - return String(x); - } -} - -//#endregion - -//# sourceMappingURL=langsmith.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/document.js -//#region src/documents/document.ts -/** -* Interface for interacting with a document. -*/ -var Document = class { - pageContent; - metadata; - /** - * An optional identifier for the document. - * - * Ideally this should be unique across the document collection and formatted - * as a UUID, but this will not be enforced. - */ - id; - constructor(fields) { - this.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : ""; - this.metadata = fields.metadata ?? {}; - this.id = fields.id; - } -}; - -//#endregion - -//# sourceMappingURL=document.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/transformers.js - - -//#region src/documents/transformers.ts -/** -* Abstract base class for document transformation systems. -* -* A document transformation system takes an array of Documents and returns an -* array of transformed Documents. These arrays do not necessarily have to have -* the same length. -* -* One example of this is a text splitter that splits a large document into -* many smaller documents. -*/ -var BaseDocumentTransformer = class extends Runnable { - lc_namespace = [ - "langchain_core", - "documents", - "transformers" - ]; - /** - * Method to invoke the document transformation. This method calls the - * transformDocuments method with the provided input. - * @param input The input documents to be transformed. - * @param _options Optional configuration object to customize the behavior of callbacks. - * @returns A Promise that resolves to the transformed documents. - */ - invoke(input, _options) { - return this.transformDocuments(input); - } -}; -/** -* Class for document transformers that return exactly one transformed document -* for each input document. -*/ -var MappingDocumentTransformer = class extends BaseDocumentTransformer { - async transformDocuments(documents) { - const newDocuments = []; - for (const document of documents) { - const transformedDocument = await this._transformDocument(document); - newDocuments.push(transformedDocument); - } - return newDocuments; - } -}; - -//#endregion - -//# sourceMappingURL=transformers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/index.js - - - - -//#region src/documents/index.ts -var documents_exports = {}; -__export(documents_exports, { - BaseDocumentTransformer: () => BaseDocumentTransformer, - Document: () => Document, - MappingDocumentTransformer: () => MappingDocumentTransformer -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/base.js - - -//#region src/example_selectors/base.ts -/** -* Base class for example selectors. -*/ -var BaseExampleSelector = class extends Serializable { - lc_namespace = [ - "langchain_core", - "example_selectors", - "base" - ]; -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/conditional.js -//#region src/example_selectors/conditional.ts -/** -* Abstract class that defines the interface for selecting a prompt for a -* given language model. -*/ -var BasePromptSelector = class { - /** - * Asynchronous version of `getPrompt` that also accepts an options object - * for partial variables. - * @param llm The language model for which to get a prompt. - * @param options Optional object for partial variables. - * @returns A Promise that resolves to a prompt template. - */ - async getPromptAsync(llm, options) { - const prompt = this.getPrompt(llm); - return prompt.partial(options?.partialVariables ?? {}); - } -}; -/** -* Concrete implementation of `BasePromptSelector` that selects a prompt -* based on a set of conditions. It has a default prompt that it returns -* if none of the conditions are met. -*/ -var ConditionalPromptSelector = class extends BasePromptSelector { - defaultPrompt; - conditionals; - constructor(default_prompt, conditionals = []) { - super(); - this.defaultPrompt = default_prompt; - this.conditionals = conditionals; - } - /** - * Method that selects a prompt based on a set of conditions. If none of - * the conditions are met, it returns the default prompt. - * @param llm The language model for which to get a prompt. - * @returns A prompt template. - */ - getPrompt(llm) { - for (const [condition, prompt] of this.conditionals) if (condition(llm)) return prompt; - return this.defaultPrompt; - } -}; -/** -* Type guard function that checks if a given language model is of type -* `BaseLLM`. -*/ -function isLLM(llm) { - return llm._modelType() === "base_llm"; -} -/** -* Type guard function that checks if a given language model is of type -* `BaseChatModel`. -*/ -function isChatModel(llm) { - return llm._modelType() === "base_chat_model"; -} - -//#endregion - -//# sourceMappingURL=conditional.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/length_based.js - - -//#region src/example_selectors/length_based.ts -/** -* Calculates the length of a text based on the number of words and lines. -*/ -function getLengthBased(text) { - return text.split(/\n| /).length; -} -/** -* A specialized example selector that selects examples based on their -* length, ensuring that the total length of the selected examples does -* not exceed a specified maximum length. -* @example -* ```typescript -* const exampleSelector = new LengthBasedExampleSelector( -* [ -* { input: "happy", output: "sad" }, -* { input: "tall", output: "short" }, -* { input: "energetic", output: "lethargic" }, -* { input: "sunny", output: "gloomy" }, -* { input: "windy", output: "calm" }, -* ], -* { -* examplePrompt: new PromptTemplate({ -* inputVariables: ["input", "output"], -* template: "Input: {input}\nOutput: {output}", -* }), -* maxLength: 25, -* }, -* ); -* const dynamicPrompt = new FewShotPromptTemplate({ -* exampleSelector, -* examplePrompt: new PromptTemplate({ -* inputVariables: ["input", "output"], -* template: "Input: {input}\nOutput: {output}", -* }), -* prefix: "Give the antonym of every input", -* suffix: "Input: {adjective}\nOutput:", -* inputVariables: ["adjective"], -* }); -* console.log(dynamicPrompt.format({ adjective: "big" })); -* console.log( -* dynamicPrompt.format({ -* adjective: -* "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else", -* }), -* ); -* ``` -*/ -var LengthBasedExampleSelector = class LengthBasedExampleSelector extends BaseExampleSelector { - examples = []; - examplePrompt; - getTextLength = getLengthBased; - maxLength = 2048; - exampleTextLengths = []; - constructor(data) { - super(data); - this.examplePrompt = data.examplePrompt; - this.maxLength = data.maxLength ?? 2048; - this.getTextLength = data.getTextLength ?? getLengthBased; - } - /** - * Adds an example to the list of examples and calculates its length. - * @param example The example to be added. - * @returns Promise that resolves when the example has been added and its length calculated. - */ - async addExample(example) { - this.examples.push(example); - const stringExample = await this.examplePrompt.format(example); - this.exampleTextLengths.push(this.getTextLength(stringExample)); - } - /** - * Calculates the lengths of the examples. - * @param v Array of lengths of the examples. - * @param values Instance of LengthBasedExampleSelector. - * @returns Promise that resolves with an array of lengths of the examples. - */ - async calculateExampleTextLengths(v, values) { - if (v.length > 0) return v; - const { examples, examplePrompt } = values; - const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); - return stringExamples.map((eg) => this.getTextLength(eg)); - } - /** - * Selects examples until the total length of the selected examples - * reaches the maxLength. - * @param inputVariables The input variables for the examples. - * @returns Promise that resolves with an array of selected examples. - */ - async selectExamples(inputVariables) { - const inputs = Object.values(inputVariables).join(" "); - let remainingLength = this.maxLength - this.getTextLength(inputs); - let i = 0; - const examples = []; - while (remainingLength > 0 && i < this.examples.length) { - const newLength = remainingLength - this.exampleTextLengths[i]; - if (newLength < 0) break; - else { - examples.push(this.examples[i]); - remainingLength = newLength; - } - i += 1; - } - return examples; - } - /** - * Creates a new instance of LengthBasedExampleSelector and adds a list of - * examples to it. - * @param examples Array of examples to be added. - * @param args Input parameters for the LengthBasedExampleSelector. - * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. - */ - static async fromExamples(examples, args) { - const selector = new LengthBasedExampleSelector(args); - await Promise.all(examples.map((eg) => selector.addExample(eg))); - return selector; - } -}; - -//#endregion - -//# sourceMappingURL=length_based.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js - - - -//#region src/example_selectors/semantic_similarity.ts -function sortedValues(values) { - return Object.keys(values).sort().map((key) => values[key]); -} -/** -* Class that selects examples based on semantic similarity. It extends -* the BaseExampleSelector class. -* @example -* ```typescript -* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( -* [ -* { input: "happy", output: "sad" }, -* { input: "tall", output: "short" }, -* { input: "energetic", output: "lethargic" }, -* { input: "sunny", output: "gloomy" }, -* { input: "windy", output: "calm" }, -* ], -* new OpenAIEmbeddings(), -* HNSWLib, -* { k: 1 }, -* ); -* const dynamicPrompt = new FewShotPromptTemplate({ -* exampleSelector, -* examplePrompt: PromptTemplate.fromTemplate( -* "Input: {input}\nOutput: {output}", -* ), -* prefix: "Give the antonym of every input", -* suffix: "Input: {adjective}\nOutput:", -* inputVariables: ["adjective"], -* }); -* console.log(await dynamicPrompt.format({ adjective: "rainy" })); -* ``` -*/ -var SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector extends BaseExampleSelector { - vectorStoreRetriever; - exampleKeys; - inputKeys; - constructor(data) { - super(data); - this.exampleKeys = data.exampleKeys; - this.inputKeys = data.inputKeys; - if (data.vectorStore !== void 0) this.vectorStoreRetriever = data.vectorStore.asRetriever({ - k: data.k ?? 4, - filter: data.filter - }); - else if (data.vectorStoreRetriever) this.vectorStoreRetriever = data.vectorStoreRetriever; - else throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); - } - /** - * Method that adds a new example to the vectorStore. The example is - * converted to a string and added to the vectorStore as a document. - * @param example The example to be added to the vectorStore. - * @returns Promise that resolves when the example has been added to the vectorStore. - */ - async addExample(example) { - const inputKeys = this.inputKeys ?? Object.keys(example); - const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {})).join(" "); - await this.vectorStoreRetriever.addDocuments([new Document({ - pageContent: stringExample, - metadata: example - })]); - } - /** - * Method that selects which examples to use based on semantic similarity. - * It performs a similarity search in the vectorStore using the input - * variables and returns the examples with the highest similarity. - * @param inputVariables The input variables used for the similarity search. - * @returns Promise that resolves with an array of the selected examples. - */ - async selectExamples(inputVariables) { - const inputKeys = this.inputKeys ?? Object.keys(inputVariables); - const query = sortedValues(inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: inputVariables[key] - }), {})).join(" "); - const exampleDocs = await this.vectorStoreRetriever.invoke(query); - const examples = exampleDocs.map((doc) => doc.metadata); - if (this.exampleKeys) return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {})); - return examples; - } - /** - * Static method that creates a new instance of - * SemanticSimilarityExampleSelector. It takes a list of examples, an - * instance of Embeddings, a VectorStore class, and an options object as - * parameters. It converts the examples to strings, creates a VectorStore - * from the strings and the embeddings, and returns a new - * SemanticSimilarityExampleSelector with the created VectorStore and the - * options provided. - * @param examples The list of examples to be used. - * @param embeddings The instance of Embeddings to be used. - * @param vectorStoreCls The VectorStore class to be used. - * @param options The options object for the SemanticSimilarityExampleSelector. - * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. - */ - static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { - const inputKeys = options.inputKeys ?? null; - const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {}) : example).join(" ")); - const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options); - return new SemanticSimilarityExampleSelector({ - vectorStore, - k: options.k ?? 4, - exampleKeys: options.exampleKeys, - inputKeys: options.inputKeys - }); - } -}; - -//#endregion - -//# sourceMappingURL=semantic_similarity.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/index.js - - - - - - -//#region src/example_selectors/index.ts -var example_selectors_exports = {}; -__export(example_selectors_exports, { - BaseExampleSelector: () => BaseExampleSelector, - BasePromptSelector: () => BasePromptSelector, - ConditionalPromptSelector: () => ConditionalPromptSelector, - LengthBasedExampleSelector: () => LengthBasedExampleSelector, - SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, - isChatModel: () => isChatModel, - isLLM: () => isLLM -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/record_manager.js - - -//#region src/indexing/record_manager.ts -const UUIDV5_NAMESPACE = "10f90ea3-90a4-4962-bf75-83a0f3c1c62a"; -var RecordManager = class extends Serializable { - lc_namespace = ["langchain", "recordmanagers"]; -}; - -//#endregion - -//# sourceMappingURL=record_manager.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/base.js - - - - - - -//#region src/indexing/base.ts -/** -* HashedDocument is a Document with hashes calculated. -* Hashes are calculated based on page content and metadata. -* It is used for indexing. -*/ -var _HashedDocument = class { - uid; - hash_; - contentHash; - metadataHash; - pageContent; - metadata; - keyEncoder = sha256; - constructor(fields) { - this.uid = fields.uid; - this.pageContent = fields.pageContent; - this.metadata = fields.metadata; - } - makeDefaultKeyEncoder(keyEncoderFn) { - this.keyEncoder = keyEncoderFn; - } - calculateHashes() { - const forbiddenKeys = [ - "hash_", - "content_hash", - "metadata_hash" - ]; - for (const key of forbiddenKeys) if (key in this.metadata) throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(", ")}]`); - const contentHash = this._hashStringToUUID(this.pageContent); - try { - const metadataHash = this._hashNestedDictToUUID(this.metadata); - this.contentHash = contentHash; - this.metadataHash = metadataHash; - } catch (e) { - throw new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`); - } - this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash); - if (!this.uid) this.uid = this.hash_; - } - toDocument() { - return new Document({ - pageContent: this.pageContent, - metadata: this.metadata - }); - } - static fromDocument(document, uid) { - const doc = new this({ - pageContent: document.pageContent, - metadata: document.metadata, - uid: uid || document.uid - }); - doc.calculateHashes(); - return doc; - } - _hashStringToUUID(inputString) { - const hash_value = this.keyEncoder(inputString); - return v5(hash_value, UUIDV5_NAMESPACE); - } - _hashNestedDictToUUID(data) { - const serialized_data = JSON.stringify(data, Object.keys(data).sort()); - const hash_value = this.keyEncoder(serialized_data); - return v5(hash_value, UUIDV5_NAMESPACE); - } -}; -function _batch(size, iterable) { - const batches = []; - let currentBatch = []; - iterable.forEach((item) => { - currentBatch.push(item); - if (currentBatch.length >= size) { - batches.push(currentBatch); - currentBatch = []; - } - }); - if (currentBatch.length > 0) batches.push(currentBatch); - return batches; -} -function _deduplicateInOrder(hashedDocuments) { - const seen = /* @__PURE__ */ new Set(); - const deduplicated = []; - for (const hashedDoc of hashedDocuments) { - if (!hashedDoc.hash_) throw new Error("Hashed document does not have a hash"); - if (!seen.has(hashedDoc.hash_)) { - seen.add(hashedDoc.hash_); - deduplicated.push(hashedDoc); - } - } - return deduplicated; -} -function _getSourceIdAssigner(sourceIdKey) { - if (sourceIdKey === null) return (_doc) => null; - else if (typeof sourceIdKey === "string") return (doc) => doc.metadata[sourceIdKey]; - else if (typeof sourceIdKey === "function") return sourceIdKey; - else throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`); -} -const _isBaseDocumentLoader = (arg) => { - if ("load" in arg && typeof arg.load === "function" && "loadAndSplit" in arg && typeof arg.loadAndSplit === "function") return true; - return false; -}; -/** -* Index data from the doc source into the vector store. -* -* Indexing functionality uses a manager to keep track of which documents -* are in the vector store. -* -* This allows us to keep track of which documents were updated, and which -* documents were deleted, which documents should be skipped. -* -* For the time being, documents are indexed using their hashes, and users -* are not able to specify the uid of the document. -* -* @param {IndexArgs} args -* @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents. -* @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents. -* @param {VectorStore} args.vectorStore The vector store to use for storing the documents. -* @param {IndexOptions | undefined} args.options Options for indexing. -* @returns {Promise} -*/ -async function index(args) { - const { docsSource, recordManager, vectorStore, options } = args; - const { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1e3, forceUpdate = false } = options ?? {}; - if (cleanup === "incremental" && !sourceIdKey) throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'."); - const docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource; - const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null); - const indexStartDt = await recordManager.getTime(); - let numAdded = 0; - let numDeleted = 0; - let numUpdated = 0; - let numSkipped = 0; - const batches = _batch(batchSize ?? 100, docs); - for (const batch of batches) { - const hashedDocs = _deduplicateInOrder(batch.map((doc) => _HashedDocument.fromDocument(doc))); - const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc)); - if (cleanup === "incremental") hashedDocs.forEach((_hashedDoc, index$1) => { - const source = sourceIds[index$1]; - if (source === null) throw new Error("sourceIdKey must be provided when cleanup is incremental"); - }); - const batchExists = await recordManager.exists(hashedDocs.map((doc) => doc.uid)); - const uids = []; - const docsToIndex = []; - const docsToUpdate = []; - const seenDocs = /* @__PURE__ */ new Set(); - hashedDocs.forEach((hashedDoc, i) => { - const docExists = batchExists[i]; - if (docExists) if (forceUpdate) seenDocs.add(hashedDoc.uid); - else { - docsToUpdate.push(hashedDoc.uid); - return; - } - uids.push(hashedDoc.uid); - docsToIndex.push(hashedDoc.toDocument()); - }); - if (docsToUpdate.length > 0) { - await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt }); - numSkipped += docsToUpdate.length; - } - if (docsToIndex.length > 0) { - await vectorStore.addDocuments(docsToIndex, { ids: uids }); - numAdded += docsToIndex.length - seenDocs.size; - numUpdated += seenDocs.size; - } - await recordManager.update(hashedDocs.map((doc) => doc.uid), { - timeAtLeast: indexStartDt, - groupIds: sourceIds - }); - if (cleanup === "incremental") { - sourceIds.forEach((sourceId) => { - if (!sourceId) throw new Error("Source id cannot be null"); - }); - const uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - groupIds: sourceIds - }); - if (uidsToDelete.length > 0) { - await vectorStore.delete({ ids: uidsToDelete }); - await recordManager.deleteKeys(uidsToDelete); - numDeleted += uidsToDelete.length; - } - } - } - if (cleanup === "full") { - let uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - limit: cleanupBatchSize - }); - while (uidsToDelete.length > 0) { - await vectorStore.delete({ ids: uidsToDelete }); - await recordManager.deleteKeys(uidsToDelete); - numDeleted += uidsToDelete.length; - uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - limit: cleanupBatchSize - }); - } - } - return { - numAdded, - numDeleted, - numUpdated, - numSkipped - }; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/index.js - - - - -//#region src/indexing/index.ts -var indexing_exports = {}; -__export(indexing_exports, { - RecordManager: () => RecordManager, - UUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE, - _HashedDocument: () => _HashedDocument, - _batch: () => _batch, - _deduplicateInOrder: () => _deduplicateInOrder, - _getSourceIdAssigner: () => _getSourceIdAssigner, - _isBaseDocumentLoader: () => _isBaseDocumentLoader, - index: () => index -}); - -//#endregion - -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ./node_modules/base64-js/index.js -var base64_js = __nccwpck_require__(8793); -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js - - -var chunk_VL2OQCWN_defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? chunk_VL2OQCWN_defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; - -// src/utils.ts -function never(_) { -} -function bytePairMerge(piece, ranks) { - let parts = Array.from( - { length: piece.length }, - (_, i) => ({ start: i, end: i + 1 }) - ); - while (parts.length > 1) { - let minRank = null; - for (let i = 0; i < parts.length - 1; i++) { - const slice = piece.slice(parts[i].start, parts[i + 1].end); - const rank = ranks.get(slice.join(",")); - if (rank == null) - continue; - if (minRank == null || rank < minRank[0]) { - minRank = [rank, i]; - } - } - if (minRank != null) { - const i = minRank[1]; - parts[i] = { start: parts[i].start, end: parts[i + 1].end }; - parts.splice(i + 1, 1); - } else { - break; - } - } - return parts; -} -function bytePairEncode(piece, ranks) { - if (piece.length === 1) - return [ranks.get(piece.join(","))]; - return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); -} -function chunk_VL2OQCWN_escapeRegex(str) { - return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); -} -var _Tiktoken = class { - /** @internal */ - specialTokens; - /** @internal */ - inverseSpecialTokens; - /** @internal */ - patStr; - /** @internal */ - textEncoder = new TextEncoder(); - /** @internal */ - textDecoder = new TextDecoder("utf-8"); - /** @internal */ - rankMap = /* @__PURE__ */ new Map(); - /** @internal */ - textMap = /* @__PURE__ */ new Map(); - constructor(ranks, extendedSpecialTokens) { - this.patStr = ranks.pat_str; - const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { - const [_, offsetStr, ...tokens] = x.split(" "); - const offset = Number.parseInt(offsetStr, 10); - tokens.forEach((token, i) => memo[token] = offset + i); - return memo; - }, {}); - for (const [token, rank] of Object.entries(uncompressed)) { - const bytes = base64_js.toByteArray(token); - this.rankMap.set(bytes.join(","), rank); - this.textMap.set(rank, bytes); - } - this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; - this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { - memo[rank] = this.textEncoder.encode(text); - return memo; - }, {}); - } - encode(text, allowedSpecial = [], disallowedSpecial = "all") { - const regexes = new RegExp(this.patStr, "ug"); - const specialRegex = _Tiktoken.specialTokenRegex( - Object.keys(this.specialTokens) - ); - const ret = []; - const allowedSpecialSet = new Set( - allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial - ); - const disallowedSpecialSet = new Set( - disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( - (x) => !allowedSpecialSet.has(x) - ) : disallowedSpecial - ); - if (disallowedSpecialSet.size > 0) { - const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ - ...disallowedSpecialSet - ]); - const specialMatch = text.match(disallowedSpecialRegex); - if (specialMatch != null) { - throw new Error( - `The text contains a special token that is not allowed: ${specialMatch[0]}` - ); - } - } - let start = 0; - while (true) { - let nextSpecial = null; - let startFind = start; - while (true) { - specialRegex.lastIndex = startFind; - nextSpecial = specialRegex.exec(text); - if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) - break; - startFind = nextSpecial.index + 1; - } - const end = nextSpecial?.index ?? text.length; - for (const match of text.substring(start, end).matchAll(regexes)) { - const piece = this.textEncoder.encode(match[0]); - const token2 = this.rankMap.get(piece.join(",")); - if (token2 != null) { - ret.push(token2); - continue; - } - ret.push(...bytePairEncode(piece, this.rankMap)); - } - if (nextSpecial == null) - break; - let token = this.specialTokens[nextSpecial[0]]; - ret.push(token); - start = nextSpecial.index + nextSpecial[0].length; - } - return ret; - } - decode(tokens) { - const res = []; - let length = 0; - for (let i2 = 0; i2 < tokens.length; ++i2) { - const token = tokens[i2]; - const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; - if (bytes != null) { - res.push(bytes); - length += bytes.length; - } - } - const mergedArray = new Uint8Array(length); - let i = 0; - for (const bytes of res) { - mergedArray.set(bytes, i); - i += bytes.length; - } - return this.textDecoder.decode(mergedArray); - } -}; -var Tiktoken = _Tiktoken; -__publicField(Tiktoken, "specialTokenRegex", (tokens) => { - return new RegExp(tokens.map((i) => chunk_VL2OQCWN_escapeRegex(i)).join("|"), "g"); -}); -function getEncodingNameForModel(model) { - switch (model) { - case "gpt2": { - return "gpt2"; - } - case "code-cushman-001": - case "code-cushman-002": - case "code-davinci-001": - case "code-davinci-002": - case "cushman-codex": - case "davinci-codex": - case "davinci-002": - case "text-davinci-002": - case "text-davinci-003": { - return "p50k_base"; - } - case "code-davinci-edit-001": - case "text-davinci-edit-001": { - return "p50k_edit"; - } - case "ada": - case "babbage": - case "babbage-002": - case "code-search-ada-code-001": - case "code-search-babbage-code-001": - case "curie": - case "davinci": - case "text-ada-001": - case "text-babbage-001": - case "text-curie-001": - case "text-davinci-001": - case "text-search-ada-doc-001": - case "text-search-babbage-doc-001": - case "text-search-curie-doc-001": - case "text-search-davinci-doc-001": - case "text-similarity-ada-001": - case "text-similarity-babbage-001": - case "text-similarity-curie-001": - case "text-similarity-davinci-001": { - return "r50k_base"; - } - case "gpt-3.5-turbo-instruct-0914": - case "gpt-3.5-turbo-instruct": - case "gpt-3.5-turbo-16k-0613": - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo": - case "gpt-4-32k-0613": - case "gpt-4-32k-0314": - case "gpt-4-32k": - case "gpt-4-0613": - case "gpt-4-0314": - case "gpt-4": - case "gpt-3.5-turbo-1106": - case "gpt-35-turbo": - case "gpt-4-1106-preview": - case "gpt-4-vision-preview": - case "gpt-3.5-turbo-0125": - case "gpt-4-turbo": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-turbo-preview": - case "gpt-4-0125-preview": - case "text-embedding-ada-002": - case "text-embedding-3-small": - case "text-embedding-3-large": { - return "cl100k_base"; - } - case "gpt-4o": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": - case "gpt-4o-2024-11-20": - case "gpt-4o-mini-2024-07-18": - case "gpt-4o-mini": - case "gpt-4o-search-preview": - case "gpt-4o-search-preview-2025-03-11": - case "gpt-4o-mini-search-preview": - case "gpt-4o-mini-search-preview-2025-03-11": - case "gpt-4o-audio-preview": - case "gpt-4o-audio-preview-2024-12-17": - case "gpt-4o-audio-preview-2024-10-01": - case "gpt-4o-mini-audio-preview": - case "gpt-4o-mini-audio-preview-2024-12-17": - case "o1": - case "o1-2024-12-17": - case "o1-mini": - case "o1-mini-2024-09-12": - case "o1-preview": - case "o1-preview-2024-09-12": - case "o1-pro": - case "o1-pro-2025-03-19": - case "o3": - case "o3-2025-04-16": - case "o3-mini": - case "o3-mini-2025-01-31": - case "o4-mini": - case "o4-mini-2025-04-16": - case "chatgpt-4o-latest": - case "gpt-4o-realtime": - case "gpt-4o-realtime-preview-2024-10-01": - case "gpt-4o-realtime-preview-2024-12-17": - case "gpt-4o-mini-realtime-preview": - case "gpt-4o-mini-realtime-preview-2024-12-17": - case "gpt-4.1": - case "gpt-4.1-2025-04-14": - case "gpt-4.1-mini": - case "gpt-4.1-mini-2025-04-14": - case "gpt-4.1-nano": - case "gpt-4.1-nano-2025-04-14": - case "gpt-4.5-preview": - case "gpt-4.5-preview-2025-02-27": - case "gpt-5": - case "gpt-5-2025-08-07": - case "gpt-5-nano": - case "gpt-5-nano-2025-08-07": - case "gpt-5-mini": - case "gpt-5-mini-2025-08-07": - case "gpt-5-chat-latest": { - return "o200k_base"; - } - default: - throw new Error("Unknown model"); - } -} - - - -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js - - - - -//#region src/utils/tiktoken.ts -var tiktoken_exports = {}; -__export(tiktoken_exports, { - encodingForModel: () => encodingForModel, - getEncoding: () => getEncoding -}); -const cache = {}; -const caller = /* @__PURE__ */ new async_caller_AsyncCaller({}); -async function getEncoding(encoding) { - if (!(encoding in cache)) cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => { - delete cache[encoding]; - throw e; - }); - return await cache[encoding]; -} -async function encodingForModel(model) { - return getEncoding(getEncodingNameForModel(model)); -} - -//#endregion - -//# sourceMappingURL=tiktoken.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js - - - - - - - - -//#region src/language_models/base.ts -var language_models_base_base_exports = {}; -__export(language_models_base_base_exports, { - BaseLangChain: () => BaseLangChain, - BaseLanguageModel: () => BaseLanguageModel, - calculateMaxTokens: () => calculateMaxTokens, - getEmbeddingContextSize: () => getEmbeddingContextSize, - getModelContextSize: () => getModelContextSize, - getModelNameForTiktoken: () => getModelNameForTiktoken, - isOpenAITool: () => isOpenAITool -}); -const getModelNameForTiktoken = (modelName) => { - if (modelName.startsWith("gpt-3.5-turbo-16k")) return "gpt-3.5-turbo-16k"; - if (modelName.startsWith("gpt-3.5-turbo-")) return "gpt-3.5-turbo"; - if (modelName.startsWith("gpt-4-32k")) return "gpt-4-32k"; - if (modelName.startsWith("gpt-4-")) return "gpt-4"; - if (modelName.startsWith("gpt-4o")) return "gpt-4o"; - return modelName; -}; -const getEmbeddingContextSize = (modelName) => { - switch (modelName) { - case "text-embedding-ada-002": return 8191; - default: return 2046; - } -}; -const getModelContextSize = (modelName) => { - switch (getModelNameForTiktoken(modelName)) { - case "gpt-3.5-turbo-16k": return 16384; - case "gpt-3.5-turbo": return 4096; - case "gpt-4-32k": return 32768; - case "gpt-4": return 8192; - case "text-davinci-003": return 4097; - case "text-curie-001": return 2048; - case "text-babbage-001": return 2048; - case "text-ada-001": return 2048; - case "code-davinci-002": return 8e3; - case "code-cushman-001": return 2048; - default: return 4097; - } -}; -/** -* Whether or not the input matches the OpenAI tool definition. -* @param {unknown} tool The input to check. -* @returns {boolean} Whether the input is an OpenAI tool definition. -*/ -function isOpenAITool(tool) { - if (typeof tool !== "object" || !tool) return false; - if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.function) return true; - return false; -} -const calculateMaxTokens = async ({ prompt, modelName }) => { - let numTokens; - try { - numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; - } catch { - console.warn("Failed to calculate number of tokens, falling back to approximate count"); - numTokens = Math.ceil(prompt.length / 4); - } - const maxTokens = getModelContextSize(modelName); - return maxTokens - numTokens; -}; -const getVerbosity = () => false; -/** -* Base class for language models, chains, tools. -*/ -var BaseLangChain = class extends Runnable { - /** - * Whether to print out response text. - */ - verbose; - callbacks; - tags; - metadata; - get lc_attributes() { - return { - callbacks: void 0, - verbose: void 0 - }; - } - constructor(params) { - super(params); - this.verbose = params.verbose ?? getVerbosity(); - this.callbacks = params.callbacks; - this.tags = params.tags ?? []; - this.metadata = params.metadata ?? {}; - } -}; -/** -* Base class for language models. -*/ -var BaseLanguageModel = class extends BaseLangChain { - /** - * Keys that the language model accepts as call options. - */ - get callKeys() { - return [ - "stop", - "timeout", - "signal", - "tags", - "metadata", - "callbacks" - ]; - } - /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. - */ - caller; - cache; - constructor({ callbacks, callbackManager,...params }) { - const { cache,...rest } = params; - super({ - callbacks: callbacks ?? callbackManager, - ...rest - }); - if (typeof cache === "object") this.cache = cache; - else if (cache) this.cache = InMemoryCache.global(); - else this.cache = void 0; - this.caller = new async_caller_AsyncCaller(params ?? {}); - } - _encoding; - /** - * Get the number of tokens in the content. - * @param content The content to get the number of tokens for. - * @returns The number of tokens in the content. - */ - async getNumTokens(content) { - let textContent; - if (typeof content === "string") textContent = content; - else - /** - * Content is an array of ContentBlock - * - * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content. - * We need to find a better way to do this. - * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116 - */ - textContent = content.map((item) => { - if (typeof item === "string") return item; - if (item.type === "text" && "text" in item) return item.text; - return ""; - }).join(""); - let numTokens = Math.ceil(textContent.length / 4); - if (!this._encoding) try { - this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); - } catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } - if (this._encoding) try { - numTokens = this._encoding.encode(textContent).length; - } catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } - return numTokens; - } - static _convertInputToPromptValue(input) { - if (typeof input === "string") return new StringPromptValue(input); - else if (Array.isArray(input)) return new ChatPromptValue(input.map(utils_coerceMessageLikeToMessage)); - else return input; - } - /** - * Get the identifying parameters of the LLM. - */ - _identifyingParams() { - return {}; - } - /** - * Create a unique cache key for a specific call to a specific language model. - * @param callOptions Call options for the model - * @returns A unique cache key. - */ - _getSerializedCacheKeyParametersForCall({ config,...callOptions }) { - const params = { - ...this._identifyingParams(), - ...callOptions, - _type: this._llmType(), - _model: this._modelType() - }; - const filteredEntries = Object.entries(params).filter(([_, value]) => value !== void 0); - const serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); - return serializedEntries; - } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType() - }; - } - /** - * @deprecated - * Load an LLM from a json-like object describing it. - */ - static async deserialize(_data) { - throw new Error("Use .toJSON() instead"); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js - - - - -//#region src/runnables/passthrough.ts -/** -* A runnable to passthrough inputs unchanged or with additional keys. -* -* This runnable behaves almost like the identity function, except that it -* can be configured to add additional keys to the output, if the input is -* an object. -* -* The example below demonstrates how to use `RunnablePassthrough to -* passthrough the input from the `.invoke()` -* -* @example -* ```typescript -* const chain = RunnableSequence.from([ -* { -* question: new RunnablePassthrough(), -* context: async () => loadContextFromStore(), -* }, -* prompt, -* llm, -* outputParser, -* ]); -* const response = await chain.invoke( -* "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." -* ); -* ``` -*/ -var RunnablePassthrough = class extends Runnable { - static lc_name() { - return "RunnablePassthrough"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - func; - constructor(fields) { - super(fields); - if (fields) this.func = fields.func; - } - async invoke(input, options) { - const config = ensureConfig(options); - if (this.func) await this.func(input, config); - return this._callWithConfig((input$1) => Promise.resolve(input$1), input, config); - } - async *transform(generator, options) { - const config = ensureConfig(options); - let finalOutput; - let finalOutputSupported = true; - for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - if (this.func && finalOutput !== void 0) await this.func(finalOutput, config); - } - /** - * A runnable that assigns key-value pairs to the input. - * - * The example below shows how you could use it with an inline function. - * - * @example - * ```typescript - * const prompt = - * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} - * Question: {question} - * SQL Query:`); - * - * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` - * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. - * // In this case, we're passing the schema. - * const sqlQueryGeneratorChain = RunnableSequence.from([ - * RunnablePassthrough.assign({ - * schema: async () => db.getTableInfo(), - * }), - * prompt, - * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), - * new StringOutputParser(), - * ]); - * const result = await sqlQueryGeneratorChain.invoke({ - * question: "How many employees are there?", - * }); - * ``` - */ - static assign(mapping) { - return new RunnableAssign(new RunnableMap({ steps: mapping })); - } -}; - -//#endregion - -//# sourceMappingURL=passthrough.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/utils.js -//#region src/language_models/utils.ts -const language_models_utils_iife = (fn) => fn(); -function castStandardMessageContent(message) { - const Cls = message.constructor; - return new Cls({ - ...message, - content: message.contentBlocks, - response_metadata: { - ...message.response_metadata, - output_version: "v1" - } - }); -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js - - - - - - - - - - - - - - - - - - -//#region src/language_models/chat_models.ts -var chat_models_exports = {}; -__export(chat_models_exports, { - BaseChatModel: () => BaseChatModel, - SimpleChatModel: () => SimpleChatModel -}); -function _formatForTracing(messages) { - const messagesToTrace = []; - for (const message of messages) { - let messageToTrace = message; - if (Array.isArray(message.content)) for (let idx = 0; idx < message.content.length; idx++) { - const block = message.content[idx]; - if (isURLContentBlock(block) || isBase64ContentBlock(block)) { - if (messageToTrace === message) messageToTrace = new message.constructor({ - ...messageToTrace, - content: [ - ...message.content.slice(0, idx), - convertToOpenAIImageBlock(block), - ...message.content.slice(idx + 1) - ] - }); - } - } - messagesToTrace.push(messageToTrace); - } - return messagesToTrace; -} -/** -* Base class for chat models. It extends the BaseLanguageModel class and -* provides methods for generating chat based on input messages. -*/ -var BaseChatModel = class BaseChatModel extends BaseLanguageModel { - lc_namespace = [ - "langchain", - "chat_models", - this._llmType() - ]; - disableStreaming = false; - outputVersion; - get callKeys() { - return [...super.callKeys, "outputVersion"]; - } - constructor(fields) { - super(fields); - this.outputVersion = language_models_utils_iife(() => { - const outputVersion = fields.outputVersion ?? getEnvironmentVariable("LC_OUTPUT_VERSION"); - if (outputVersion && ["v0", "v1"].includes(outputVersion)) return outputVersion; - return "v0"; - }); - } - _separateRunnableConfigFromCallOptionsCompat(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; - } - /** - * Invokes the chat model with a single input. - * @param input The input for the language model. - * @param options The call options. - * @returns A Promise that resolves to a BaseMessageChunk. - */ - async invoke(input, options) { - const promptValue = BaseChatModel._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - const chatGeneration = result.generations[0][0]; - return chatGeneration.message; - } - async *_streamResponseChunks(_messages, _options, _runManager) { - throw new Error("Not implemented."); - } - async *_streamIterator(input, options) { - if (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) yield this.invoke(input, options); - else { - const prompt = BaseChatModel._convertInputToPromptValue(input); - const messages = prompt.toChatMessages(); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const inheritableMetadata = { - ...runnableConfig.metadata, - ...this.getLsParams(callOptions) - }; - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), - batch_size: 1 - }; - const outputVersion = callOptions.outputVersion ?? this.outputVersion; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); - let generationChunk; - let llmOutput; - try { - for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) chunk.message._updateId(`run-${runId}`); - } - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - if (outputVersion === "v1") yield castStandardMessageContent(chunk.message); - else yield chunk.message; - if (!generationChunk) generationChunk = chunk; - else generationChunk = generationChunk.concat(chunk); - if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens - } }; - } - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - generations: [[generationChunk]], - llmOutput - }))); - } - } - getLsParams(options) { - const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); - return { - ls_model_type: "chat", - ls_stop: options.stop, - ls_provider: providerName - }; - } - /** @ignore */ - async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { - const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); - let runManagers; - if (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) runManagers = startedRunManagers; - else { - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions) - }; - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1 - }; - runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); - } - const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; - const generations = []; - const llmOutputs = []; - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) try { - const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); - let aggregated; - let llmOutput; - for await (const chunk of stream) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) chunk.message._updateId(`run-${runId}`); - } - if (aggregated === void 0) aggregated = chunk; - else aggregated = concat(aggregated, chunk); - if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens - } }; - } - if (aggregated === void 0) throw new Error("Received empty response from chat model call."); - generations.push([aggregated]); - await runManagers?.[0].handleLLMEnd({ - generations, - llmOutput - }); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - else { - const results = await Promise.allSettled(baseMessages.map(async (messageList, i) => { - const generateResults = await this._generate(messageList, { - ...parsedOptions, - promptIndex: i - }, runManagers?.[i]); - if (outputVersion === "v1") for (const generation of generateResults.generations) generation.message = castStandardMessageContent(generation.message); - return generateResults; - })); - await Promise.all(results.map(async (pResult, i) => { - if (pResult.status === "fulfilled") { - const result = pResult.value; - for (const generation of result.generations) { - if (generation.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) generation.message._updateId(`run-${runId}`); - } - generation.message.response_metadata = { - ...generation.generationInfo, - ...generation.message.response_metadata - }; - } - if (result.generations.length === 1) result.generations[0].message.response_metadata = { - ...result.llmOutput, - ...result.generations[0].message.response_metadata - }; - generations[i] = result.generations; - llmOutputs[i] = result.llmOutput; - return runManagers?.[i]?.handleLLMEnd({ - generations: [result.generations], - llmOutput: result.llmOutput - }); - } else { - await runManagers?.[i]?.handleLLMError(pResult.reason); - return Promise.reject(pResult.reason); - } - })); - } - const output = { - generations, - llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0 - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, - configurable: true - }); - return output; - } - async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions }) { - const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions) - }; - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1 - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); - const missingPromptIndices = []; - const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { - const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); - const result = await cache.lookup(prompt, llmStringKey); - if (result == null) missingPromptIndices.push(index); - return result; - })); - const cachedResults = results.map((result, index) => ({ - result, - runManager: runManagers?.[index] - })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); - const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result$1) => { - if ("message" in result$1 && isBaseMessage(result$1.message) && isAIMessage(result$1.message)) { - result$1.message.usage_metadata = { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0 - }; - if (outputVersion === "v1") result$1.message = castStandardMessageContent(result$1.message); - } - result$1.generationInfo = { - ...result$1.generationInfo, - tokenUsage: {} - }; - return result$1; - }); - if (result.length) await runManager?.handleLLMNewToken(result[0].text); - return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); - } else { - await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, - configurable: true - }); - return output; - } - /** - * Generates chat based on the input messages. - * @param messages An array of arrays of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generate(messages, options, callbacks) { - let parsedOptions; - if (Array.isArray(options)) parsedOptions = { stop: options }; - else parsedOptions = options; - const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) return this._generateUncached(baseMessages, callOptions, runnableConfig); - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - messages: baseMessages, - cache, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); - return cache.update(prompt, llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { - generations, - llmOutput - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(_options) { - return {}; - } - _modelType() { - return "base_chat_model"; - } - /** - * Generates a prompt based on the input prompt values. - * @param promptValues An array of BasePromptValue instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generatePrompt(promptValues, options, callbacks) { - const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); - return this.generate(promptMessages, options, callbacks); - } - withStructuredOutput(outputSchema, config) { - if (typeof this.bindTools !== "function") throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); - if (config?.strict) throw new Error(`"strict" mode is not supported for this model by default.`); - const schema = outputSchema; - const name = config?.name; - const description = getSchemaDescription(schema) ?? "A function available to call."; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); - let functionName = name ?? "extract"; - let tools; - if (isInteropZodSchema(schema)) tools = [{ - type: "function", - function: { - name: functionName, - description, - parameters: toJsonSchema(schema) - } - }]; - else { - if ("name" in schema) functionName = schema.name; - tools = [{ - type: "function", - function: { - name: functionName, - description, - parameters: schema - } - }]; - } - const llm = this.bindTools(tools); - const outputParser = RunnableLambda.from((input) => { - if (!AIMessageChunk.isInstance(input)) throw new Error("Input is not an AIMessageChunk."); - if (!input.tool_calls || input.tool_calls.length === 0) throw new Error("No tool calls found in the response."); - const toolCall = input.tool_calls.find((tc) => tc.name === functionName); - if (!toolCall) throw new Error(`No tool call found with name ${functionName}.`); - return toolCall.args; - }); - if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "StructuredOutput" }); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); - } -}; -/** -* An abstract class that extends BaseChatModel and provides a simple -* implementation of _generate. -*/ -var SimpleChatModel = class extends BaseChatModel { - async _generate(messages, options, runManager) { - const text = await this._call(messages, options, runManager); - const message = new AIMessage(text); - if (typeof message.content !== "string") throw new Error("Cannot generate with a simple chat model when output is not a string."); - return { generations: [{ - text: message.content, - message - }] }; - } -}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/llms.js - - - - - - - -//#region src/language_models/llms.ts -var llms_exports = {}; -__export(llms_exports, { - BaseLLM: () => BaseLLM, - LLM: () => LLM -}); -/** -* LLM Wrapper. Takes in a prompt (or prompts) and returns a string. -*/ -var BaseLLM = class BaseLLM extends BaseLanguageModel { - lc_namespace = [ - "langchain", - "llms", - this._llmType() - ]; - /** - * This method takes an input and options, and returns a string. It - * converts the input to a prompt value and generates a result based on - * the prompt. - * @param input Input for the LLM. - * @param options Options for the LLM call. - * @returns A string result based on the prompt. - */ - async invoke(input, options) { - const promptValue = BaseLLM._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - return result.generations[0][0].text; - } - async *_streamResponseChunks(_input, _options, _runManager) { - throw new Error("Not implemented."); - } - _separateRunnableConfigFromCallOptionsCompat(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; - } - async *_streamIterator(input, options) { - if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) yield this.invoke(input, options); - else { - const prompt = BaseLLM._convertInputToPromptValue(input); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), - batch_size: 1 - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); - let generation = new GenerationChunk({ text: "" }); - try { - for await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) { - if (!generation) generation = chunk; - else generation = generation.concat(chunk); - if (typeof chunk.text === "string") yield chunk.text; - } - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] }))); - } - } - /** - * This method takes prompt values, options, and callbacks, and generates - * a result based on the prompts. - * @param promptValues Prompt values for the LLM. - * @param options Options for the LLM call. - * @param callbacks Callbacks for the LLM call. - * @returns An LLMResult based on the prompts. - */ - async generatePrompt(promptValues, options, callbacks) { - const prompts = promptValues.map((promptValue) => promptValue.toString()); - return this.generate(prompts, options, callbacks); - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(_options) { - return {}; - } - _flattenLLMResult(llmResult) { - const llmResults = []; - for (let i = 0; i < llmResult.generations.length; i += 1) { - const genList = llmResult.generations[i]; - if (i === 0) llmResults.push({ - generations: [genList], - llmOutput: llmResult.llmOutput - }); - else { - const llmOutput = llmResult.llmOutput ? { - ...llmResult.llmOutput, - tokenUsage: {} - } : void 0; - llmResults.push({ - generations: [genList], - llmOutput - }); - } - } - return llmResults; - } - /** @ignore */ - async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { - let runManagers; - if (startedRunManagers !== void 0 && startedRunManagers.length === prompts.length) runManagers = startedRunManagers; - else { - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: prompts.length - }; - runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions?.runName); - } - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - let output; - if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks) try { - const stream = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); - let aggregated; - for await (const chunk of stream) if (aggregated === void 0) aggregated = chunk; - else aggregated = concat(aggregated, chunk); - if (aggregated === void 0) throw new Error("Received empty response from chat model call."); - output = { - generations: [[aggregated]], - llmOutput: {} - }; - await runManagers?.[0].handleLLMEnd(output); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - else { - try { - output = await this._generate(prompts, parsedOptions, runManagers?.[0]); - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - const flattenedOutputs = this._flattenLLMResult(output); - await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); - } - const runIds = runManagers?.map((manager) => manager.runId) || void 0; - Object.defineProperty(output, RUN_KEY, { - value: runIds ? { runIds } : void 0, - configurable: true - }); - return output; - } - async _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, runId }) { - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: prompts.length - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, void 0, extra, void 0, void 0, handledOptions?.runName); - const missingPromptIndices = []; - const results = await Promise.allSettled(prompts.map(async (prompt, index) => { - const result = await cache.lookup(prompt, llmStringKey); - if (result == null) missingPromptIndices.push(index); - return result; - })); - const cachedResults = results.map((result, index) => ({ - result, - runManager: runManagers?.[index] - })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result$1) => { - result$1.generationInfo = { - ...result$1.generationInfo, - tokenUsage: {} - }; - return result$1; - }); - if (result.length) await runManager?.handleLLMNewToken(result[0].text); - return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); - } else { - await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, - configurable: true - }); - return output; - } - /** - * Run the LLM on the given prompts and input, handling caching. - */ - async generate(prompts, options, callbacks) { - if (!Array.isArray(prompts)) throw new Error("Argument 'prompts' is expected to be a string[]"); - let parsedOptions; - if (Array.isArray(options)) parsedOptions = { stop: options }; - else parsedOptions = options; - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) return this._generateUncached(prompts, callOptions, runnableConfig); - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - prompts, - cache, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig, - runId: runnableConfig.runId - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - return cache.update(prompts[promptIndex], llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { - generations, - llmOutput - }; - } - /** - * Get the identifying parameters of the LLM. - */ - _identifyingParams() { - return {}; - } - _modelType() { - return "base_llm"; - } -}; -/** -* LLM class that provides a simpler interface to subclass than {@link BaseLLM}. -* -* Requires only implementing a simpler {@link _call} method instead of {@link _generate}. -* -* @augments BaseLLM -*/ -var LLM = class extends BaseLLM { - async _generate(prompts, options, runManager) { - const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { - ...options, - promptIndex - }, runManager).then((text) => [{ text }]))); - return { generations }; - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js - - - -//#region src/runnables/router.ts -/** -* A runnable that routes to a set of runnables based on Input['key']. -* Returns the output of the selected runnable. -* @example -* ```typescript -* import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; -* -* const router = new RouterRunnable({ -* runnables: { -* toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), -* reverseText: RunnableLambda.from((text: string) => -* text.split("").reverse().join("") -* ), -* }, -* }); -* -* // Invoke the 'reverseText' runnable -* const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); -* -* // "dlroW olleH" -* -* // Invoke the 'toUpperCase' runnable -* const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); -* -* // "HELLO WORLD" -* ``` -*/ -var RouterRunnable = class extends Runnable { - static lc_name() { - return "RouterRunnable"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - runnables; - constructor(fields) { - super(fields); - this.runnables = fields.runnables; - } - async invoke(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === void 0) throw new Error(`No runnable associated with key "${key}".`); - return runnable.invoke(actualInput, ensureConfig(options)); - } - async batch(inputs, options, batchOptions) { - const keys = inputs.map((input) => input.key); - const actualInputs = inputs.map((input) => input.input); - const missingKey = keys.find((key) => this.runnables[key] === void 0); - if (missingKey !== void 0) throw new Error(`One or more keys do not have a corresponding runnable.`); - const runnables = keys.map((key) => this.runnables[key]); - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; - const batchResults = []; - for (let i = 0; i < actualInputs.length; i += batchSize) { - const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i$1) => runnables[i$1].invoke(actualInput, optionsList[i$1])); - const batchResult = await Promise.all(batchPromises); - batchResults.push(batchResult); - } - return batchResults.flat(); - } - async stream(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === void 0) throw new Error(`No runnable associated with key "${key}".`); - return runnable.stream(actualInput, options); - } -}; - -//#endregion - -//# sourceMappingURL=router.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js - - - - -//#region src/runnables/branch.ts -/** -* Class that represents a runnable branch. The RunnableBranch is -* initialized with an array of branches and a default branch. When invoked, -* it evaluates the condition of each branch in order and executes the -* corresponding branch if the condition is true. If none of the conditions -* are true, it executes the default branch. -* @example -* ```typescript -* const branch = RunnableBranch.from([ -* [ -* (x: { topic: string; question: string }) => -* x.topic.toLowerCase().includes("anthropic"), -* anthropicChain, -* ], -* [ -* (x: { topic: string; question: string }) => -* x.topic.toLowerCase().includes("langchain"), -* langChainChain, -* ], -* generalChain, -* ]); -* -* const fullChain = RunnableSequence.from([ -* { -* topic: classificationChain, -* question: (input: { question: string }) => input.question, -* }, -* branch, -* ]); -* -* const result = await fullChain.invoke({ -* question: "how do I use LangChain?", -* }); -* ``` -*/ -var RunnableBranch = class extends Runnable { - static lc_name() { - return "RunnableBranch"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - default; - branches; - constructor(fields) { - super(fields); - this.branches = fields.branches; - this.default = fields.default; - } - /** - * Convenience method for instantiating a RunnableBranch from - * RunnableLikes (objects, functions, or Runnables). - * - * Each item in the input except for the last one should be a - * tuple with two items. The first is a "condition" RunnableLike that - * returns "true" if the second RunnableLike in the tuple should run. - * - * The final item in the input should be a RunnableLike that acts as a - * default branch if no other branches match. - * - * @example - * ```ts - * import { RunnableBranch } from "@langchain/core/runnables"; - * - * const branch = RunnableBranch.from([ - * [(x: number) => x > 0, (x: number) => x + 1], - * [(x: number) => x < 0, (x: number) => x - 1], - * (x: number) => x - * ]); - * ``` - * @param branches An array where the every item except the last is a tuple of [condition, runnable] - * pairs. The last item is a default runnable which is invoked if no other condition matches. - * @returns A new RunnableBranch. - */ - static from(branches) { - if (branches.length < 1) throw new Error("RunnableBranch requires at least one branch"); - const branchLikes = branches.slice(0, -1); - const coercedBranches = branchLikes.map(([condition, runnable]) => [_coerceToRunnable(condition), _coerceToRunnable(runnable)]); - const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); - return new this({ - branches: coercedBranches, - default: defaultBranch - }); - } - async _invoke(input, config, runManager) { - let result; - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) })); - if (conditionValue) { - result = await branchRunnable.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); - break; - } - } - if (!result) result = await this.default.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); - return result; - } - async invoke(input, config = {}) { - return this._callWithConfig(this._invoke, input, config); - } - async *_streamIterator(input, config) { - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, void 0, void 0, void 0, config?.runName); - let finalOutput; - let finalOutputSupported = true; - let stream; - try { - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) })); - if (conditionValue) { - stream = await branchRunnable.stream(input, config_patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - break; - } - } - if (stream === void 0) { - stream = await this.default.stream(input, config_patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}); - } -}; - -//#endregion - -//# sourceMappingURL=branch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js - - - - - - - -//#region src/runnables/history.ts -/** -* Wraps a LCEL chain and manages history. It appends input messages -* and chain outputs as history, and adds the current history messages to -* the chain input. -* @example -* ```typescript -* // pnpm install @langchain/anthropic @langchain/community @upstash/redis -* -* import { -* ChatPromptTemplate, -* MessagesPlaceholder, -* } from "@langchain/core/prompts"; -* import { ChatAnthropic } from "@langchain/anthropic"; -* import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; -* // For demos, you can also use an in-memory store: -* // import { ChatMessageHistory } from "@langchain/classic/stores/message/in_memory"; -* -* const prompt = ChatPromptTemplate.fromMessages([ -* ["system", "You're an assistant who's good at {ability}"], -* new MessagesPlaceholder("history"), -* ["human", "{question}"], -* ]); -* -* const chain = prompt.pipe(new ChatAnthropic({})); -* -* const chainWithHistory = new RunnableWithMessageHistory({ -* runnable: chain, -* getMessageHistory: (sessionId) => -* new UpstashRedisChatMessageHistory({ -* sessionId, -* config: { -* url: process.env.UPSTASH_REDIS_REST_URL!, -* token: process.env.UPSTASH_REDIS_REST_TOKEN!, -* }, -* }), -* inputMessagesKey: "question", -* historyMessagesKey: "history", -* }); -* -* const result = await chainWithHistory.invoke( -* { -* ability: "math", -* question: "What does cosine mean?", -* }, -* { -* configurable: { -* sessionId: "some_string_identifying_a_user", -* }, -* } -* ); -* -* const result2 = await chainWithHistory.invoke( -* { -* ability: "math", -* question: "What's its inverse?", -* }, -* { -* configurable: { -* sessionId: "some_string_identifying_a_user", -* }, -* } -* ); -* ``` -*/ -var RunnableWithMessageHistory = class extends RunnableBinding { - runnable; - inputMessagesKey; - outputMessagesKey; - historyMessagesKey; - getMessageHistory; - constructor(fields) { - let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); - const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; - if (messagesKey) historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); - const bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run, config$1) => this._exitHistory(run, config$1 ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); - const config = fields.config ?? {}; - super({ - ...fields, - config, - bound - }); - this.runnable = fields.runnable; - this.getMessageHistory = fields.getMessageHistory; - this.inputMessagesKey = fields.inputMessagesKey; - this.outputMessagesKey = fields.outputMessagesKey; - this.historyMessagesKey = fields.historyMessagesKey; - } - _getInputMessages(inputValue) { - let parsedInputValue; - if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { - let key; - if (this.inputMessagesKey) key = this.inputMessagesKey; - else if (Object.keys(inputValue).length === 1) key = Object.keys(inputValue)[0]; - else key = "input"; - if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) parsedInputValue = inputValue[key][0]; - else parsedInputValue = inputValue[key]; - } else parsedInputValue = inputValue; - if (typeof parsedInputValue === "string") return [new HumanMessage(parsedInputValue)]; - else if (Array.isArray(parsedInputValue)) return parsedInputValue; - else if (isBaseMessage(parsedInputValue)) return [parsedInputValue]; - else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); - } - _getOutputMessages(outputValue) { - let parsedOutputValue; - if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { - let key; - if (this.outputMessagesKey !== void 0) key = this.outputMessagesKey; - else if (Object.keys(outputValue).length === 1) key = Object.keys(outputValue)[0]; - else key = "output"; - if (outputValue.generations !== void 0) parsedOutputValue = outputValue.generations[0][0].message; - else parsedOutputValue = outputValue[key]; - } else parsedOutputValue = outputValue; - if (typeof parsedOutputValue === "string") return [new AIMessage(parsedOutputValue)]; - else if (Array.isArray(parsedOutputValue)) return parsedOutputValue; - else if (isBaseMessage(parsedOutputValue)) return [parsedOutputValue]; - else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); - } - async _enterHistory(input, kwargs) { - const history = kwargs?.configurable?.messageHistory; - const messages = await history.getMessages(); - if (this.historyMessagesKey === void 0) return messages.concat(this._getInputMessages(input)); - return messages; - } - async _exitHistory(run, config) { - const history = config.configurable?.messageHistory; - let inputs; - if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) inputs = run.inputs[0]; - else inputs = run.inputs; - let inputMessages = this._getInputMessages(inputs); - if (this.historyMessagesKey === void 0) { - const existingMessages = await history.getMessages(); - inputMessages = inputMessages.slice(existingMessages.length); - } - const outputValue = run.outputs; - if (!outputValue) throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); - const outputMessages = this._getOutputMessages(outputValue); - await history.addMessages([...inputMessages, ...outputMessages]); - } - async _mergeConfig(...configs) { - const config = await super._mergeConfig(...configs); - if (!config.configurable || !config.configurable.sessionId) { - const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; - const exampleConfig = { configurable: { sessionId: "123" } }; - throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); - } - const { sessionId } = config.configurable; - config.configurable.messageHistory = await this.getMessageHistory(sessionId); - return config; - } -}; - -//#endregion - -//# sourceMappingURL=history.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js - - - - - - - - -//#region src/runnables/index.ts -var runnables_exports = {}; -__export(runnables_exports, { - RouterRunnable: () => RouterRunnable, - Runnable: () => Runnable, - RunnableAssign: () => RunnableAssign, - RunnableBinding: () => RunnableBinding, - RunnableBranch: () => RunnableBranch, - RunnableEach: () => RunnableEach, - RunnableLambda: () => RunnableLambda, - RunnableMap: () => RunnableMap, - RunnableParallel: () => RunnableParallel, - RunnablePassthrough: () => RunnablePassthrough, - RunnablePick: () => RunnablePick, - RunnableRetry: () => RunnableRetry, - RunnableSequence: () => RunnableSequence, - RunnableToolLike: () => RunnableToolLike, - RunnableWithFallbacks: () => RunnableWithFallbacks, - RunnableWithMessageHistory: () => RunnableWithMessageHistory, - _coerceToRunnable: () => _coerceToRunnable, - ensureConfig: () => ensureConfig, - getCallbackManagerForConfig: () => getCallbackManagerForConfig, - mergeConfigs: () => mergeConfigs, - patchConfig: () => config_patchConfig, - pickRunnableConfigKeys: () => config_pickRunnableConfigKeys -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_patch.js - - - - - -//#region src/utils/json_patch.ts -var json_patch_exports = {}; -__export(json_patch_exports, { - applyPatch: () => applyPatch, - compare: () => compare -}); - -//#endregion - -//# sourceMappingURL=json_patch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js - - - - -//#region src/output_parsers/base.ts -/** -* Abstract base class for parsing the output of a Large Language Model -* (LLM) call. It provides methods for parsing the result of an LLM call -* and invoking the parser with a given input. -*/ -var BaseLLMOutputParser = class extends Runnable { - /** - * Parses the result of an LLM call with a given prompt. By default, it - * simply calls `parseResult`. - * @param generations The generations from an LLM call. - * @param _prompt The prompt used in the LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - _baseMessageToString(message) { - return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); - } - _baseMessageContentToString(content) { - return JSON.stringify(content); - } - /** - * Calls the parser with a given input and optional configuration options. - * If the input is a string, it creates a generation with the input as - * text and calls `parseResult`. If the input is a `BaseMessage`, it - * creates a generation with the input as a message and the content of the - * input as text, and then calls `parseResult`. - * @param input The input to the parser, which can be a string or a `BaseMessage`. - * @param options Optional configuration options. - * @returns A promise of the parsed output. - */ - async invoke(input, options) { - if (typeof input === "string") return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ text: input$1 }], options$1?.callbacks), input, { - ...options, - runType: "parser" - }); - else return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ - message: input$1, - text: this._baseMessageToString(input$1) - }], options$1?.callbacks), input, { - ...options, - runType: "parser" - }); - } -}; -/** -* Class to parse the output of an LLM call. -*/ -var BaseOutputParser = class extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); - } - /** - * Return the string type key uniquely identifying this class of parser - */ - _type() { - throw new Error("_type not implemented"); - } -}; -/** -* Exception that output parsers should raise to signify a parsing error. -* -* This exists to differentiate parsing errors from other code or execution errors -* that also may arise inside the output parser. OutputParserExceptions will be -* available to catch and handle in ways to fix the parsing error, while other -* errors will be raised. -* -* @param message - The error that's being re-raised or an error message. -* @param llmOutput - String model output which is error-ing. -* @param observation - String explanation of error which can be passed to a -* model to try and remediate the issue. -* @param sendToLLM - Whether to send the observation and llm_output back to an Agent -* after an OutputParserException has been raised. This gives the underlying -* model driving the agent the context that the previous output was improperly -* structured, in the hopes that it will update the output to the correct -* format. -*/ -var OutputParserException = class extends Error { - llmOutput; - observation; - sendToLLM; - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === void 0 || llmOutput === void 0) throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); - } - addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/transform.js - - - - - - -//#region src/output_parsers/transform.ts -/** -* Class to parse the output of an LLM call that also allows streaming inputs. -*/ -var BaseTransformOutputParser = class extends BaseOutputParser { - async *_transform(inputGenerator) { - for await (const chunk of inputGenerator) if (typeof chunk === "string") yield this.parseResult([{ text: chunk }]); - else yield this.parseResult([{ - message: chunk, - text: this._baseMessageToString(chunk) - }]); - } - /** - * Transforms an asynchronous generator of input into an asynchronous - * generator of parsed output. - * @param inputGenerator An asynchronous generator of input. - * @param options A configuration object. - * @returns An asynchronous generator of parsed output. - */ - async *transform(inputGenerator, options) { - yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { - ...options, - runType: "parser" - }); - } -}; -/** -* A base class for output parsers that can handle streaming input. It -* extends the `BaseTransformOutputParser` class and provides a method for -* converting parsed outputs into a diff format. -*/ -var BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { - diff = false; - constructor(fields) { - super(fields); - this.diff = fields?.diff ?? this.diff; - } - async *_transform(inputGenerator) { - let prevParsed; - let accGen; - for await (const chunk of inputGenerator) { - if (typeof chunk !== "string" && typeof chunk.content !== "string") throw new Error("Cannot handle non-string output."); - let chunkGen; - if (isBaseMessageChunk(chunk)) { - if (typeof chunk.content !== "string") throw new Error("Cannot handle non-string message output."); - chunkGen = new ChatGenerationChunk({ - message: chunk, - text: chunk.content - }); - } else if (isBaseMessage(chunk)) { - if (typeof chunk.content !== "string") throw new Error("Cannot handle non-string message output."); - chunkGen = new ChatGenerationChunk({ - message: convertToChunk(chunk), - text: chunk.content - }); - } else chunkGen = new GenerationChunk({ text: chunk }); - if (accGen === void 0) accGen = chunkGen; - else accGen = accGen.concat(chunkGen); - const parsed = await this.parsePartialResult([accGen]); - if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { - if (this.diff) yield this._diff(prevParsed, parsed); - else yield parsed; - prevParsed = parsed; - } - } - } - getFormatInstructions() { - return ""; - } -}; - -//#endregion - -//# sourceMappingURL=transform.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/bytes.js - - -//#region src/output_parsers/bytes.ts -/** -* OutputParser that parses LLMResult into the top likely string and -* encodes it into bytes. -*/ -var BytesOutputParser = class extends BaseTransformOutputParser { - static lc_name() { - return "BytesOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "bytes" - ]; - lc_serializable = true; - textEncoder = new TextEncoder(); - parse(text) { - return Promise.resolve(this.textEncoder.encode(text)); - } - getFormatInstructions() { - return ""; - } -}; - -//#endregion - -//# sourceMappingURL=bytes.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/list.js - - - -//#region src/output_parsers/list.ts -/** -* Class to parse the output of an LLM call to a list. -* @augments BaseOutputParser -*/ -var ListOutputParser = class extends BaseTransformOutputParser { - re; - async *_transform(inputGenerator) { - let buffer = ""; - for await (const input of inputGenerator) { - if (typeof input === "string") buffer += input; - else buffer += input.content; - if (!this.re) { - const parts = await this.parse(buffer); - if (parts.length > 1) { - for (const part of parts.slice(0, -1)) yield [part]; - buffer = parts[parts.length - 1]; - } - } else { - const matches = [...buffer.matchAll(this.re)]; - if (matches.length > 1) { - let doneIdx = 0; - for (const match of matches.slice(0, -1)) { - yield [match[1]]; - doneIdx += (match.index ?? 0) + match[0].length; - } - buffer = buffer.slice(doneIdx); - } - } - } - for (const part of await this.parse(buffer)) yield [part]; - } -}; -/** -* Class to parse the output of an LLM call as a comma-separated list. -* @augments ListOutputParser -*/ -var CommaSeparatedListOutputParser = class extends ListOutputParser { - static lc_name() { - return "CommaSeparatedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - /** - * Parses the given text into an array of strings, using a comma as the - * separator. If the parsing fails, throws an OutputParserException. - * @param text The text to parse. - * @returns An array of strings obtained by splitting the input text at each comma. - */ - async parse(text) { - try { - return text.trim().split(",").map((s) => s.trim()); - } catch { - throw new OutputParserException(`Could not parse output: ${text}`, text); - } - } - /** - * Provides instructions on the expected format of the response for the - * CommaSeparatedListOutputParser. - * @returns A string containing instructions on the expected format of the response. - */ - getFormatInstructions() { - return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; - } -}; -/** -* Class to parse the output of an LLM call to a list with a specific length and separator. -* @augments ListOutputParser -*/ -var CustomListOutputParser = class extends ListOutputParser { - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - length; - separator; - constructor({ length, separator }) { - super(...arguments); - this.length = length; - this.separator = separator || ","; - } - /** - * Parses the given text into an array of strings, using the specified - * separator. If the parsing fails or the number of items in the list - * doesn't match the expected length, throws an OutputParserException. - * @param text The text to parse. - * @returns An array of strings obtained by splitting the input text at each occurrence of the specified separator. - */ - async parse(text) { - try { - const items = text.trim().split(this.separator).map((s) => s.trim()); - if (this.length !== void 0 && items.length !== this.length) throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); - return items; - } catch (e) { - if (Object.getPrototypeOf(e) === OutputParserException.prototype) throw e; - throw new OutputParserException(`Could not parse output: ${text}`); - } - } - /** - * Provides instructions on the expected format of the response for the - * CustomListOutputParser, including the number of items and the - * separator. - * @returns A string containing instructions on the expected format of the response. - */ - getFormatInstructions() { - return `Your response should be a list of ${this.length === void 0 ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; - } -}; -var NumberedListOutputParser = class extends ListOutputParser { - static lc_name() { - return "NumberedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - getFormatInstructions() { - return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; - } - re = /\d+\.\s([^\n]+)/g; - async parse(text) { - return [...text.matchAll(this.re) ?? []].map((m) => m[1]); - } -}; -var MarkdownListOutputParser = class extends ListOutputParser { - static lc_name() { - return "NumberedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - getFormatInstructions() { - return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; - } - re = /^\s*[-*]\s([^\n]+)$/gm; - async parse(text) { - return [...text.matchAll(this.re) ?? []].map((m) => m[1]); - } -}; - -//#endregion - -//# sourceMappingURL=list.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/string.js - - -//#region src/output_parsers/string.ts -/** -* OutputParser that parses LLMResult into the top likely string. -* @example -* ```typescript -* const promptTemplate = PromptTemplate.fromTemplate( -* "Tell me a joke about {topic}", -* ); -* -* const chain = RunnableSequence.from([ -* promptTemplate, -* new ChatOpenAI({ model: "gpt-4o-mini" }), -* new StringOutputParser(), -* ]); -* -* const result = await chain.invoke({ topic: "bears" }); -* console.log("What do you call a bear with no teeth? A gummy bear!"); -* ``` -*/ -var StringOutputParser = class extends BaseTransformOutputParser { - static lc_name() { - return "StrOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "string" - ]; - lc_serializable = true; - /** - * Parses a string output from an LLM call. This method is meant to be - * implemented by subclasses to define how a string output from an LLM - * should be parsed. - * @param text The string output from an LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parse(text) { - return Promise.resolve(text); - } - getFormatInstructions() { - return ""; - } - _textContentToString(content) { - return content.text; - } - _imageUrlContentToString(_content) { - throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); - } - _messageContentToString(content) { - switch (content.type) { - case "text": - case "text_delta": - if ("text" in content) return this._textContentToString(content); - break; - case "image_url": - if ("image_url" in content) return this._imageUrlContentToString(content); - break; - default: throw new Error(`Cannot coerce "${content.type}" message part into a string.`); - } - throw new Error(`Invalid content type: ${content.type}`); - } - _baseMessageContentToString(content) { - return content.reduce((acc, item) => acc + this._messageContentToString(item), ""); - } -}; - -//#endregion - -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/structured.js - - - - - -//#region src/output_parsers/structured.ts -var StructuredOutputParser = class extends BaseOutputParser { - static lc_name() { - return "StructuredOutputParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "structured" - ]; - toJSON() { - return this.toJSONNotImplemented(); - } - constructor(schema) { - super(schema); - this.schema = schema; - } - /** - * Creates a new StructuredOutputParser from a Zod schema. - * @param schema The Zod schema which the output should match - * @returns A new instance of StructuredOutputParser. - */ - static fromZodSchema(schema) { - return new this(schema); - } - /** - * Creates a new StructuredOutputParser from a set of names and - * descriptions. - * @param schemas An object where each key is a name and each value is a description - * @returns A new instance of StructuredOutputParser. - */ - static fromNamesAndDescriptions(schemas) { - const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); - return new this(zodSchema); - } - /** - * Returns a markdown code snippet with a JSON object formatted according - * to the schema. - * @param options Optional. The options for formatting the instructions - * @returns A markdown code snippet with a JSON object formatted according to the schema. - */ - getFormatInstructions() { - return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. - -"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. - -For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} -would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. -Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. - -Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! - -Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: -\`\`\`json -${JSON.stringify(toJsonSchema(this.schema))} -\`\`\` -`; - } - /** - * Parses the given text according to the schema. - * @param text The text to parse - * @returns The parsed output. - */ - async parse(text) { - try { - const trimmedText = text.trim(); - const json = trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText; - const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { - const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n"); - return `"${escapedInsideQuotes}"`; - }).replace(/\n/g, ""); - return await interopParseAsync(this.schema, JSON.parse(escapedJson)); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); - } - } -}; -/** -* A specific type of `StructuredOutputParser` that parses JSON data -* formatted as a markdown code snippet. -*/ -var JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { - static lc_name() { - return "JsonMarkdownStructuredOutputParser"; - } - getFormatInstructions(options) { - const interpolationDepth = options?.interpolationDepth ?? 1; - if (interpolationDepth < 1) throw new Error("f string interpolation depth must be at least 1"); - return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``; - } - _schemaToInstruction(schemaInput, indent = 2) { - const schema = schemaInput; - if ("type" in schema) { - let nullable = false; - let type; - if (Array.isArray(schema.type)) { - const nullIdx = schema.type.findIndex((type$1) => type$1 === "null"); - if (nullIdx !== -1) { - nullable = true; - schema.type.splice(nullIdx, 1); - } - type = schema.type.join(" | "); - } else type = schema.type; - if (schema.type === "object" && schema.properties) { - const description$1 = schema.description ? ` // ${schema.description}` : ""; - const properties = Object.entries(schema.properties).map(([key, value]) => { - const isOptional = schema.required?.includes(key) ? "" : " (optional)"; - return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; - }).join("\n"); - return `{\n${properties}\n${" ".repeat(indent - 2)}}${description$1}`; - } - if (schema.type === "array" && schema.items) { - const description$1 = schema.description ? ` // ${schema.description}` : ""; - return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\n${" ".repeat(indent - 2)}] ${description$1}`; - } - const isNullable = nullable ? " (nullable)" : ""; - const description = schema.description ? ` // ${schema.description}` : ""; - return `${type}${description}${isNullable}`; - } - if ("anyOf" in schema) return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(`\n${" ".repeat(indent - 2)}`); - throw new Error("unsupported schema type"); - } - static fromZodSchema(schema) { - return new this(schema); - } - static fromNamesAndDescriptions(schemas) { - const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); - return new this(zodSchema); - } -}; -/** -* A type of `StructuredOutputParser` that handles asymmetric input and -* output schemas. -*/ -var AsymmetricStructuredOutputParser = class extends BaseOutputParser { - structuredInputParser; - constructor({ inputSchema }) { - super(...arguments); - this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); - } - async parse(text) { - let parsedInput; - try { - parsedInput = await this.structuredInputParser.parse(text); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); - } - return this.outputProcessor(parsedInput); - } - getFormatInstructions() { - return this.structuredInputParser.getFormatInstructions(); - } -}; - -//#endregion - -//# sourceMappingURL=structured.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/json.js - - - - - -//#region src/output_parsers/json.ts -/** -* Class for parsing the output of an LLM into a JSON object. -*/ -var JsonOutputParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputParser"; - } - lc_namespace = ["langchain_core", "output_parsers"]; - lc_serializable = true; - /** @internal */ - _concatOutputChunks(first, second) { - if (this.diff) return super._concatOutputChunks(first, second); - return second; - } - _diff(prev, next) { - if (!next) return void 0; - if (!prev) return [{ - op: "replace", - path: "", - value: next - }]; - return compare(prev, next); - } - async parsePartialResult(generations) { - return parseJsonMarkdown(generations[0].text); - } - async parse(text) { - return parseJsonMarkdown(text, JSON.parse); - } - getFormatInstructions() { - return ""; - } -}; - -//#endregion - -//# sourceMappingURL=json.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/sax-js/sax.js -//#region src/utils/sax-js/sax.ts -const initializeSax = function() { - const sax$1 = {}; - sax$1.parser = function(strict, opt) { - return new SAXParser(strict, opt); - }; - sax$1.SAXParser = SAXParser; - sax$1.SAXStream = SAXStream; - sax$1.createStream = createStream; - sax$1.MAX_BUFFER_LENGTH = 64 * 1024; - const buffers = [ - "comment", - "sgmlDecl", - "textNode", - "tagName", - "doctype", - "procInstName", - "procInstBody", - "entity", - "attribName", - "attribValue", - "cdata", - "script" - ]; - sax$1.EVENTS = [ - "text", - "processinginstruction", - "sgmldeclaration", - "doctype", - "comment", - "opentagstart", - "attribute", - "opentag", - "closetag", - "opencdata", - "cdata", - "closecdata", - "error", - "end", - "ready", - "script", - "opennamespace", - "closenamespace" - ]; - function SAXParser(strict, opt) { - if (!(this instanceof SAXParser)) return new SAXParser(strict, opt); - var parser = this; - clearBuffers(parser); - parser.q = parser.c = ""; - parser.bufferCheckPosition = sax$1.MAX_BUFFER_LENGTH; - parser.opt = opt || {}; - parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; - parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; - parser.tags = []; - parser.closed = parser.closedRoot = parser.sawRoot = false; - parser.tag = parser.error = null; - parser.strict = !!strict; - parser.noscript = !!(strict || parser.opt.noscript); - parser.state = S.BEGIN; - parser.strictEntities = parser.opt.strictEntities; - parser.ENTITIES = parser.strictEntities ? Object.create(sax$1.XML_ENTITIES) : Object.create(sax$1.ENTITIES); - parser.attribList = []; - if (parser.opt.xmlns) parser.ns = Object.create(rootNS); - parser.trackPosition = parser.opt.position !== false; - if (parser.trackPosition) parser.position = parser.line = parser.column = 0; - emit(parser, "onready"); - } - if (!Object.create) Object.create = function(o) { - function F() {} - F.prototype = o; - var newf = new F(); - return newf; - }; - if (!Object.keys) Object.keys = function(o) { - var a = []; - for (var i in o) if (o.hasOwnProperty(i)) a.push(i); - return a; - }; - function checkBufferLength(parser) { - var maxAllowed = Math.max(sax$1.MAX_BUFFER_LENGTH, 10); - var maxActual = 0; - for (var i = 0, l = buffers.length; i < l; i++) { - var len = parser[buffers[i]].length; - if (len > maxAllowed) switch (buffers[i]) { - case "textNode": - closeText(parser); - break; - case "cdata": - emitNode(parser, "oncdata", parser.cdata); - parser.cdata = ""; - break; - case "script": - emitNode(parser, "onscript", parser.script); - parser.script = ""; - break; - default: error(parser, "Max buffer length exceeded: " + buffers[i]); - } - maxActual = Math.max(maxActual, len); - } - var m = sax$1.MAX_BUFFER_LENGTH - maxActual; - parser.bufferCheckPosition = m + parser.position; - } - function clearBuffers(parser) { - for (var i = 0, l = buffers.length; i < l; i++) parser[buffers[i]] = ""; - } - function flushBuffers(parser) { - closeText(parser); - if (parser.cdata !== "") { - emitNode(parser, "oncdata", parser.cdata); - parser.cdata = ""; - } - if (parser.script !== "") { - emitNode(parser, "onscript", parser.script); - parser.script = ""; - } - } - SAXParser.prototype = { - end: function() { - end(this); - }, - write, - resume: function() { - this.error = null; - return this; - }, - close: function() { - return this.write(null); - }, - flush: function() { - flushBuffers(this); - } - }; - var Stream = ReadableStream; - if (!Stream) Stream = function() {}; - var streamWraps = sax$1.EVENTS.filter(function(ev) { - return ev !== "error" && ev !== "end"; - }); - function createStream(strict, opt) { - return new SAXStream(strict, opt); - } - function SAXStream(strict, opt) { - if (!(this instanceof SAXStream)) return new SAXStream(strict, opt); - Stream.apply(this); - this._parser = new SAXParser(strict, opt); - this.writable = true; - this.readable = true; - var me = this; - this._parser.onend = function() { - me.emit("end"); - }; - this._parser.onerror = function(er) { - me.emit("error", er); - me._parser.error = null; - }; - this._decoder = null; - streamWraps.forEach(function(ev) { - Object.defineProperty(me, "on" + ev, { - get: function() { - return me._parser["on" + ev]; - }, - set: function(h) { - if (!h) { - me.removeAllListeners(ev); - me._parser["on" + ev] = h; - return h; - } - me.on(ev, h); - }, - enumerable: true, - configurable: false - }); - }); - } - SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }); - SAXStream.prototype.write = function(data) { - this._parser.write(data.toString()); - this.emit("data", data); - return true; - }; - SAXStream.prototype.end = function(chunk) { - if (chunk && chunk.length) this.write(chunk); - this._parser.end(); - return true; - }; - SAXStream.prototype.on = function(ev, handler) { - var me = this; - if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) me._parser["on" + ev] = function() { - var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); - args.splice(0, 0, ev); - me.emit.apply(me, args); - }; - return Stream.prototype.on.call(me, ev, handler); - }; - var CDATA = "[CDATA["; - var DOCTYPE = "DOCTYPE"; - var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; - var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; - var rootNS = { - xml: XML_NAMESPACE, - xmlns: XMLNS_NAMESPACE - }; - var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; - var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; - var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; - var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; - function isWhitespace(c) { - return c === " " || c === "\n" || c === "\r" || c === " "; - } - function isQuote(c) { - return c === "\"" || c === "'"; - } - function isAttribEnd(c) { - return c === ">" || isWhitespace(c); - } - function isMatch(regex, c) { - return regex.test(c); - } - function notMatch(regex, c) { - return !isMatch(regex, c); - } - var S = 0; - sax$1.STATE = { - BEGIN: S++, - BEGIN_WHITESPACE: S++, - TEXT: S++, - TEXT_ENTITY: S++, - OPEN_WAKA: S++, - SGML_DECL: S++, - SGML_DECL_QUOTED: S++, - DOCTYPE: S++, - DOCTYPE_QUOTED: S++, - DOCTYPE_DTD: S++, - DOCTYPE_DTD_QUOTED: S++, - COMMENT_STARTING: S++, - COMMENT: S++, - COMMENT_ENDING: S++, - COMMENT_ENDED: S++, - CDATA: S++, - CDATA_ENDING: S++, - CDATA_ENDING_2: S++, - PROC_INST: S++, - PROC_INST_BODY: S++, - PROC_INST_ENDING: S++, - OPEN_TAG: S++, - OPEN_TAG_SLASH: S++, - ATTRIB: S++, - ATTRIB_NAME: S++, - ATTRIB_NAME_SAW_WHITE: S++, - ATTRIB_VALUE: S++, - ATTRIB_VALUE_QUOTED: S++, - ATTRIB_VALUE_CLOSED: S++, - ATTRIB_VALUE_UNQUOTED: S++, - ATTRIB_VALUE_ENTITY_Q: S++, - ATTRIB_VALUE_ENTITY_U: S++, - CLOSE_TAG: S++, - CLOSE_TAG_SAW_WHITE: S++, - SCRIPT: S++, - SCRIPT_ENDING: S++ - }; - sax$1.XML_ENTITIES = { - amp: "&", - gt: ">", - lt: "<", - quot: "\"", - apos: "'" - }; - sax$1.ENTITIES = { - amp: "&", - gt: ">", - lt: "<", - quot: "\"", - apos: "'", - AElig: 198, - Aacute: 193, - Acirc: 194, - Agrave: 192, - Aring: 197, - Atilde: 195, - Auml: 196, - Ccedil: 199, - ETH: 208, - Eacute: 201, - Ecirc: 202, - Egrave: 200, - Euml: 203, - Iacute: 205, - Icirc: 206, - Igrave: 204, - Iuml: 207, - Ntilde: 209, - Oacute: 211, - Ocirc: 212, - Ograve: 210, - Oslash: 216, - Otilde: 213, - Ouml: 214, - THORN: 222, - Uacute: 218, - Ucirc: 219, - Ugrave: 217, - Uuml: 220, - Yacute: 221, - aacute: 225, - acirc: 226, - aelig: 230, - agrave: 224, - aring: 229, - atilde: 227, - auml: 228, - ccedil: 231, - eacute: 233, - ecirc: 234, - egrave: 232, - eth: 240, - euml: 235, - iacute: 237, - icirc: 238, - igrave: 236, - iuml: 239, - ntilde: 241, - oacute: 243, - ocirc: 244, - ograve: 242, - oslash: 248, - otilde: 245, - ouml: 246, - szlig: 223, - thorn: 254, - uacute: 250, - ucirc: 251, - ugrave: 249, - uuml: 252, - yacute: 253, - yuml: 255, - copy: 169, - reg: 174, - nbsp: 160, - iexcl: 161, - cent: 162, - pound: 163, - curren: 164, - yen: 165, - brvbar: 166, - sect: 167, - uml: 168, - ordf: 170, - laquo: 171, - not: 172, - shy: 173, - macr: 175, - deg: 176, - plusmn: 177, - sup1: 185, - sup2: 178, - sup3: 179, - acute: 180, - micro: 181, - para: 182, - middot: 183, - cedil: 184, - ordm: 186, - raquo: 187, - frac14: 188, - frac12: 189, - frac34: 190, - iquest: 191, - times: 215, - divide: 247, - OElig: 338, - oelig: 339, - Scaron: 352, - scaron: 353, - Yuml: 376, - fnof: 402, - circ: 710, - tilde: 732, - Alpha: 913, - Beta: 914, - Gamma: 915, - Delta: 916, - Epsilon: 917, - Zeta: 918, - Eta: 919, - Theta: 920, - Iota: 921, - Kappa: 922, - Lambda: 923, - Mu: 924, - Nu: 925, - Xi: 926, - Omicron: 927, - Pi: 928, - Rho: 929, - Sigma: 931, - Tau: 932, - Upsilon: 933, - Phi: 934, - Chi: 935, - Psi: 936, - Omega: 937, - alpha: 945, - beta: 946, - gamma: 947, - delta: 948, - epsilon: 949, - zeta: 950, - eta: 951, - theta: 952, - iota: 953, - kappa: 954, - lambda: 955, - mu: 956, - nu: 957, - xi: 958, - omicron: 959, - pi: 960, - rho: 961, - sigmaf: 962, - sigma: 963, - tau: 964, - upsilon: 965, - phi: 966, - chi: 967, - psi: 968, - omega: 969, - thetasym: 977, - upsih: 978, - piv: 982, - ensp: 8194, - emsp: 8195, - thinsp: 8201, - zwnj: 8204, - zwj: 8205, - lrm: 8206, - rlm: 8207, - ndash: 8211, - mdash: 8212, - lsquo: 8216, - rsquo: 8217, - sbquo: 8218, - ldquo: 8220, - rdquo: 8221, - bdquo: 8222, - dagger: 8224, - Dagger: 8225, - bull: 8226, - hellip: 8230, - permil: 8240, - prime: 8242, - Prime: 8243, - lsaquo: 8249, - rsaquo: 8250, - oline: 8254, - frasl: 8260, - euro: 8364, - image: 8465, - weierp: 8472, - real: 8476, - trade: 8482, - alefsym: 8501, - larr: 8592, - uarr: 8593, - rarr: 8594, - darr: 8595, - harr: 8596, - crarr: 8629, - lArr: 8656, - uArr: 8657, - rArr: 8658, - dArr: 8659, - hArr: 8660, - forall: 8704, - part: 8706, - exist: 8707, - empty: 8709, - nabla: 8711, - isin: 8712, - notin: 8713, - ni: 8715, - prod: 8719, - sum: 8721, - minus: 8722, - lowast: 8727, - radic: 8730, - prop: 8733, - infin: 8734, - ang: 8736, - and: 8743, - or: 8744, - cap: 8745, - cup: 8746, - int: 8747, - there4: 8756, - sim: 8764, - cong: 8773, - asymp: 8776, - ne: 8800, - equiv: 8801, - le: 8804, - ge: 8805, - sub: 8834, - sup: 8835, - nsub: 8836, - sube: 8838, - supe: 8839, - oplus: 8853, - otimes: 8855, - perp: 8869, - sdot: 8901, - lceil: 8968, - rceil: 8969, - lfloor: 8970, - rfloor: 8971, - lang: 9001, - rang: 9002, - loz: 9674, - spades: 9824, - clubs: 9827, - hearts: 9829, - diams: 9830 - }; - Object.keys(sax$1.ENTITIES).forEach(function(key) { - var e = sax$1.ENTITIES[key]; - var s$1 = typeof e === "number" ? String.fromCharCode(e) : e; - sax$1.ENTITIES[key] = s$1; - }); - for (var s in sax$1.STATE) sax$1.STATE[sax$1.STATE[s]] = s; - S = sax$1.STATE; - function emit(parser, event, data) { - parser[event] && parser[event](data); - } - function emitNode(parser, nodeType, data) { - if (parser.textNode) closeText(parser); - emit(parser, nodeType, data); - } - function closeText(parser) { - parser.textNode = textopts(parser.opt, parser.textNode); - if (parser.textNode) emit(parser, "ontext", parser.textNode); - parser.textNode = ""; - } - function textopts(opt, text) { - if (opt.trim) text = text.trim(); - if (opt.normalize) text = text.replace(/\s+/g, " "); - return text; - } - function error(parser, er) { - closeText(parser); - if (parser.trackPosition) er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c; - er = new Error(er); - parser.error = er; - emit(parser, "onerror", er); - return parser; - } - function end(parser) { - if (parser.sawRoot && !parser.closedRoot) strictFail(parser, "Unclosed root tag"); - if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) error(parser, "Unexpected end"); - closeText(parser); - parser.c = ""; - parser.closed = true; - emit(parser, "onend"); - SAXParser.call(parser, parser.strict, parser.opt); - return parser; - } - function strictFail(parser, message) { - if (typeof parser !== "object" || !(parser instanceof SAXParser)) throw new Error("bad call to strictFail"); - if (parser.strict) error(parser, message); - } - function newTag(parser) { - if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase](); - var parent = parser.tags[parser.tags.length - 1] || parser; - var tag = parser.tag = { - name: parser.tagName, - attributes: {} - }; - if (parser.opt.xmlns) tag.ns = parent.ns; - parser.attribList.length = 0; - emitNode(parser, "onopentagstart", tag); - } - function qname(name, attribute) { - var i = name.indexOf(":"); - var qualName = i < 0 ? ["", name] : name.split(":"); - var prefix = qualName[0]; - var local = qualName[1]; - if (attribute && name === "xmlns") { - prefix = "xmlns"; - local = ""; - } - return { - prefix, - local - }; - } - function attrib(parser) { - if (!parser.strict) parser.attribName = parser.attribName[parser.looseCase](); - if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { - parser.attribName = parser.attribValue = ""; - return; - } - if (parser.opt.xmlns) { - var qn = qname(parser.attribName, true); - var prefix = qn.prefix; - var local = qn.local; - if (prefix === "xmlns") if (local === "xml" && parser.attribValue !== XML_NAMESPACE) strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue); - else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue); - else { - var tag = parser.tag; - var parent = parser.tags[parser.tags.length - 1] || parser; - if (tag.ns === parent.ns) tag.ns = Object.create(parent.ns); - tag.ns[local] = parser.attribValue; - } - parser.attribList.push([parser.attribName, parser.attribValue]); - } else { - parser.tag.attributes[parser.attribName] = parser.attribValue; - emitNode(parser, "onattribute", { - name: parser.attribName, - value: parser.attribValue - }); - } - parser.attribName = parser.attribValue = ""; - } - function openTag(parser, selfClosing) { - if (parser.opt.xmlns) { - var tag = parser.tag; - var qn = qname(parser.tagName); - tag.prefix = qn.prefix; - tag.local = qn.local; - tag.uri = tag.ns[qn.prefix] || ""; - if (tag.prefix && !tag.uri) { - strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); - tag.uri = qn.prefix; - } - var parent = parser.tags[parser.tags.length - 1] || parser; - if (tag.ns && parent.ns !== tag.ns) Object.keys(tag.ns).forEach(function(p) { - emitNode(parser, "onopennamespace", { - prefix: p, - uri: tag.ns[p] - }); - }); - for (var i = 0, l = parser.attribList.length; i < l; i++) { - var nv = parser.attribList[i]; - var name = nv[0]; - var value = nv[1]; - var qualName = qname(name, true); - var prefix = qualName.prefix; - var local = qualName.local; - var uri = prefix === "" ? "" : tag.ns[prefix] || ""; - var a = { - name, - value, - prefix, - local, - uri - }; - if (prefix && prefix !== "xmlns" && !uri) { - strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); - a.uri = prefix; - } - parser.tag.attributes[name] = a; - emitNode(parser, "onattribute", a); - } - parser.attribList.length = 0; - } - parser.tag.isSelfClosing = !!selfClosing; - parser.sawRoot = true; - parser.tags.push(parser.tag); - emitNode(parser, "onopentag", parser.tag); - if (!selfClosing) { - if (!parser.noscript && parser.tagName.toLowerCase() === "script") parser.state = S.SCRIPT; - else parser.state = S.TEXT; - parser.tag = null; - parser.tagName = ""; - } - parser.attribName = parser.attribValue = ""; - parser.attribList.length = 0; - } - function closeTag(parser) { - if (!parser.tagName) { - strictFail(parser, "Weird empty close tag."); - parser.textNode += ""; - parser.state = S.TEXT; - return; - } - if (parser.script) { - if (parser.tagName !== "script") { - parser.script += ""; - parser.tagName = ""; - parser.state = S.SCRIPT; - return; - } - emitNode(parser, "onscript", parser.script); - parser.script = ""; - } - var t = parser.tags.length; - var tagName = parser.tagName; - if (!parser.strict) tagName = tagName[parser.looseCase](); - var closeTo = tagName; - while (t--) { - var close = parser.tags[t]; - if (close.name !== closeTo) strictFail(parser, "Unexpected close tag"); - else break; - } - if (t < 0) { - strictFail(parser, "Unmatched closing tag: " + parser.tagName); - parser.textNode += ""; - parser.state = S.TEXT; - return; - } - parser.tagName = tagName; - var s$1 = parser.tags.length; - while (s$1-- > t) { - var tag = parser.tag = parser.tags.pop(); - parser.tagName = parser.tag.name; - emitNode(parser, "onclosetag", parser.tagName); - var x = {}; - for (var i in tag.ns) x[i] = tag.ns[i]; - var parent = parser.tags[parser.tags.length - 1] || parser; - if (parser.opt.xmlns && tag.ns !== parent.ns) Object.keys(tag.ns).forEach(function(p) { - var n = tag.ns[p]; - emitNode(parser, "onclosenamespace", { - prefix: p, - uri: n - }); - }); - } - if (t === 0) parser.closedRoot = true; - parser.tagName = parser.attribValue = parser.attribName = ""; - parser.attribList.length = 0; - parser.state = S.TEXT; - } - function parseEntity(parser) { - var entity = parser.entity; - var entityLC = entity.toLowerCase(); - var num; - var numStr = ""; - if (parser.ENTITIES[entity]) return parser.ENTITIES[entity]; - if (parser.ENTITIES[entityLC]) return parser.ENTITIES[entityLC]; - entity = entityLC; - if (entity.charAt(0) === "#") if (entity.charAt(1) === "x") { - entity = entity.slice(2); - num = parseInt(entity, 16); - numStr = num.toString(16); - } else { - entity = entity.slice(1); - num = parseInt(entity, 10); - numStr = num.toString(10); - } - entity = entity.replace(/^0+/, ""); - if (isNaN(num) || numStr.toLowerCase() !== entity) { - strictFail(parser, "Invalid character entity"); - return "&" + parser.entity + ";"; - } - return String.fromCodePoint(num); - } - function beginWhiteSpace(parser, c) { - if (c === "<") { - parser.state = S.OPEN_WAKA; - parser.startTagPosition = parser.position; - } else if (!isWhitespace(c)) { - strictFail(parser, "Non-whitespace before first tag."); - parser.textNode = c; - parser.state = S.TEXT; - } - } - function charAt(chunk, i) { - var result = ""; - if (i < chunk.length) result = chunk.charAt(i); - return result; - } - function write(chunk) { - var parser = this; - if (this.error) throw this.error; - if (parser.closed) return error(parser, "Cannot write after close. Assign an onready handler."); - if (chunk === null) return end(parser); - if (typeof chunk === "object") chunk = chunk.toString(); - var i = 0; - var c = ""; - while (true) { - c = charAt(chunk, i++); - parser.c = c; - if (!c) break; - if (parser.trackPosition) { - parser.position++; - if (c === "\n") { - parser.line++; - parser.column = 0; - } else parser.column++; - } - switch (parser.state) { - case S.BEGIN: - parser.state = S.BEGIN_WHITESPACE; - if (c === "") continue; - beginWhiteSpace(parser, c); - continue; - case S.BEGIN_WHITESPACE: - beginWhiteSpace(parser, c); - continue; - case S.TEXT: - if (parser.sawRoot && !parser.closedRoot) { - var starti = i - 1; - while (c && c !== "<" && c !== "&") { - c = charAt(chunk, i++); - if (c && parser.trackPosition) { - parser.position++; - if (c === "\n") { - parser.line++; - parser.column = 0; - } else parser.column++; - } - } - parser.textNode += chunk.substring(starti, i - 1); - } - if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { - parser.state = S.OPEN_WAKA; - parser.startTagPosition = parser.position; - } else { - if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) strictFail(parser, "Text data outside of root node."); - if (c === "&") parser.state = S.TEXT_ENTITY; - else parser.textNode += c; - } - continue; - case S.SCRIPT: - if (c === "<") parser.state = S.SCRIPT_ENDING; - else parser.script += c; - continue; - case S.SCRIPT_ENDING: - if (c === "/") parser.state = S.CLOSE_TAG; - else { - parser.script += "<" + c; - parser.state = S.SCRIPT; - } - continue; - case S.OPEN_WAKA: - if (c === "!") { - parser.state = S.SGML_DECL; - parser.sgmlDecl = ""; - } else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) { - parser.state = S.OPEN_TAG; - parser.tagName = c; - } else if (c === "/") { - parser.state = S.CLOSE_TAG; - parser.tagName = ""; - } else if (c === "?") { - parser.state = S.PROC_INST; - parser.procInstName = parser.procInstBody = ""; - } else { - strictFail(parser, "Unencoded <"); - if (parser.startTagPosition + 1 < parser.position) { - var pad = parser.position - parser.startTagPosition; - c = new Array(pad).join(" ") + c; - } - parser.textNode += "<" + c; - parser.state = S.TEXT; - } - continue; - case S.SGML_DECL: - if ((parser.sgmlDecl + c).toUpperCase() === CDATA) { - emitNode(parser, "onopencdata"); - parser.state = S.CDATA; - parser.sgmlDecl = ""; - parser.cdata = ""; - } else if (parser.sgmlDecl + c === "--") { - parser.state = S.COMMENT; - parser.comment = ""; - parser.sgmlDecl = ""; - } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) { - parser.state = S.DOCTYPE; - if (parser.doctype || parser.sawRoot) strictFail(parser, "Inappropriately located doctype declaration"); - parser.doctype = ""; - parser.sgmlDecl = ""; - } else if (c === ">") { - emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); - parser.sgmlDecl = ""; - parser.state = S.TEXT; - } else if (isQuote(c)) { - parser.state = S.SGML_DECL_QUOTED; - parser.sgmlDecl += c; - } else parser.sgmlDecl += c; - continue; - case S.SGML_DECL_QUOTED: - if (c === parser.q) { - parser.state = S.SGML_DECL; - parser.q = ""; - } - parser.sgmlDecl += c; - continue; - case S.DOCTYPE: - if (c === ">") { - parser.state = S.TEXT; - emitNode(parser, "ondoctype", parser.doctype); - parser.doctype = true; - } else { - parser.doctype += c; - if (c === "[") parser.state = S.DOCTYPE_DTD; - else if (isQuote(c)) { - parser.state = S.DOCTYPE_QUOTED; - parser.q = c; - } - } - continue; - case S.DOCTYPE_QUOTED: - parser.doctype += c; - if (c === parser.q) { - parser.q = ""; - parser.state = S.DOCTYPE; - } - continue; - case S.DOCTYPE_DTD: - parser.doctype += c; - if (c === "]") parser.state = S.DOCTYPE; - else if (isQuote(c)) { - parser.state = S.DOCTYPE_DTD_QUOTED; - parser.q = c; - } - continue; - case S.DOCTYPE_DTD_QUOTED: - parser.doctype += c; - if (c === parser.q) { - parser.state = S.DOCTYPE_DTD; - parser.q = ""; - } - continue; - case S.COMMENT: - if (c === "-") parser.state = S.COMMENT_ENDING; - else parser.comment += c; - continue; - case S.COMMENT_ENDING: - if (c === "-") { - parser.state = S.COMMENT_ENDED; - parser.comment = textopts(parser.opt, parser.comment); - if (parser.comment) emitNode(parser, "oncomment", parser.comment); - parser.comment = ""; - } else { - parser.comment += "-" + c; - parser.state = S.COMMENT; - } - continue; - case S.COMMENT_ENDED: - if (c !== ">") { - strictFail(parser, "Malformed comment"); - parser.comment += "--" + c; - parser.state = S.COMMENT; - } else parser.state = S.TEXT; - continue; - case S.CDATA: - if (c === "]") parser.state = S.CDATA_ENDING; - else parser.cdata += c; - continue; - case S.CDATA_ENDING: - if (c === "]") parser.state = S.CDATA_ENDING_2; - else { - parser.cdata += "]" + c; - parser.state = S.CDATA; - } - continue; - case S.CDATA_ENDING_2: - if (c === ">") { - if (parser.cdata) emitNode(parser, "oncdata", parser.cdata); - emitNode(parser, "onclosecdata"); - parser.cdata = ""; - parser.state = S.TEXT; - } else if (c === "]") parser.cdata += "]"; - else { - parser.cdata += "]]" + c; - parser.state = S.CDATA; - } - continue; - case S.PROC_INST: - if (c === "?") parser.state = S.PROC_INST_ENDING; - else if (isWhitespace(c)) parser.state = S.PROC_INST_BODY; - else parser.procInstName += c; - continue; - case S.PROC_INST_BODY: - if (!parser.procInstBody && isWhitespace(c)) continue; - else if (c === "?") parser.state = S.PROC_INST_ENDING; - else parser.procInstBody += c; - continue; - case S.PROC_INST_ENDING: - if (c === ">") { - emitNode(parser, "onprocessinginstruction", { - name: parser.procInstName, - body: parser.procInstBody - }); - parser.procInstName = parser.procInstBody = ""; - parser.state = S.TEXT; - } else { - parser.procInstBody += "?" + c; - parser.state = S.PROC_INST_BODY; - } - continue; - case S.OPEN_TAG: - if (isMatch(nameBody, c)) parser.tagName += c; - else { - newTag(parser); - if (c === ">") openTag(parser); - else if (c === "/") parser.state = S.OPEN_TAG_SLASH; - else { - if (!isWhitespace(c)) strictFail(parser, "Invalid character in tag name"); - parser.state = S.ATTRIB; - } - } - continue; - case S.OPEN_TAG_SLASH: - if (c === ">") { - openTag(parser, true); - closeTag(parser); - } else { - strictFail(parser, "Forward-slash in opening tag not followed by >"); - parser.state = S.ATTRIB; - } - continue; - case S.ATTRIB: - if (isWhitespace(c)) continue; - else if (c === ">") openTag(parser); - else if (c === "/") parser.state = S.OPEN_TAG_SLASH; - else if (isMatch(nameStart, c)) { - parser.attribName = c; - parser.attribValue = ""; - parser.state = S.ATTRIB_NAME; - } else strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_NAME: - if (c === "=") parser.state = S.ATTRIB_VALUE; - else if (c === ">") { - strictFail(parser, "Attribute without value"); - parser.attribValue = parser.attribName; - attrib(parser); - openTag(parser); - } else if (isWhitespace(c)) parser.state = S.ATTRIB_NAME_SAW_WHITE; - else if (isMatch(nameBody, c)) parser.attribName += c; - else strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_NAME_SAW_WHITE: - if (c === "=") parser.state = S.ATTRIB_VALUE; - else if (isWhitespace(c)) continue; - else { - strictFail(parser, "Attribute without value"); - parser.tag.attributes[parser.attribName] = ""; - parser.attribValue = ""; - emitNode(parser, "onattribute", { - name: parser.attribName, - value: "" - }); - parser.attribName = ""; - if (c === ">") openTag(parser); - else if (isMatch(nameStart, c)) { - parser.attribName = c; - parser.state = S.ATTRIB_NAME; - } else { - strictFail(parser, "Invalid attribute name"); - parser.state = S.ATTRIB; - } - } - continue; - case S.ATTRIB_VALUE: - if (isWhitespace(c)) continue; - else if (isQuote(c)) { - parser.q = c; - parser.state = S.ATTRIB_VALUE_QUOTED; - } else { - strictFail(parser, "Unquoted attribute value"); - parser.state = S.ATTRIB_VALUE_UNQUOTED; - parser.attribValue = c; - } - continue; - case S.ATTRIB_VALUE_QUOTED: - if (c !== parser.q) { - if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_Q; - else parser.attribValue += c; - continue; - } - attrib(parser); - parser.q = ""; - parser.state = S.ATTRIB_VALUE_CLOSED; - continue; - case S.ATTRIB_VALUE_CLOSED: - if (isWhitespace(c)) parser.state = S.ATTRIB; - else if (c === ">") openTag(parser); - else if (c === "/") parser.state = S.OPEN_TAG_SLASH; - else if (isMatch(nameStart, c)) { - strictFail(parser, "No whitespace between attributes"); - parser.attribName = c; - parser.attribValue = ""; - parser.state = S.ATTRIB_NAME; - } else strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_VALUE_UNQUOTED: - if (!isAttribEnd(c)) { - if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_U; - else parser.attribValue += c; - continue; - } - attrib(parser); - if (c === ">") openTag(parser); - else parser.state = S.ATTRIB; - continue; - case S.CLOSE_TAG: - if (!parser.tagName) if (isWhitespace(c)) continue; - else if (notMatch(nameStart, c)) if (parser.script) { - parser.script += "") closeTag(parser); - else if (isMatch(nameBody, c)) parser.tagName += c; - else if (parser.script) { - parser.script += "") closeTag(parser); - else strictFail(parser, "Invalid characters in closing tag"); - continue; - case S.TEXT_ENTITY: - case S.ATTRIB_VALUE_ENTITY_Q: - case S.ATTRIB_VALUE_ENTITY_U: - var returnState; - var buffer; - switch (parser.state) { - case S.TEXT_ENTITY: - returnState = S.TEXT; - buffer = "textNode"; - break; - case S.ATTRIB_VALUE_ENTITY_Q: - returnState = S.ATTRIB_VALUE_QUOTED; - buffer = "attribValue"; - break; - case S.ATTRIB_VALUE_ENTITY_U: - returnState = S.ATTRIB_VALUE_UNQUOTED; - buffer = "attribValue"; - break; - } - if (c === ";") if (parser.opt.unparsedEntities) { - var parsedEntity = parseEntity(parser); - parser.entity = ""; - parser.state = returnState; - parser.write(parsedEntity); - } else { - parser[buffer] += parseEntity(parser); - parser.entity = ""; - parser.state = returnState; - } - else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) parser.entity += c; - else { - strictFail(parser, "Invalid character in entity name"); - parser[buffer] += "&" + parser.entity + c; - parser.entity = ""; - parser.state = returnState; - } - continue; - default: throw new Error(parser, "Unknown state: " + parser.state); - } - } - if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser); - return parser; - } - /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */ - /* istanbul ignore next */ - if (!String.fromCodePoint) (function() { - var stringFromCharCode = String.fromCharCode; - var floor = Math.floor; - var fromCodePoint = function() { - var MAX_SIZE = 16384; - var codeUnits = []; - var highSurrogate; - var lowSurrogate; - var index = -1; - var length = arguments.length; - if (!length) return ""; - var result = ""; - while (++index < length) { - var codePoint = Number(arguments[index]); - if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) throw RangeError("Invalid code point: " + codePoint); - if (codePoint <= 65535) codeUnits.push(codePoint); - else { - codePoint -= 65536; - highSurrogate = (codePoint >> 10) + 55296; - lowSurrogate = codePoint % 1024 + 56320; - codeUnits.push(highSurrogate, lowSurrogate); - } - if (index + 1 === length || codeUnits.length > MAX_SIZE) { - result += stringFromCharCode.apply(null, codeUnits); - codeUnits.length = 0; - } - } - return result; - }; - /* istanbul ignore next */ - if (Object.defineProperty) Object.defineProperty(String, "fromCodePoint", { - value: fromCodePoint, - configurable: true, - writable: true - }); - else String.fromCodePoint = fromCodePoint; - })(); - return sax$1; -}; -const sax = initializeSax(); - -//#endregion - -//# sourceMappingURL=sax.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/xml.js - - - - - -//#region src/output_parsers/xml.ts -const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file. -1. Output should conform to the tags below. -2. If tags are not given, make them on your own. -3. Remember to always open and close all the tags. - -As an example, for the tags ["foo", "bar", "baz"]: -1. String "\n \n \n \n" is a well-formatted instance of the schema. -2. String "\n \n " is a badly-formatted instance. -3. String "\n \n \n" is a badly-formatted instance. - -Here are the output tags: -\`\`\` -{tags} -\`\`\``; -var XMLOutputParser = class extends BaseCumulativeTransformOutputParser { - tags; - constructor(fields) { - super(fields); - this.tags = fields?.tags; - } - static lc_name() { - return "XMLOutputParser"; - } - lc_namespace = ["langchain_core", "output_parsers"]; - lc_serializable = true; - _diff(prev, next) { - if (!next) return void 0; - if (!prev) return [{ - op: "replace", - path: "", - value: next - }]; - return compare(prev, next); - } - async parsePartialResult(generations) { - return parseXMLMarkdown(generations[0].text); - } - async parse(text) { - return parseXMLMarkdown(text); - } - getFormatInstructions() { - const withTags = !!(this.tags && this.tags.length > 0); - return withTags ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; - } -}; -const strip = (text) => text.split("\n").map((line) => line.replace(/^\s+/, "")).join("\n").trim(); -const parseParsedResult = (input) => { - if (Object.keys(input).length === 0) return {}; - const result = {}; - if (input.children.length > 0) { - result[input.name] = input.children.map(parseParsedResult); - return result; - } else { - result[input.name] = input.text ?? void 0; - return result; - } -}; -function parseXMLMarkdown(s) { - const cleanedString = strip(s); - const parser = sax.parser(true); - let parsedResult = {}; - const elementStack = []; - parser.onopentag = (node) => { - const element = { - name: node.name, - attributes: node.attributes, - children: [], - text: "", - isSelfClosing: node.isSelfClosing - }; - if (elementStack.length > 0) { - const parentElement = elementStack[elementStack.length - 1]; - parentElement.children.push(element); - } else parsedResult = element; - if (!node.isSelfClosing) elementStack.push(element); - }; - parser.onclosetag = () => { - if (elementStack.length > 0) { - const lastElement = elementStack.pop(); - if (elementStack.length === 0 && lastElement) parsedResult = lastElement; - } - }; - parser.ontext = (text) => { - if (elementStack.length > 0) { - const currentElement = elementStack[elementStack.length - 1]; - currentElement.text += text; - } - }; - parser.onattribute = (attr) => { - if (elementStack.length > 0) { - const currentElement = elementStack[elementStack.length - 1]; - currentElement.attributes[attr.name] = attr.value; - } - }; - const match = /```(xml)?(.*)```/s.exec(cleanedString); - const xmlString = match ? match[2] : cleanedString; - parser.write(xmlString).close(); - if (parsedResult && parsedResult.name === "?xml") parsedResult = parsedResult.children[0]; - return parseParsedResult(parsedResult); -} - -//#endregion - -//# sourceMappingURL=xml.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/index.js - - - - - - - - - - - -//#region src/output_parsers/index.ts -var output_parsers_exports = {}; -__export(output_parsers_exports, { - AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, - BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, - BaseLLMOutputParser: () => BaseLLMOutputParser, - BaseOutputParser: () => BaseOutputParser, - BaseTransformOutputParser: () => BaseTransformOutputParser, - BytesOutputParser: () => BytesOutputParser, - CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, - CustomListOutputParser: () => CustomListOutputParser, - JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, - JsonOutputParser: () => JsonOutputParser, - ListOutputParser: () => ListOutputParser, - MarkdownListOutputParser: () => MarkdownListOutputParser, - NumberedListOutputParser: () => NumberedListOutputParser, - OutputParserException: () => OutputParserException, - StringOutputParser: () => StringOutputParser, - StructuredOutputParser: () => StructuredOutputParser, - XMLOutputParser: () => XMLOutputParser, - XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, - parseJsonMarkdown: () => parseJsonMarkdown, - parsePartialJson: () => parsePartialJson, - parseXMLMarkdown: () => parseXMLMarkdown -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js - - - - - - - -//#region src/output_parsers/openai_tools/json_output_tools_parsers.ts -function parseToolCall(rawToolCall, options) { - if (rawToolCall.function === void 0) return void 0; - let functionArgs; - if (options?.partial) try { - functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}"); - } catch { - return void 0; - } - else try { - functionArgs = JSON.parse(rawToolCall.function.arguments); - } catch (e) { - throw new OutputParserException([ - `Function "${rawToolCall.function.name}" arguments:`, - ``, - rawToolCall.function.arguments, - ``, - `are not valid JSON.`, - `Error: ${e.message}` - ].join("\n")); - } - const parsedToolCall = { - name: rawToolCall.function.name, - args: functionArgs, - type: "tool_call" - }; - if (options?.returnId) parsedToolCall.id = rawToolCall.id; - return parsedToolCall; -} -function convertLangChainToolCallToOpenAI(toolCall) { - if (toolCall.id === void 0) throw new Error(`All OpenAI tool calls must have an "id" field.`); - return { - id: toolCall.id, - type: "function", - function: { - name: toolCall.name, - arguments: JSON.stringify(toolCall.args) - } - }; -} -function makeInvalidToolCall(rawToolCall, errorMsg) { - return { - name: rawToolCall.function?.name, - args: rawToolCall.function?.arguments, - id: rawToolCall.id, - error: errorMsg, - type: "invalid_tool_call" - }; -} -/** -* Class for parsing the output of a tool-calling LLM into a JSON object. -*/ -var JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputToolsParser"; - } - returnId = false; - lc_namespace = [ - "langchain", - "output_parsers", - "openai_tools" - ]; - lc_serializable = true; - constructor(fields) { - super(fields); - this.returnId = fields?.returnId ?? this.returnId; - } - _diff() { - throw new Error("Not supported."); - } - async parse() { - throw new Error("Not implemented."); - } - async parseResult(generations) { - const result = await this.parsePartialResult(generations, false); - return result; - } - /** - * Parses the output and returns a JSON object. If `argsOnly` is true, - * only the arguments of the function call are returned. - * @param generations The output of the LLM to parse. - * @returns A JSON object representation of the function call or its arguments. - */ - async parsePartialResult(generations, partial = true) { - const message = generations[0].message; - let toolCalls; - if (isAIMessage(message) && message.tool_calls?.length) toolCalls = message.tool_calls.map((toolCall) => { - const { id,...rest } = toolCall; - if (!this.returnId) return rest; - return { - id, - ...rest - }; - }); - else if (message.additional_kwargs.tool_calls !== void 0) { - const rawToolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls)); - toolCalls = rawToolCalls.map((rawToolCall) => { - return parseToolCall(rawToolCall, { - returnId: this.returnId, - partial - }); - }); - } - if (!toolCalls) return []; - const parsedToolCalls = []; - for (const toolCall of toolCalls) if (toolCall !== void 0) { - const backwardsCompatibleToolCall = { - type: toolCall.name, - args: toolCall.args, - id: toolCall.id - }; - parsedToolCalls.push(backwardsCompatibleToolCall); - } - return parsedToolCalls; - } -}; -/** -* Class for parsing the output of a tool-calling LLM into a JSON object if you are -* expecting only a single tool to be called. -*/ -var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser { - static lc_name() { - return "JsonOutputKeyToolsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_tools" - ]; - lc_serializable = true; - returnId = false; - /** The type of tool calls to return. */ - keyName; - /** Whether to return only the first tool call. */ - returnSingle = false; - zodSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - } - async _validateResult(result) { - if (this.zodSchema === void 0) return result; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); - if (zodParsedResult.success) return zodParsedResult.data; - else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2)); - } - async parsePartialResult(generations) { - const results = await super.parsePartialResult(generations); - const matchingResults = results.filter((result) => result.type === this.keyName); - let returnedValues = matchingResults; - if (!matchingResults.length) return void 0; - if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); - if (this.returnSingle) return returnedValues[0]; - return returnedValues; - } - async parseResult(generations) { - const results = await super.parsePartialResult(generations, false); - const matchingResults = results.filter((result) => result.type === this.keyName); - let returnedValues = matchingResults; - if (!matchingResults.length) return void 0; - if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); - if (this.returnSingle) return this._validateResult(returnedValues[0]); - const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value))); - return toolCallResults; - } -}; - -//#endregion - -//# sourceMappingURL=json_output_tools_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js - - - -//#region src/output_parsers/openai_tools/index.ts -var openai_tools_exports = {}; -__export(openai_tools_exports, { - JsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser, - JsonOutputToolsParser: () => JsonOutputToolsParser, - convertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI, - makeInvalidToolCall: () => makeInvalidToolCall, - parseToolCall: () => parseToolCall -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js - - - - - - - -//#region src/output_parsers/openai_functions/json_output_functions_parsers.ts -/** -* Class for parsing the output of an LLM. Can be configured to return -* only the arguments of the function call in the output. -*/ -var OutputFunctionsParser = class extends BaseLLMOutputParser { - static lc_name() { - return "OutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - argsOnly = true; - constructor(config) { - super(); - this.argsOnly = config?.argsOnly ?? this.argsOnly; - } - /** - * Parses the output and returns a string representation of the function - * call or its arguments. - * @param generations The output of the LLM to parse. - * @returns A string representation of the function call or its arguments. - */ - async parseResult(generations) { - if ("message" in generations[0]) { - const gen = generations[0]; - const functionCall = gen.message.additional_kwargs.function_call; - if (!functionCall) throw new Error(`No function_call in message ${JSON.stringify(generations)}`); - if (!functionCall.arguments) throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`); - if (this.argsOnly) return functionCall.arguments; - return JSON.stringify(functionCall); - } else throw new Error(`No message in generations ${JSON.stringify(generations)}`); - } -}; -/** -* Class for parsing the output of an LLM into a JSON object. Uses an -* instance of `OutputFunctionsParser` to parse the output. -*/ -var JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - outputParser; - argsOnly = true; - constructor(config) { - super(config); - this.argsOnly = config?.argsOnly ?? this.argsOnly; - this.outputParser = new OutputFunctionsParser(config); - } - _diff(prev, next) { - if (!next) return void 0; - const ops = compare(prev ?? {}, next); - return ops; - } - async parsePartialResult(generations) { - const generation = generations[0]; - if (!generation.message) return void 0; - const { message } = generation; - const functionCall = message.additional_kwargs.function_call; - if (!functionCall) return void 0; - if (this.argsOnly) return parsePartialJson(functionCall.arguments); - return { - ...functionCall, - arguments: parsePartialJson(functionCall.arguments) - }; - } - /** - * Parses the output and returns a JSON object. If `argsOnly` is true, - * only the arguments of the function call are returned. - * @param generations The output of the LLM to parse. - * @returns A JSON object representation of the function call or its arguments. - */ - async parseResult(generations) { - const result = await this.outputParser.parseResult(generations); - if (!result) throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`); - return this.parse(result); - } - async parse(text) { - const parsedResult = JSON.parse(text); - if (this.argsOnly) return parsedResult; - parsedResult.arguments = JSON.parse(parsedResult.arguments); - return parsedResult; - } - getFormatInstructions() { - return ""; - } -}; -/** -* Class for parsing the output of an LLM into a JSON object and returning -* a specific attribute. Uses an instance of `JsonOutputFunctionsParser` -* to parse the output. -*/ -var JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser { - static lc_name() { - return "JsonKeyOutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - outputParser = new JsonOutputFunctionsParser(); - attrName; - get lc_aliases() { - return { attrName: "key_name" }; - } - constructor(fields) { - super(fields); - this.attrName = fields.attrName; - } - /** - * Parses the output and returns a specific attribute of the parsed JSON - * object. - * @param generations The output of the LLM to parse. - * @returns The value of a specific attribute of the parsed JSON object. - */ - async parseResult(generations) { - const result = await this.outputParser.parseResult(generations); - return result[this.attrName]; - } -}; - -//#endregion - -//# sourceMappingURL=json_output_functions_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js - - - -//#region src/output_parsers/openai_functions/index.ts -var openai_functions_exports = {}; -__export(openai_functions_exports, { - JsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser, - JsonOutputFunctionsParser: () => JsonOutputFunctionsParser, - OutputFunctionsParser: () => OutputFunctionsParser -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/base.js - - -//#region src/prompts/base.ts -/** -* Base class for prompt templates. Exposes a format method that returns a -* string prompt given a set of input values. -*/ -var BasePromptTemplate = class extends Runnable { - lc_serializable = true; - lc_namespace = [ - "langchain_core", - "prompts", - this._getPromptType() - ]; - get lc_attributes() { - return { partialVariables: void 0 }; - } - inputVariables; - outputParser; - partialVariables; - /** - * Metadata to be used for tracing. - */ - metadata; - /** Tags to be used for tracing. */ - tags; - constructor(input) { - super(input); - const { inputVariables } = input; - if (inputVariables.includes("stop")) throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); - Object.assign(this, input); - } - /** - * Merges partial variables and user variables. - * @param userVariables The user variables to merge with the partial variables. - * @returns A Promise that resolves to an object containing the merged variables. - */ - async mergePartialAndUserVariables(userVariables) { - const partialVariables = this.partialVariables ?? {}; - const partialValues = {}; - for (const [key, value] of Object.entries(partialVariables)) if (typeof value === "string") partialValues[key] = value; - else partialValues[key] = await value(); - const allKwargs = { - ...partialValues, - ...userVariables - }; - return allKwargs; - } - /** - * Invokes the prompt template with the given input and options. - * @param input The input to invoke the prompt template with. - * @param options Optional configuration for the callback. - * @returns A Promise that resolves to the output of the prompt template. - */ - async invoke(input, options) { - const metadata = { - ...this.metadata, - ...options?.metadata - }; - const tags = [...this.tags ?? [], ...options?.tags ?? []]; - return this._callWithConfig((input$1) => this.formatPromptValue(input$1), input, { - ...options, - tags, - metadata, - runType: "prompt" - }); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/string.js - - - -//#region src/prompts/string.ts -/** -* Base class for string prompt templates. It extends the -* BasePromptTemplate class and overrides the formatPromptValue method to -* return a StringPromptValue. -*/ -var BaseStringPromptTemplate = class extends BasePromptTemplate { - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new StringPromptValue(formattedPrompt); - } -}; - -//#endregion - -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ./node_modules/mustache/mustache.mjs -/*! - * mustache.js - Logic-less {{mustache}} templates with JavaScript - * http://github.com/janl/mustache.js - */ - -var objectToString = Object.prototype.toString; -var mustache_isArray = Array.isArray || function isArrayPolyfill (object) { - return objectToString.call(object) === '[object Array]'; -}; - -function isFunction (object) { - return typeof object === 'function'; -} - -/** - * More correct typeof string handling array - * which normally returns typeof 'object' - */ -function typeStr (obj) { - return mustache_isArray(obj) ? 'array' : typeof obj; -} - -function escapeRegExp (string) { - return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); -} - -/** - * Null safe way of checking whether or not an object, - * including its prototype, has a given property - */ -function hasProperty (obj, propName) { - return obj != null && typeof obj === 'object' && (propName in obj); -} - -/** - * Safe way of detecting whether or not the given thing is a primitive and - * whether it has the given property - */ -function primitiveHasOwnProperty (primitive, propName) { - return ( - primitive != null - && typeof primitive !== 'object' - && primitive.hasOwnProperty - && primitive.hasOwnProperty(propName) - ); -} - -// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 -// See https://github.com/janl/mustache.js/issues/189 -var regExpTest = RegExp.prototype.test; -function testRegExp (re, string) { - return regExpTest.call(re, string); -} - -var nonSpaceRe = /\S/; -function isWhitespace (string) { - return !testRegExp(nonSpaceRe, string); -} - -var entityMap = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '/': '/', - '`': '`', - '=': '=' -}; - -function escapeHtml (string) { - return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) { - return entityMap[s]; - }); -} - -var whiteRe = /\s*/; -var spaceRe = /\s+/; -var equalsRe = /\s*=/; -var curlyRe = /\s*\}/; -var tagRe = /#|\^|\/|>|\{|&|=|!/; - -/** - * Breaks up the given `template` string into a tree of tokens. If the `tags` - * argument is given here it must be an array with two string values: the - * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of - * course, the default is to use mustaches (i.e. mustache.tags). - * - * A token is an array with at least 4 elements. The first element is the - * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag - * did not contain a symbol (i.e. {{myValue}}) this element is "name". For - * all text that appears outside a symbol this element is "text". - * - * The second element of a token is its "value". For mustache tags this is - * whatever else was inside the tag besides the opening symbol. For text tokens - * this is the text itself. - * - * The third and fourth elements of the token are the start and end indices, - * respectively, of the token in the original template. - * - * Tokens that are the root node of a subtree contain two more elements: 1) an - * array of tokens in the subtree and 2) the index in the original template at - * which the closing tag for that section begins. - * - * Tokens for partials also contain two more elements: 1) a string value of - * indendation prior to that tag and 2) the index of that tag on that line - - * eg a value of 2 indicates the partial is the third tag on this line. - */ -function parseTemplate (template, tags) { - if (!template) - return []; - var lineHasNonSpace = false; - var sections = []; // Stack to hold section tokens - var tokens = []; // Buffer to hold the tokens - var spaces = []; // Indices of whitespace tokens on the current line - var hasTag = false; // Is there a {{tag}} on the current line? - var nonSpace = false; // Is there a non-space char on the current line? - var indentation = ''; // Tracks indentation for tags that use it - var tagIndex = 0; // Stores a count of number of tags encountered on a line - - // Strips all whitespace tokens array for the current line - // if there was a {{#tag}} on it and otherwise only space. - function stripSpace () { - if (hasTag && !nonSpace) { - while (spaces.length) - delete tokens[spaces.pop()]; - } else { - spaces = []; - } - - hasTag = false; - nonSpace = false; - } - - var openingTagRe, closingTagRe, closingCurlyRe; - function compileTags (tagsToCompile) { - if (typeof tagsToCompile === 'string') - tagsToCompile = tagsToCompile.split(spaceRe, 2); - - if (!mustache_isArray(tagsToCompile) || tagsToCompile.length !== 2) - throw new Error('Invalid tags: ' + tagsToCompile); - - openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*'); - closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1])); - closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1])); - } - - compileTags(tags || mustache.tags); - - var scanner = new Scanner(template); - - var start, type, value, chr, token, openSection; - while (!scanner.eos()) { - start = scanner.pos; - - // Match any text between tags. - value = scanner.scanUntil(openingTagRe); - - if (value) { - for (var i = 0, valueLength = value.length; i < valueLength; ++i) { - chr = value.charAt(i); - - if (isWhitespace(chr)) { - spaces.push(tokens.length); - indentation += chr; - } else { - nonSpace = true; - lineHasNonSpace = true; - indentation += ' '; - } - - tokens.push([ 'text', chr, start, start + 1 ]); - start += 1; - - // Check for whitespace on the current line. - if (chr === '\n') { - stripSpace(); - indentation = ''; - tagIndex = 0; - lineHasNonSpace = false; - } - } - } - - // Match the opening tag. - if (!scanner.scan(openingTagRe)) - break; - - hasTag = true; - - // Get the tag type. - type = scanner.scan(tagRe) || 'name'; - scanner.scan(whiteRe); - - // Get the tag value. - if (type === '=') { - value = scanner.scanUntil(equalsRe); - scanner.scan(equalsRe); - scanner.scanUntil(closingTagRe); - } else if (type === '{') { - value = scanner.scanUntil(closingCurlyRe); - scanner.scan(curlyRe); - scanner.scanUntil(closingTagRe); - type = '&'; - } else { - value = scanner.scanUntil(closingTagRe); - } - - // Match the closing tag. - if (!scanner.scan(closingTagRe)) - throw new Error('Unclosed tag at ' + scanner.pos); - - if (type == '>') { - token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ]; - } else { - token = [ type, value, start, scanner.pos ]; - } - tagIndex++; - tokens.push(token); - - if (type === '#' || type === '^') { - sections.push(token); - } else if (type === '/') { - // Check section nesting. - openSection = sections.pop(); - - if (!openSection) - throw new Error('Unopened section "' + value + '" at ' + start); - - if (openSection[1] !== value) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); - } else if (type === 'name' || type === '{' || type === '&') { - nonSpace = true; - } else if (type === '=') { - // Set the tags for the next time around. - compileTags(value); - } - } - - stripSpace(); - - // Make sure there are no open sections when we're done. - openSection = sections.pop(); - - if (openSection) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); - - return nestTokens(squashTokens(tokens)); -} - -/** - * Combines the values of consecutive text tokens in the given `tokens` array - * to a single token. - */ -function squashTokens (tokens) { - var squashedTokens = []; - - var token, lastToken; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - token = tokens[i]; - - if (token) { - if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { - lastToken[1] += token[1]; - lastToken[3] = token[3]; - } else { - squashedTokens.push(token); - lastToken = token; - } - } - } - - return squashedTokens; -} - -/** - * Forms the given array of `tokens` into a nested tree structure where - * tokens that represent a section have two additional items: 1) an array of - * all tokens that appear in that section and 2) the index in the original - * template that represents the end of that section. - */ -function nestTokens (tokens) { - var nestedTokens = []; - var collector = nestedTokens; - var sections = []; - - var token, section; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - token = tokens[i]; - - switch (token[0]) { - case '#': - case '^': - collector.push(token); - sections.push(token); - collector = token[4] = []; - break; - case '/': - section = sections.pop(); - section[5] = token[2]; - collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; - break; - default: - collector.push(token); - } - } - - return nestedTokens; -} - -/** - * A simple string scanner that is used by the template parser to find - * tokens in template strings. - */ -function Scanner (string) { - this.string = string; - this.tail = string; - this.pos = 0; -} - -/** - * Returns `true` if the tail is empty (end of string). - */ -Scanner.prototype.eos = function eos () { - return this.tail === ''; -}; - -/** - * Tries to match the given regular expression at the current position. - * Returns the matched text if it can match, the empty string otherwise. - */ -Scanner.prototype.scan = function scan (re) { - var match = this.tail.match(re); - - if (!match || match.index !== 0) - return ''; - - var string = match[0]; - - this.tail = this.tail.substring(string.length); - this.pos += string.length; - - return string; -}; - -/** - * Skips all text until the given regular expression can be matched. Returns - * the skipped string, which is the entire tail if no match can be made. - */ -Scanner.prototype.scanUntil = function scanUntil (re) { - var index = this.tail.search(re), match; - - switch (index) { - case -1: - match = this.tail; - this.tail = ''; - break; - case 0: - match = ''; - break; - default: - match = this.tail.substring(0, index); - this.tail = this.tail.substring(index); - } - - this.pos += match.length; - - return match; -}; - -/** - * Represents a rendering context by wrapping a view object and - * maintaining a reference to the parent context. - */ -function Context (view, parentContext) { - this.view = view; - this.cache = { '.': this.view }; - this.parent = parentContext; -} - -/** - * Creates a new context using the given view with this context - * as the parent. - */ -Context.prototype.push = function push (view) { - return new Context(view, this); -}; - -/** - * Returns the value of the given name in this context, traversing - * up the context hierarchy if the value is absent in this context's view. - */ -Context.prototype.lookup = function lookup (name) { - var cache = this.cache; - - var value; - if (cache.hasOwnProperty(name)) { - value = cache[name]; - } else { - var context = this, intermediateValue, names, index, lookupHit = false; - - while (context) { - if (name.indexOf('.') > 0) { - intermediateValue = context.view; - names = name.split('.'); - index = 0; - - /** - * Using the dot notion path in `name`, we descend through the - * nested objects. - * - * To be certain that the lookup has been successful, we have to - * check if the last object in the path actually has the property - * we are looking for. We store the result in `lookupHit`. - * - * This is specially necessary for when the value has been set to - * `undefined` and we want to avoid looking up parent contexts. - * - * In the case where dot notation is used, we consider the lookup - * to be successful even if the last "object" in the path is - * not actually an object but a primitive (e.g., a string, or an - * integer), because it is sometimes useful to access a property - * of an autoboxed primitive, such as the length of a string. - **/ - while (intermediateValue != null && index < names.length) { - if (index === names.length - 1) - lookupHit = ( - hasProperty(intermediateValue, names[index]) - || primitiveHasOwnProperty(intermediateValue, names[index]) - ); - - intermediateValue = intermediateValue[names[index++]]; - } - } else { - intermediateValue = context.view[name]; - - /** - * Only checking against `hasProperty`, which always returns `false` if - * `context.view` is not an object. Deliberately omitting the check - * against `primitiveHasOwnProperty` if dot notation is not used. - * - * Consider this example: - * ``` - * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"}) - * ``` - * - * If we were to check also against `primitiveHasOwnProperty`, as we do - * in the dot notation case, then render call would return: - * - * "The length of a football field is 9." - * - * rather than the expected: - * - * "The length of a football field is 100 yards." - **/ - lookupHit = hasProperty(context.view, name); - } - - if (lookupHit) { - value = intermediateValue; - break; - } - - context = context.parent; - } - - cache[name] = value; - } - - if (isFunction(value)) - value = value.call(this.view); - - return value; -}; - -/** - * A Writer knows how to take a stream of tokens and render them to a - * string, given a context. It also maintains a cache of templates to - * avoid the need to parse the same template twice. - */ -function Writer () { - this.templateCache = { - _cache: {}, - set: function set (key, value) { - this._cache[key] = value; - }, - get: function get (key) { - return this._cache[key]; - }, - clear: function clear () { - this._cache = {}; - } - }; -} - -/** - * Clears all cached templates in this writer. - */ -Writer.prototype.clearCache = function clearCache () { - if (typeof this.templateCache !== 'undefined') { - this.templateCache.clear(); - } -}; - -/** - * Parses and caches the given `template` according to the given `tags` or - * `mustache.tags` if `tags` is omitted, and returns the array of tokens - * that is generated from the parse. - */ -Writer.prototype.parse = function parse (template, tags) { - var cache = this.templateCache; - var cacheKey = template + ':' + (tags || mustache.tags).join(':'); - var isCacheEnabled = typeof cache !== 'undefined'; - var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined; - - if (tokens == undefined) { - tokens = parseTemplate(template, tags); - isCacheEnabled && cache.set(cacheKey, tokens); - } - return tokens; -}; - -/** - * High-level method that is used to render the given `template` with - * the given `view`. - * - * The optional `partials` argument may be an object that contains the - * names and templates of partials that are used in the template. It may - * also be a function that is used to load partial templates on the fly - * that takes a single argument: the name of the partial. - * - * If the optional `config` argument is given here, then it should be an - * object with a `tags` attribute or an `escape` attribute or both. - * If an array is passed, then it will be interpreted the same way as - * a `tags` attribute on a `config` object. - * - * The `tags` attribute of a `config` object must be an array with two - * string values: the opening and closing tags used in the template (e.g. - * [ "<%", "%>" ]). The default is to mustache.tags. - * - * The `escape` attribute of a `config` object must be a function which - * accepts a string as input and outputs a safely escaped string. - * If an `escape` function is not provided, then an HTML-safe string - * escaping function is used as the default. - */ -Writer.prototype.render = function render (template, view, partials, config) { - var tags = this.getConfigTags(config); - var tokens = this.parse(template, tags); - var context = (view instanceof Context) ? view : new Context(view, undefined); - return this.renderTokens(tokens, context, partials, template, config); -}; - -/** - * Low-level method that renders the given array of `tokens` using - * the given `context` and `partials`. - * - * Note: The `originalTemplate` is only ever used to extract the portion - * of the original template that was contained in a higher-order section. - * If the template doesn't use higher-order sections, this argument may - * be omitted. - */ -Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) { - var buffer = ''; - - var token, symbol, value; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - value = undefined; - token = tokens[i]; - symbol = token[0]; - - if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config); - else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config); - else if (symbol === '>') value = this.renderPartial(token, context, partials, config); - else if (symbol === '&') value = this.unescapedValue(token, context); - else if (symbol === 'name') value = this.escapedValue(token, context, config); - else if (symbol === 'text') value = this.rawValue(token); - - if (value !== undefined) - buffer += value; - } - - return buffer; -}; - -Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) { - var self = this; - var buffer = ''; - var value = context.lookup(token[1]); - - // This function is used to render an arbitrary template - // in the current context by higher-order sections. - function subRender (template) { - return self.render(template, context, partials, config); - } - - if (!value) return; - - if (mustache_isArray(value)) { - for (var j = 0, valueLength = value.length; j < valueLength; ++j) { - buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config); - } - } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') { - buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); - } else if (isFunction(value)) { - if (typeof originalTemplate !== 'string') - throw new Error('Cannot use higher-order sections without the original template'); - - // Extract the portion of the original template that the section contains. - value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); - - if (value != null) - buffer += value; - } else { - buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); - } - return buffer; -}; - -Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) { - var value = context.lookup(token[1]); - - // Use JavaScript's definition of falsy. Include empty arrays. - // See https://github.com/janl/mustache.js/issues/186 - if (!value || (mustache_isArray(value) && value.length === 0)) - return this.renderTokens(token[4], context, partials, originalTemplate, config); -}; - -Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) { - var filteredIndentation = indentation.replace(/[^ \t]/g, ''); - var partialByNl = partial.split('\n'); - for (var i = 0; i < partialByNl.length; i++) { - if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { - partialByNl[i] = filteredIndentation + partialByNl[i]; - } - } - return partialByNl.join('\n'); -}; - -Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) { - if (!partials) return; - var tags = this.getConfigTags(config); - - var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; - if (value != null) { - var lineHasNonSpace = token[6]; - var tagIndex = token[5]; - var indentation = token[4]; - var indentedValue = value; - if (tagIndex == 0 && indentation) { - indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); - } - var tokens = this.parse(indentedValue, tags); - return this.renderTokens(tokens, context, partials, indentedValue, config); - } -}; - -Writer.prototype.unescapedValue = function unescapedValue (token, context) { - var value = context.lookup(token[1]); - if (value != null) - return value; -}; - -Writer.prototype.escapedValue = function escapedValue (token, context, config) { - var escape = this.getConfigEscape(config) || mustache.escape; - var value = context.lookup(token[1]); - if (value != null) - return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value); -}; - -Writer.prototype.rawValue = function rawValue (token) { - return token[1]; -}; - -Writer.prototype.getConfigTags = function getConfigTags (config) { - if (mustache_isArray(config)) { - return config; - } - else if (config && typeof config === 'object') { - return config.tags; - } - else { - return undefined; - } -}; - -Writer.prototype.getConfigEscape = function getConfigEscape (config) { - if (config && typeof config === 'object' && !mustache_isArray(config)) { - return config.escape; - } - else { - return undefined; - } -}; - -var mustache = { - name: 'mustache.js', - version: '4.2.0', - tags: [ '{{', '}}' ], - clearCache: undefined, - escape: undefined, - parse: undefined, - render: undefined, - Scanner: undefined, - Context: undefined, - Writer: undefined, - /** - * Allows a user to override the default caching strategy, by providing an - * object with set, get and clear methods. This can also be used to disable - * the cache by setting it to the literal `undefined`. - */ - set templateCache (cache) { - defaultWriter.templateCache = cache; - }, - /** - * Gets the default or overridden caching object from the default writer. - */ - get templateCache () { - return defaultWriter.templateCache; - } -}; - -// All high-level mustache.* functions use this writer. -var defaultWriter = new Writer(); - -/** - * Clears all cached templates in the default writer. - */ -mustache.clearCache = function clearCache () { - return defaultWriter.clearCache(); -}; - -/** - * Parses and caches the given template in the default writer and returns the - * array of tokens it contains. Doing this ahead of time avoids the need to - * parse templates on the fly as they are rendered. - */ -mustache.parse = function parse (template, tags) { - return defaultWriter.parse(template, tags); -}; - -/** - * Renders the `template` with the given `view`, `partials`, and `config` - * using the default writer. - */ -mustache.render = function render (template, view, partials, config) { - if (typeof template !== 'string') { - throw new TypeError('Invalid template! Template should be a "string" ' + - 'but "' + typeStr(template) + '" was given as the first ' + - 'argument for mustache#render(template, view, partials)'); - } - - return defaultWriter.render(template, view, partials, config); -}; - -// Export the escaping function so that the user may override it. -// See https://github.com/janl/mustache.js/issues/244 -mustache.escape = escapeHtml; - -// Export these mainly for testing, but also for advanced usage. -mustache.Scanner = Scanner; -mustache.Context = Context; -mustache.Writer = Writer; - -/* harmony default export */ const mustache_mustache = (mustache); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/template.js - - - -//#region src/prompts/template.ts -function configureMustache() { - mustache_mustache.escape = (text) => text; -} -const parseFString = (template) => { - const chars = template.split(""); - const nodes = []; - const nextBracket = (bracket, start) => { - for (let i$1 = start; i$1 < chars.length; i$1 += 1) if (bracket.includes(chars[i$1])) return i$1; - return -1; - }; - let i = 0; - while (i < chars.length) if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { - nodes.push({ - type: "literal", - text: "{" - }); - i += 2; - } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { - nodes.push({ - type: "literal", - text: "}" - }); - i += 2; - } else if (chars[i] === "{") { - const j = nextBracket("}", i); - if (j < 0) throw new Error("Unclosed '{' in template."); - nodes.push({ - type: "variable", - name: chars.slice(i + 1, j).join("") - }); - i = j + 1; - } else if (chars[i] === "}") throw new Error("Single '}' in template."); - else { - const next = nextBracket("{}", i); - const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); - nodes.push({ - type: "literal", - text - }); - i = next < 0 ? chars.length : next; - } - return nodes; -}; -/** -* Convert the result of mustache.parse into an array of ParsedTemplateNode, -* to make it compatible with other LangChain string parsing template formats. -* -* @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library. -* @param {string[]} context Array of section variable names for nested context -* @returns {ParsedTemplateNode[]} -*/ -const mustacheTemplateToNodes = (template, context = []) => { - const nodes = []; - for (const temp of template) if (temp[0] === "name") { - const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; - nodes.push({ - type: "variable", - name - }); - } else if ([ - "#", - "&", - "^", - ">" - ].includes(temp[0])) { - nodes.push({ - type: "variable", - name: temp[1] - }); - if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { - const newContext = [...context, temp[1]]; - const nestedNodes = mustacheTemplateToNodes(temp[4], newContext); - nodes.push(...nestedNodes); - } - } else nodes.push({ - type: "literal", - text: temp[1] - }); - return nodes; -}; -const parseMustache = (template) => { - configureMustache(); - const parsed = mustache_mustache.parse(template); - return mustacheTemplateToNodes(parsed); -}; -const interpolateFString = (template, values) => { - return parseFString(template).reduce((res, node) => { - if (node.type === "variable") { - if (node.name in values) { - const stringValue = typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name]); - return res + stringValue; - } - throw new Error(`(f-string) Missing value for input ${node.name}`); - } - return res + node.text; - }, ""); -}; -const interpolateMustache = (template, values) => { - configureMustache(); - return mustache_mustache.render(template, values); -}; -const DEFAULT_FORMATTER_MAPPING = { - "f-string": interpolateFString, - mustache: interpolateMustache -}; -const DEFAULT_PARSER_MAPPING = { - "f-string": parseFString, - mustache: parseMustache -}; -const renderTemplate = (template, templateFormat, inputValues) => { - try { - return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); - } catch (e) { - const error = addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); - throw error; - } -}; -const template_parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); -const checkValidTemplate = (template, templateFormat, inputVariables) => { - if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { - const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); - throw new Error(`Invalid template format. Got \`${templateFormat}\`; - should be one of ${validFormats}`); - } - try { - const dummyInputs = inputVariables.reduce((acc, v) => { - acc[v] = "foo"; - return acc; - }, {}); - if (Array.isArray(template)) template.forEach((message) => { - if (message.type === "text" && "text" in message && typeof message.text === "string") renderTemplate(message.text, templateFormat, dummyInputs); - else if (message.type === "image_url") { - if (typeof message.image_url === "string") renderTemplate(message.image_url, templateFormat, dummyInputs); - else if (typeof message.image_url === "object" && message.image_url !== null && "url" in message.image_url && typeof message.image_url.url === "string") { - const imageUrl = message.image_url.url; - renderTemplate(imageUrl, templateFormat, dummyInputs); - } - } else throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); - }); - else renderTemplate(template, templateFormat, dummyInputs); - } catch (e) { - throw new Error(`Invalid prompt schema: ${e.message}`); - } -}; - -//#endregion - -//# sourceMappingURL=template.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/prompt.js - - - -//#region src/prompts/prompt.ts -/** -* Schema to represent a basic prompt for an LLM. -* @augments BasePromptTemplate -* @augments PromptTemplateInput -* -* @example -* ```ts -* import { PromptTemplate } from "langchain/prompts"; -* -* const prompt = new PromptTemplate({ -* inputVariables: ["foo"], -* template: "Say {foo}", -* }); -* ``` -*/ -var PromptTemplate = class PromptTemplate extends BaseStringPromptTemplate { - static lc_name() { - return "PromptTemplate"; - } - template; - templateFormat = "f-string"; - validateTemplate = true; - /** - * Additional fields which should be included inside - * the message content array if using a complex message - * content. - */ - additionalContentFields; - constructor(input) { - super(input); - if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; - Object.assign(this, input); - if (this.validateTemplate) { - if (this.templateFormat === "mustache") throw new Error("Mustache templates cannot be validated."); - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.template, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - return renderTemplate(this.template, this.templateFormat, allValues); - } - /** - * Take examples in list format with prefix and suffix to create a prompt. - * - * Intended to be used a a way to dynamically create a prompt from examples. - * - * @param examples - List of examples to use in the prompt. - * @param suffix - String to go after the list of examples. Should generally set up the user's input. - * @param inputVariables - A list of variable names the final prompt template will expect - * @param exampleSeparator - The separator to use in between examples - * @param prefix - String that should go before any examples. Generally includes examples. - * - * @returns The final prompt template generated. - */ - static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { - const template = [ - prefix, - ...examples, - suffix - ].join(exampleSeparator); - return new PromptTemplate({ - inputVariables, - template - }); - } - static fromTemplate(template, options) { - const { templateFormat = "f-string",...rest } = options ?? {}; - const names = /* @__PURE__ */ new Set(); - template_parseTemplate(template, templateFormat).forEach((node) => { - if (node.type === "variable") names.add(node.name); - }); - return new PromptTemplate({ - inputVariables: [...names], - templateFormat, - template, - ...rest - }); - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of PromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new PromptTemplate(promptDict); - } - serialize() { - if (this.outputParser !== void 0) throw new Error("Cannot serialize a prompt template with an output parser"); - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - template: this.template, - template_format: this.templateFormat - }; - } - static async deserialize(data) { - if (!data.template) throw new Error("Prompt template must have a template"); - const res = new PromptTemplate({ - inputVariables: data.input_variables, - template: data.template, - templateFormat: data.template_format - }); - return res; - } -}; - -//#endregion - -//# sourceMappingURL=prompt.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/image.js - - - - -//#region src/prompts/image.ts -/** -* An image prompt template for a multimodal model. -*/ -var ImagePromptTemplate = class ImagePromptTemplate extends BasePromptTemplate { - static lc_name() { - return "ImagePromptTemplate"; - } - lc_namespace = [ - "langchain_core", - "prompts", - "image" - ]; - template; - templateFormat = "f-string"; - validateTemplate = true; - /** - * Additional fields which should be included inside - * the message content array if using a complex message - * content. - */ - additionalContentFields; - constructor(input) { - super(input); - this.template = input.template; - this.templateFormat = input.templateFormat ?? this.templateFormat; - this.validateTemplate = input.validateTemplate ?? this.validateTemplate; - this.additionalContentFields = input.additionalContentFields; - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate([{ - type: "image_url", - image_url: this.template - }], this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of ImagePromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new ImagePromptTemplate(promptDict); - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const formatted = {}; - for (const [key, value] of Object.entries(this.template)) if (typeof value === "string") formatted[key] = renderTemplate(value, this.templateFormat, values); - else formatted[key] = value; - const url = values.url || formatted.url; - const detail = values.detail || formatted.detail; - if (!url) throw new Error("Must provide either an image URL."); - if (typeof url !== "string") throw new Error("url must be a string."); - const output = { url }; - if (detail) output.detail = detail; - return output; - } - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new ImagePromptValue(formattedPrompt); - } -}; - -//#endregion - -//# sourceMappingURL=image.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/dict.js - - - -//#region src/prompts/dict.ts -var DictPromptTemplate = class extends Runnable { - lc_namespace = [ - "langchain_core", - "prompts", - "dict" - ]; - lc_serializable = true; - template; - templateFormat; - inputVariables; - static lc_name() { - return "DictPromptTemplate"; - } - constructor(fields) { - const templateFormat = fields.templateFormat ?? "f-string"; - const inputVariables = _getInputVariables(fields.template, templateFormat); - super({ - inputVariables, - ...fields - }); - this.template = fields.template; - this.templateFormat = templateFormat; - this.inputVariables = inputVariables; - } - async format(values) { - return _insertInputVariables(this.template, values, this.templateFormat); - } - async invoke(values) { - return await this._callWithConfig(this.format.bind(this), values, { runType: "prompt" }); - } -}; -function _getInputVariables(template, templateFormat) { - const inputVariables = []; - for (const v of Object.values(template)) if (typeof v === "string") template_parseTemplate(v, templateFormat).forEach((t) => { - if (t.type === "variable") inputVariables.push(t.name); - }); - else if (Array.isArray(v)) { - for (const x of v) if (typeof x === "string") template_parseTemplate(x, templateFormat).forEach((t) => { - if (t.type === "variable") inputVariables.push(t.name); - }); - else if (typeof x === "object") inputVariables.push(..._getInputVariables(x, templateFormat)); - } else if (typeof v === "object" && v !== null) inputVariables.push(..._getInputVariables(v, templateFormat)); - return Array.from(new Set(inputVariables)); -} -function _insertInputVariables(template, inputs, templateFormat) { - const formatted = {}; - for (const [k, v] of Object.entries(template)) if (typeof v === "string") formatted[k] = renderTemplate(v, templateFormat, inputs); - else if (Array.isArray(v)) { - const formattedV = []; - for (const x of v) if (typeof x === "string") formattedV.push(renderTemplate(x, templateFormat, inputs)); - else if (typeof x === "object") formattedV.push(_insertInputVariables(x, inputs, templateFormat)); - formatted[k] = formattedV; - } else if (typeof v === "object" && v !== null) formatted[k] = _insertInputVariables(v, inputs, templateFormat); - else formatted[k] = v; - return formatted; -} - -//#endregion - -//# sourceMappingURL=dict.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/chat.js - - - - - - - - - - - - - - - - - -//#region src/prompts/chat.ts -/** -* Abstract class that serves as a base for creating message prompt -* templates. It defines how to format messages for different roles in a -* conversation. -*/ -var BaseMessagePromptTemplate = class extends Runnable { - lc_namespace = [ - "langchain_core", - "prompts", - "chat" - ]; - lc_serializable = true; - /** - * Calls the formatMessages method with the provided input and options. - * @param input Input for the formatMessages method - * @param options Optional BaseCallbackConfig - * @returns Formatted output messages - */ - async invoke(input, options) { - return this._callWithConfig((input$1) => this.formatMessages(input$1), input, { - ...options, - runType: "prompt" - }); - } -}; -/** -* Class that represents a placeholder for messages in a chat prompt. It -* extends the BaseMessagePromptTemplate. -*/ -var MessagesPlaceholder = class extends BaseMessagePromptTemplate { - static lc_name() { - return "MessagesPlaceholder"; - } - variableName; - optional; - constructor(fields) { - if (typeof fields === "string") fields = { variableName: fields }; - super(fields); - this.variableName = fields.variableName; - this.optional = fields.optional ?? false; - } - get inputVariables() { - return [this.variableName]; - } - async formatMessages(values) { - const input = values[this.variableName]; - if (this.optional && !input) return []; - else if (!input) { - const error = /* @__PURE__ */ new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); - error.name = "InputFormatError"; - throw error; - } - let formattedMessages; - try { - if (Array.isArray(input)) formattedMessages = input.map(utils_coerceMessageLikeToMessage); - else formattedMessages = [utils_coerceMessageLikeToMessage(input)]; - } catch (e) { - const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); - const error = new Error([ - `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, - `Received value: ${readableInput}`, - `Additional message: ${e.message}` - ].join("\n\n")); - error.name = "InputFormatError"; - error.lc_error_code = e.lc_error_code; - throw error; - } - return formattedMessages; - } -}; -/** -* Abstract class that serves as a base for creating message string prompt -* templates. It extends the BaseMessagePromptTemplate. -*/ -var BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { - prompt; - constructor(fields) { - if (!("prompt" in fields)) fields = { prompt: fields }; - super(fields); - this.prompt = fields.prompt; - } - get inputVariables() { - return this.prompt.inputVariables; - } - async formatMessages(values) { - return [await this.format(values)]; - } -}; -/** -* Abstract class that serves as a base for creating chat prompt -* templates. It extends the BasePromptTemplate. -*/ -var BaseChatPromptTemplate = class extends BasePromptTemplate { - constructor(input) { - super(input); - } - async format(values) { - return (await this.formatPromptValue(values)).toString(); - } - async formatPromptValue(values) { - const resultMessages = await this.formatMessages(values); - return new ChatPromptValue(resultMessages); - } -}; -/** -* Class that represents a chat message prompt template. It extends the -* BaseMessageStringPromptTemplate. -*/ -var ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { - static lc_name() { - return "ChatMessagePromptTemplate"; - } - role; - constructor(fields, role) { - if (!("prompt" in fields)) fields = { - prompt: fields, - role - }; - super(fields); - this.role = fields.role; - } - async format(values) { - return new ChatMessage(await this.prompt.format(values), this.role); - } - static fromTemplate(template, role, options) { - return new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role); - } -}; -function isTextTemplateParam(param) { - if (param === null || typeof param !== "object" || Array.isArray(param)) return false; - return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; -} -function isImageTemplateParam(param) { - if (param === null || typeof param !== "object" || Array.isArray(param)) return false; - return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && "url" in param.image_url && typeof param.image_url.url === "string"); -} -var _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { - lc_namespace = [ - "langchain_core", - "prompts", - "chat" - ]; - lc_serializable = true; - inputVariables = []; - additionalOptions = {}; - prompt; - messageClass; - static _messageClass() { - throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); - } - chatMessageClass; - constructor(fields, additionalOptions) { - if (!("prompt" in fields)) fields = { prompt: fields }; - super(fields); - this.prompt = fields.prompt; - if (Array.isArray(this.prompt)) { - let inputVariables = []; - this.prompt.forEach((prompt) => { - if ("inputVariables" in prompt) inputVariables = inputVariables.concat(prompt.inputVariables); - }); - this.inputVariables = inputVariables; - } else this.inputVariables = this.prompt.inputVariables; - this.additionalOptions = additionalOptions ?? this.additionalOptions; - } - createMessage(content) { - const constructor = this.constructor; - if (constructor._messageClass()) { - const MsgClass = constructor._messageClass(); - return new MsgClass({ content }); - } else if (constructor.chatMessageClass) { - const MsgClass = constructor.chatMessageClass(); - return new MsgClass({ - content, - role: this.getRoleFromMessageClass(MsgClass.lc_name()) - }); - } else throw new Error("No message class defined"); - } - getRoleFromMessageClass(name) { - switch (name) { - case "HumanMessage": return "human"; - case "AIMessage": return "ai"; - case "SystemMessage": return "system"; - case "ChatMessage": return "chat"; - default: throw new Error("Invalid message class name"); - } - } - static fromTemplate(template, additionalOptions) { - if (typeof template === "string") return new this(PromptTemplate.fromTemplate(template, additionalOptions)); - const prompt = []; - for (const item of template) if (typeof item === "string") prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); - else if (item === null) {} else if (isTextTemplateParam(item)) { - let text = ""; - if (typeof item.text === "string") text = item.text ?? ""; - const options = { - ...additionalOptions, - additionalContentFields: item - }; - prompt.push(PromptTemplate.fromTemplate(text, options)); - } else if (isImageTemplateParam(item)) { - let imgTemplate = item.image_url ?? ""; - let imgTemplateObject; - let inputVariables = []; - if (typeof imgTemplate === "string") { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate); - else parsedTemplate = parseFString(imgTemplate); - const variables = parsedTemplate.flatMap((item$1) => item$1.type === "variable" ? [item$1.name] : []); - if ((variables?.length ?? 0) > 0) { - if (variables.length > 1) throw new Error(`Only one format variable allowed per image template.\nGot: ${variables}\nFrom: ${imgTemplate}`); - inputVariables = [variables[0]]; - } else inputVariables = []; - imgTemplate = { url: imgTemplate }; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else if (typeof imgTemplate === "object") { - if ("url" in imgTemplate) { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate.url); - else parsedTemplate = parseFString(imgTemplate.url); - inputVariables = parsedTemplate.flatMap((item$1) => item$1.type === "variable" ? [item$1.name] : []); - } else inputVariables = []; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else throw new Error("Invalid image template"); - prompt.push(imgTemplateObject); - } else if (typeof item === "object") prompt.push(new DictPromptTemplate({ - template: item, - templateFormat: additionalOptions?.templateFormat - })); - return new this({ - prompt, - additionalOptions - }); - } - async format(input) { - if (this.prompt instanceof BaseStringPromptTemplate) { - const text = await this.prompt.format(input); - return this.createMessage(text); - } else { - const content = []; - for (const prompt of this.prompt) { - let inputs = {}; - if (!("inputVariables" in prompt)) throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); - for (const item of prompt.inputVariables) { - if (!inputs) inputs = { [item]: input[item] }; - inputs = { - ...inputs, - [item]: input[item] - }; - } - if (prompt instanceof BaseStringPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; - if (formatted !== "") content.push({ - ...additionalContentFields, - type: "text", - text: formatted - }); - } else if (prompt instanceof ImagePromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; - content.push({ - ...additionalContentFields, - type: "image_url", - image_url: formatted - }); - } else if (prompt instanceof DictPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; - content.push({ - ...additionalContentFields, - ...formatted - }); - } - } - return this.createMessage(content); - } - } - async formatMessages(values) { - return [await this.format(values)]; - } -}; -/** -* Class that represents a human message prompt template. It extends the -* BaseMessageStringPromptTemplate. -* @example -* ```typescript -* const message = HumanMessagePromptTemplate.fromTemplate("{text}"); -* const formatted = await message.format({ text: "Hello world!" }); -* -* const chatPrompt = ChatPromptTemplate.fromMessages([message]); -* const formattedChatPrompt = await chatPrompt.invoke({ -* text: "Hello world!", -* }); -* ``` -*/ -var HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return HumanMessage; - } - static lc_name() { - return "HumanMessagePromptTemplate"; - } -}; -/** -* Class that represents an AI message prompt template. It extends the -* BaseMessageStringPromptTemplate. -*/ -var AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return AIMessage; - } - static lc_name() { - return "AIMessagePromptTemplate"; - } -}; -/** -* Class that represents a system message prompt template. It extends the -* BaseMessageStringPromptTemplate. -* @example -* ```typescript -* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); -* const formatted = await message.format({ text: "Hello world!" }); -* -* const chatPrompt = ChatPromptTemplate.fromMessages([message]); -* const formattedChatPrompt = await chatPrompt.invoke({ -* text: "Hello world!", -* }); -* ``` -*/ -var SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return SystemMessage; - } - static lc_name() { - return "SystemMessagePromptTemplate"; - } -}; -function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { - return typeof baseMessagePromptTemplateLike.formatMessages === "function"; -} -function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { - if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) return messagePromptTemplateLike; - if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { - const messageContent = messagePromptTemplateLike[1]; - if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") { - const variableName = messageContent.slice(2, -2); - return new MessagesPlaceholder({ - variableName, - optional: true - }); - } else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") { - const variableName = messageContent.slice(1, -1); - return new MessagesPlaceholder({ - variableName, - optional: true - }); - } - throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); - } - const message = utils_coerceMessageLikeToMessage(messagePromptTemplateLike); - let templateData; - if (typeof message.content === "string") templateData = message.content; - else templateData = message.content.map((item) => { - if ("text" in item) return { - ...item, - text: item.text - }; - else if ("image_url" in item) return { - ...item, - image_url: item.image_url - }; - else return item; - }); - if (message._getType() === "human") return HumanMessagePromptTemplate.fromTemplate(templateData, extra); - else if (message._getType() === "ai") return AIMessagePromptTemplate.fromTemplate(templateData, extra); - else if (message._getType() === "system") return SystemMessagePromptTemplate.fromTemplate(templateData, extra); - else if (ChatMessage.isInstance(message)) return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); - else throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); -} -function isMessagesPlaceholder(x) { - return x.constructor.lc_name() === "MessagesPlaceholder"; -} -/** -* Class that represents a chat prompt. It extends the -* BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate -* instances to format a series of messages for a conversation. -* @example -* ```typescript -* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); -* const chatPrompt = ChatPromptTemplate.fromMessages([ -* ["ai", "You are a helpful assistant."], -* message, -* ]); -* const formattedChatPrompt = await chatPrompt.invoke({ -* text: "Hello world!", -* }); -* ``` -*/ -var ChatPromptTemplate = class ChatPromptTemplate extends BaseChatPromptTemplate { - static lc_name() { - return "ChatPromptTemplate"; - } - get lc_aliases() { - return { promptMessages: "messages" }; - } - promptMessages; - validateTemplate = true; - templateFormat = "f-string"; - constructor(input) { - super(input); - if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; - Object.assign(this, input); - if (this.validateTemplate) { - const inputVariablesMessages = /* @__PURE__ */ new Set(); - for (const promptMessage of this.promptMessages) { - if (promptMessage instanceof BaseMessage) continue; - for (const inputVariable of promptMessage.inputVariables) inputVariablesMessages.add(inputVariable); - } - const totalInputVariables = this.inputVariables; - const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); - const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); - if (difference.size > 0) throw new Error(`Input variables \`${[...difference]}\` are not used in any of the prompt messages.`); - const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); - if (otherDifference.size > 0) throw new Error(`Input variables \`${[...otherDifference]}\` are used in prompt messages but not in the prompt template.`); - } - } - _getPromptType() { - return "chat"; - } - async _parseImagePrompts(message, inputValues) { - if (typeof message.content === "string") return message; - const formattedMessageContent = await Promise.all(message.content.map(async (item) => { - if (item.type !== "image_url") return item; - let imageUrl = ""; - if (typeof item.image_url === "string") imageUrl = item.image_url; - else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url && typeof item.image_url.url === "string") imageUrl = item.image_url.url; - const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat }); - const formattedUrl = await promptTemplatePlaceholder.format(inputValues); - if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) item.image_url.url = formattedUrl; - else item.image_url = formattedUrl; - return item; - })); - message.content = formattedMessageContent; - return message; - } - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let resultMessages = []; - for (const promptMessage of this.promptMessages) if (promptMessage instanceof BaseMessage) resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); - else { - let inputValues; - if (this.templateFormat === "mustache") inputValues = { ...allValues }; - else inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { - if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) { - const error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); - throw error; - } - acc[inputVariable] = allValues[inputVariable]; - return acc; - }, {}); - const message = await promptMessage.formatMessages(inputValues); - resultMessages = resultMessages.concat(message); - } - return resultMessages; - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new ChatPromptTemplate(promptDict); - } - static fromTemplate(template, options) { - const prompt = PromptTemplate.fromTemplate(template, options); - const humanTemplate = new HumanMessagePromptTemplate({ prompt }); - return this.fromMessages([humanTemplate]); - } - /** - * Create a chat model-specific prompt from individual chat messages - * or message-like tuples. - * @param promptMessages Messages to be passed to the chat model - * @returns A new ChatPromptTemplate - */ - static fromMessages(promptMessages, extra) { - const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []); - const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); - const inputVariables = /* @__PURE__ */ new Set(); - for (const promptMessage of flattenedMessages) { - if (promptMessage instanceof BaseMessage) continue; - for (const inputVariable of promptMessage.inputVariables) { - if (inputVariable in flattenedPartialVariables) continue; - inputVariables.add(inputVariable); - } - } - return new this({ - ...extra, - inputVariables: [...inputVariables], - promptMessages: flattenedMessages, - partialVariables: flattenedPartialVariables, - templateFormat: extra?.templateFormat - }); - } -}; - -//#endregion - -//# sourceMappingURL=chat.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/few_shot.js - - - - - -//#region src/prompts/few_shot.ts -/** -* Prompt template that contains few-shot examples. -* @augments BasePromptTemplate -* @augments FewShotPromptTemplateInput -* @example -* ```typescript -* const examplePrompt = PromptTemplate.fromTemplate( -* "Input: {input}\nOutput: {output}", -* ); -* -* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( -* [ -* { input: "happy", output: "sad" }, -* { input: "tall", output: "short" }, -* { input: "energetic", output: "lethargic" }, -* { input: "sunny", output: "gloomy" }, -* { input: "windy", output: "calm" }, -* ], -* new OpenAIEmbeddings(), -* HNSWLib, -* { k: 1 }, -* ); -* -* const dynamicPrompt = new FewShotPromptTemplate({ -* exampleSelector, -* examplePrompt, -* prefix: "Give the antonym of every input", -* suffix: "Input: {adjective}\nOutput:", -* inputVariables: ["adjective"], -* }); -* -* // Format the dynamic prompt with the input 'rainy' -* console.log(await dynamicPrompt.format({ adjective: "rainy" })); -* -* ``` -*/ -var FewShotPromptTemplate = class FewShotPromptTemplate extends BaseStringPromptTemplate { - lc_serializable = false; - examples; - exampleSelector; - examplePrompt; - suffix = ""; - exampleSeparator = "\n\n"; - prefix = ""; - templateFormat = "f-string"; - validateTemplate = true; - constructor(input) { - super(input); - Object.assign(this, input); - if (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - if (this.examples === void 0 && this.exampleSelector === void 0) throw new Error("One of 'examples' and 'example_selector' should be provided"); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "few_shot"; - } - static lc_name() { - return "FewShotPromptTemplate"; - } - async getExamples(inputVariables) { - if (this.examples !== void 0) return this.examples; - if (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables); - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new FewShotPromptTemplate(promptDict); - } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); - const template = [ - this.prefix, - ...exampleStrings, - this.suffix - ].join(this.exampleSeparator); - return renderTemplate(template, this.templateFormat, allValues); - } - serialize() { - if (this.exampleSelector || !this.examples) throw new Error("Serializing an example selector is not currently supported"); - if (this.outputParser !== void 0) throw new Error("Serializing an output parser is not currently supported"); - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - example_prompt: this.examplePrompt.serialize(), - example_separator: this.exampleSeparator, - suffix: this.suffix, - prefix: this.prefix, - template_format: this.templateFormat, - examples: this.examples - }; - } - static async deserialize(data) { - const { example_prompt } = data; - if (!example_prompt) throw new Error("Missing example prompt"); - const examplePrompt = await PromptTemplate.deserialize(example_prompt); - let examples; - if (Array.isArray(data.examples)) examples = data.examples; - else throw new Error("Invalid examples format. Only list or string are supported."); - return new FewShotPromptTemplate({ - inputVariables: data.input_variables, - examplePrompt, - examples, - exampleSeparator: data.example_separator, - prefix: data.prefix, - suffix: data.suffix, - templateFormat: data.template_format - }); - } -}; -/** -* Chat prompt template that contains few-shot examples. -* @augments BasePromptTemplateInput -* @augments FewShotChatMessagePromptTemplateInput -*/ -var FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate extends BaseChatPromptTemplate { - lc_serializable = true; - examples; - exampleSelector; - examplePrompt; - suffix = ""; - exampleSeparator = "\n\n"; - prefix = ""; - templateFormat = "f-string"; - validateTemplate = true; - _getPromptType() { - return "few_shot_chat"; - } - static lc_name() { - return "FewShotChatMessagePromptTemplate"; - } - constructor(fields) { - super(fields); - this.examples = fields.examples; - this.examplePrompt = fields.examplePrompt; - this.exampleSeparator = fields.exampleSeparator ?? "\n\n"; - this.exampleSelector = fields.exampleSelector; - this.prefix = fields.prefix ?? ""; - this.suffix = fields.suffix ?? ""; - this.templateFormat = fields.templateFormat ?? "f-string"; - this.validateTemplate = fields.validateTemplate ?? true; - if (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - if (this.examples === void 0 && this.exampleSelector === void 0) throw new Error("One of 'examples' and 'example_selector' should be provided"); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - async getExamples(inputVariables) { - if (this.examples !== void 0) return this.examples; - if (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables); - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - /** - * Formats the list of values and returns a list of formatted messages. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let examples = await this.getExamples(allValues); - examples = examples.map((example) => { - const result = {}; - this.examplePrompt.inputVariables.forEach((inputVariable) => { - result[inputVariable] = example[inputVariable]; - }); - return result; - }); - const messages = []; - for (const example of examples) { - const exampleMessages = await this.examplePrompt.formatMessages(example); - messages.push(...exampleMessages); - } - return messages; - } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example))); - const exampleStrings = exampleMessages.flat().map((message) => message.content); - const template = [ - this.prefix, - ...exampleStrings, - this.suffix - ].join(this.exampleSeparator); - return renderTemplate(template, this.templateFormat, allValues); - } - /** - * Partially formats the prompt with the given values. - * @param values The values to partially format the prompt with. - * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new FewShotChatMessagePromptTemplate(promptDict); - } -}; - -//#endregion - -//# sourceMappingURL=few_shot.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/pipeline.js - - - -//#region src/prompts/pipeline.ts -/** -* Class that handles a sequence of prompts, each of which may require -* different input variables. Includes methods for formatting these -* prompts, extracting required input values, and handling partial -* prompts. -* @example -* ```typescript -* const composedPrompt = new PipelinePromptTemplate({ -* pipelinePrompts: [ -* { -* name: "introduction", -* prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`), -* }, -* { -* name: "example", -* prompt: PromptTemplate.fromTemplate( -* `Here's an example of an interaction: -* Q: {example_q} -* A: {example_a}`, -* ), -* }, -* { -* name: "start", -* prompt: PromptTemplate.fromTemplate( -* `Now, do this for real! -* Q: {input} -* A:`, -* ), -* }, -* ], -* finalPrompt: PromptTemplate.fromTemplate( -* `{introduction} -* {example} -* {start}`, -* ), -* }); -* -* const formattedPrompt = await composedPrompt.format({ -* person: "Elon Musk", -* example_q: `What's your favorite car?`, -* example_a: "Tesla", -* input: `What's your favorite social media site?`, -* }); -* ``` -*/ -var PipelinePromptTemplate = class PipelinePromptTemplate extends BasePromptTemplate { - static lc_name() { - return "PipelinePromptTemplate"; - } - pipelinePrompts; - finalPrompt; - constructor(input) { - super({ - ...input, - inputVariables: [] - }); - this.pipelinePrompts = input.pipelinePrompts; - this.finalPrompt = input.finalPrompt; - this.inputVariables = this.computeInputValues(); - } - /** - * Computes the input values required by the pipeline prompts. - * @returns Array of input values required by the pipeline prompts. - */ - computeInputValues() { - const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); - const inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat(); - return [...new Set(inputValues)]; - } - static extractRequiredInputValues(allValues, requiredValueNames) { - return requiredValueNames.reduce((requiredValues, valueName) => { - requiredValues[valueName] = allValues[valueName]; - return requiredValues; - }, {}); - } - /** - * Formats the pipeline prompts based on the provided input values. - * @param values Input values to format the pipeline prompts. - * @returns Promise that resolves with the formatted input values. - */ - async formatPipelinePrompts(values) { - const allValues = await this.mergePartialAndUserVariables(values); - for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) { - const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); - if (pipelinePrompt instanceof ChatPromptTemplate) allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); - else allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); - } - return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); - } - /** - * Formats the final prompt value based on the provided input values. - * @param values Input values to format the final prompt value. - * @returns Promise that resolves with the formatted final prompt value. - */ - async formatPromptValue(values) { - return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); - } - async format(values) { - return this.finalPrompt.format(await this.formatPipelinePrompts(values)); - } - /** - * Handles partial prompts, which are prompts that have been partially - * filled with input values. - * @param values Partial input values. - * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. - */ - async partial(values) { - const promptDict = { ...this }; - promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); - promptDict.partialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new PipelinePromptTemplate(promptDict); - } - serialize() { - throw new Error("Not implemented."); - } - _getPromptType() { - return "pipeline"; - } -}; - -//#endregion - -//# sourceMappingURL=pipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/structured.js - - - -//#region src/prompts/structured.ts -function isWithStructuredOutput(x) { - return typeof x === "object" && x != null && "withStructuredOutput" in x && typeof x.withStructuredOutput === "function"; -} -function isRunnableBinding(x) { - return typeof x === "object" && x != null && "lc_id" in x && Array.isArray(x.lc_id) && x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding"; -} -var StructuredPrompt = class StructuredPrompt extends ChatPromptTemplate { - schema; - method; - lc_namespace = [ - "langchain_core", - "prompts", - "structured" - ]; - get lc_aliases() { - return { - ...super.lc_aliases, - schema: "schema_" - }; - } - constructor(input) { - super(input); - this.schema = input.schema; - this.method = input.method; - } - pipe(coerceable) { - if (isWithStructuredOutput(coerceable)) return super.pipe(coerceable.withStructuredOutput(this.schema)); - if (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) return super.pipe(new RunnableBinding({ - bound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []), - kwargs: coerceable.kwargs ?? {}, - config: coerceable.config, - configFactories: coerceable.configFactories - })); - throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); - } - static fromMessagesAndSchema(promptMessages, schema, method) { - return StructuredPrompt.fromMessages(promptMessages, { - schema, - method - }); - } -}; - -//#endregion - -//# sourceMappingURL=structured.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/index.js - - - - - - - - - - - - -//#region src/prompts/index.ts -var prompts_exports = {}; -__export(prompts_exports, { - AIMessagePromptTemplate: () => AIMessagePromptTemplate, - BaseChatPromptTemplate: () => BaseChatPromptTemplate, - BaseMessagePromptTemplate: () => BaseMessagePromptTemplate, - BaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate, - BasePromptTemplate: () => BasePromptTemplate, - BaseStringPromptTemplate: () => BaseStringPromptTemplate, - ChatMessagePromptTemplate: () => ChatMessagePromptTemplate, - ChatPromptTemplate: () => ChatPromptTemplate, - DEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING, - DEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING, - DictPromptTemplate: () => DictPromptTemplate, - FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, - FewShotPromptTemplate: () => FewShotPromptTemplate, - HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, - ImagePromptTemplate: () => ImagePromptTemplate, - MessagesPlaceholder: () => MessagesPlaceholder, - PipelinePromptTemplate: () => PipelinePromptTemplate, - PromptTemplate: () => PromptTemplate, - StructuredPrompt: () => StructuredPrompt, - SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, - checkValidTemplate: () => checkValidTemplate, - interpolateFString: () => interpolateFString, - interpolateMustache: () => interpolateMustache, - parseFString: () => parseFString, - parseMustache: () => parseMustache, - parseTemplate: () => template_parseTemplate, - renderTemplate: () => renderTemplate -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/retrievers/document_compressors/base.js - - -//#region src/retrievers/document_compressors/base.ts -var document_compressors_base_base_exports = {}; -__export(document_compressors_base_base_exports, { BaseDocumentCompressor: () => BaseDocumentCompressor }); -/** -* Base Document Compression class. All compressors should extend this class. -*/ -var BaseDocumentCompressor = class { - static isBaseDocumentCompressor(x) { - return x?.compressDocuments !== void 0; - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/ir.js -//#region src/structured_query/ir.ts -const Operators = { - and: "and", - or: "or", - not: "not" -}; -const Comparators = { - eq: "eq", - ne: "ne", - lt: "lt", - gt: "gt", - lte: "lte", - gte: "gte" -}; -/** -* Abstract class for visiting expressions. Subclasses must implement -* visitOperation, visitComparison, and visitStructuredQuery methods. -*/ -var Visitor = class {}; -/** -* Abstract class representing an expression. Subclasses must implement -* the exprName property and the accept method. -*/ -var Expression = class { - accept(visitor) { - if (this.exprName === "Operation") return visitor.visitOperation(this); - else if (this.exprName === "Comparison") return visitor.visitComparison(this); - else if (this.exprName === "StructuredQuery") return visitor.visitStructuredQuery(this); - else throw new Error("Unknown Expression type"); - } -}; -/** -* Abstract class representing a filter directive. It extends the -* Expression class. -*/ -var FilterDirective = class extends Expression {}; -/** -* Class representing a comparison filter directive. It extends the -* FilterDirective class. -*/ -var Comparison = class extends FilterDirective { - exprName = "Comparison"; - constructor(comparator, attribute, value) { - super(); - this.comparator = comparator; - this.attribute = attribute; - this.value = value; - } -}; -/** -* Class representing an operation filter directive. It extends the -* FilterDirective class. -*/ -var Operation = class extends FilterDirective { - exprName = "Operation"; - constructor(operator, args) { - super(); - this.operator = operator; - this.args = args; - } -}; -/** -* Class representing a structured query expression. It extends the -* Expression class. -*/ -var StructuredQuery = class extends Expression { - exprName = "StructuredQuery"; - constructor(query, filter) { - super(); - this.query = query; - this.filter = filter; - } -}; - -//#endregion - -//# sourceMappingURL=ir.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/utils.js -//#region src/structured_query/utils.ts -/** -* Checks if the provided argument is an object and not an array. -*/ -function utils_isObject(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj); -} -/** -* Checks if a provided filter is empty. The filter can be a function, an -* object, a string, or undefined. -*/ -function isFilterEmpty(filter) { - if (!filter) return true; - if (typeof filter === "string" && filter.length > 0) return false; - if (typeof filter === "function") return false; - return utils_isObject(filter) && Object.keys(filter).length === 0; -} -/** -* Checks if the provided value is an integer. -*/ -function isInt(value) { - if (typeof value === "number") return value % 1 === 0; - else if (typeof value === "string") { - const numberValue = parseInt(value, 10); - return !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value; - } - return false; -} -/** -* Checks if the provided value is a floating-point number. -*/ -function isFloat(value) { - if (typeof value === "number") return value % 1 !== 0; - else if (typeof value === "string") { - const numberValue = parseFloat(value); - return !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value; - } - return false; -} -/** -* Checks if the provided value is a string that cannot be parsed into a -* number. -*/ -function isString(value) { - return typeof value === "string" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value); -} -/** -* Checks if the provided value is a boolean. -*/ -function isBoolean(value) { - return typeof value === "boolean"; -} -/** -* Casts a value that might be string or number to actual string or number. -* Since LLM might return back an integer/float as a string, we need to cast -* it back to a number, as many vector databases can't handle number as string -* values as a comparator. -*/ -function castValue(input) { - let value; - if (isString(input)) value = input; - else if (isInt(input)) value = parseInt(input, 10); - else if (isFloat(input)) value = parseFloat(input); - else if (isBoolean(input)) value = Boolean(input); - else throw new Error("Unsupported value type"); - return value; -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/base.js - - - -//#region src/structured_query/base.ts -/** -* Abstract class that provides a blueprint for creating specific -* translator classes. Defines two abstract methods: formatFunction and -* mergeFilters. -*/ -var BaseTranslator = class extends Visitor {}; -/** -* Class that extends the BaseTranslator class and provides concrete -* implementations for the abstract methods. Also declares three types: -* VisitOperationOutput, VisitComparisonOutput, and -* VisitStructuredQueryOutput, which are used as the return types for the -* visitOperation, visitComparison, and visitStructuredQuery methods -* respectively. -*/ -var BasicTranslator = class extends BaseTranslator { - allowedOperators; - allowedComparators; - constructor(opts) { - super(); - this.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or]; - this.allowedComparators = opts?.allowedComparators ?? [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - } - formatFunction(func) { - if (func in Comparators) { - if (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`); - } else if (func in Operators) { - if (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`); - } else throw new Error("Unknown comparator or operator"); - return `$${func}`; - } - /** - * Visits an operation and returns a result. - * @param operation The operation to visit. - * @returns The result of visiting the operation. - */ - visitOperation(operation) { - const args = operation.args?.map((arg) => arg.accept(this)); - return { [this.formatFunction(operation.operator)]: args }; - } - /** - * Visits a comparison and returns a result. - * @param comparison The comparison to visit. - * @returns The result of visiting the comparison. - */ - visitComparison(comparison) { - return { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } }; - } - /** - * Visits a structured query and returns a result. - * @param query The structured query to visit. - * @returns The result of visiting the structured query. - */ - visitStructuredQuery(query) { - let nextArg = {}; - if (query.filter) nextArg = { filter: query.filter.accept(this) }; - return nextArg; - } - mergeFilters(defaultFilter, generatedFilter, mergeType = "and", forceDefaultFilter = false) { - if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0; - if (isFilterEmpty(defaultFilter) || mergeType === "replace") { - if (isFilterEmpty(generatedFilter)) return void 0; - return generatedFilter; - } - if (isFilterEmpty(generatedFilter)) { - if (forceDefaultFilter) return defaultFilter; - if (mergeType === "and") return void 0; - return defaultFilter; - } - if (mergeType === "and") return { $and: [defaultFilter, generatedFilter] }; - else if (mergeType === "or") return { $or: [defaultFilter, generatedFilter] }; - else throw new Error("Unknown merge type"); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/functional.js - - - - -//#region src/structured_query/functional.ts -/** -* A class that extends `BaseTranslator` to translate structured queries -* into functional filters. -* @example -* ```typescript -* const functionalTranslator = new FunctionalTranslator(); -* const relevantDocuments = await functionalTranslator.getRelevantDocuments( -* "Which movies are rated higher than 8.5?", -* ); -* ``` -*/ -var FunctionalTranslator = class extends BaseTranslator { - allowedOperators = [Operators.and, Operators.or]; - allowedComparators = [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - formatFunction() { - throw new Error("Not implemented"); - } - /** - * Returns the allowed comparators for a given data type. - * @param input The input value to get the allowed comparators for. - * @returns An array of allowed comparators for the input data type. - */ - getAllowedComparatorsForType(inputType) { - switch (inputType) { - case "string": return [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - case "number": return [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - case "boolean": return [Comparators.eq, Comparators.ne]; - default: throw new Error(`Unsupported data type: ${inputType}`); - } - } - /** - * Returns a function that performs a comparison based on the provided - * comparator. - * @param comparator The comparator to base the comparison function on. - * @returns A function that takes two arguments and returns a boolean based on the comparison. - */ - getComparatorFunction(comparator) { - switch (comparator) { - case Comparators.eq: return (a, b) => a === b; - case Comparators.ne: return (a, b) => a !== b; - case Comparators.gt: return (a, b) => a > b; - case Comparators.gte: return (a, b) => a >= b; - case Comparators.lt: return (a, b) => a < b; - case Comparators.lte: return (a, b) => a <= b; - default: throw new Error("Unknown comparator"); - } - } - /** - * Returns a function that performs an operation based on the provided - * operator. - * @param operator The operator to base the operation function on. - * @returns A function that takes two boolean arguments and returns a boolean based on the operation. - */ - getOperatorFunction(operator) { - switch (operator) { - case Operators.and: return (a, b) => a && b; - case Operators.or: return (a, b) => a || b; - default: throw new Error("Unknown operator"); - } - } - /** - * Visits the operation part of a structured query and translates it into - * a functional filter. - * @param operation The operation part of a structured query. - * @returns A function that takes a `Document` as an argument and returns a boolean based on the operation. - */ - visitOperation(operation) { - const { operator, args } = operation; - if (this.allowedOperators.includes(operator)) { - const operatorFunction = this.getOperatorFunction(operator); - return (document) => { - if (!args) return true; - return args.reduce((acc, arg) => { - const result = arg.accept(this); - if (typeof result === "function") return operatorFunction(acc, result(document)); - else throw new Error("Filter is not a function"); - }, true); - }; - } else throw new Error("Operator not allowed"); - } - /** - * Visits the comparison part of a structured query and translates it into - * a functional filter. - * @param comparison The comparison part of a structured query. - * @returns A function that takes a `Document` as an argument and returns a boolean based on the comparison. - */ - visitComparison(comparison) { - const { comparator, attribute, value } = comparison; - const undefinedTrue = [Comparators.ne]; - if (this.allowedComparators.includes(comparator)) { - if (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`); - const comparatorFunction = this.getComparatorFunction(comparator); - return (document) => { - const documentValue = document.metadata[attribute]; - if (documentValue === void 0) { - if (undefinedTrue.includes(comparator)) return true; - return false; - } - return comparatorFunction(documentValue, castValue(value)); - }; - } else throw new Error("Comparator not allowed"); - } - /** - * Visits a structured query and translates it into a functional filter. - * @param query The structured query to translate. - * @returns An object containing a `filter` property, which is a function that takes a `Document` as an argument and returns a boolean based on the structured query. - */ - visitStructuredQuery(query) { - if (!query.filter) return {}; - const filterFunction = query.filter?.accept(this); - if (typeof filterFunction !== "function") throw new Error("Structured query filter is not a function"); - return { filter: filterFunction }; - } - /** - * Merges two filters into one, based on the specified merge type. - * @param defaultFilter The default filter function. - * @param generatedFilter The generated filter function. - * @param mergeType The type of merge to perform. Can be 'and', 'or', or 'replace'. Default is 'and'. - * @returns A function that takes a `Document` as an argument and returns a boolean based on the merged filters, or `undefined` if both filters are empty. - */ - mergeFilters(defaultFilter, generatedFilter, mergeType = "and") { - if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0; - if (isFilterEmpty(defaultFilter) || mergeType === "replace") { - if (isFilterEmpty(generatedFilter)) return void 0; - return generatedFilter; - } - if (isFilterEmpty(generatedFilter)) { - if (mergeType === "and") return void 0; - return defaultFilter; - } - if (mergeType === "and") return (document) => defaultFilter(document) && generatedFilter(document); - else if (mergeType === "or") return (document) => defaultFilter(document) || generatedFilter(document); - else throw new Error("Unknown merge type"); - } -}; - -//#endregion - -//# sourceMappingURL=functional.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/index.js - - - - - - -//#region src/structured_query/index.ts -var structured_query_exports = {}; -__export(structured_query_exports, { - BaseTranslator: () => BaseTranslator, - BasicTranslator: () => BasicTranslator, - Comparators: () => Comparators, - Comparison: () => Comparison, - Expression: () => Expression, - FilterDirective: () => FilterDirective, - FunctionalTranslator: () => FunctionalTranslator, - Operation: () => Operation, - Operators: () => Operators, - StructuredQuery: () => StructuredQuery, - Visitor: () => Visitor, - castValue: () => castValue, - isBoolean: () => isBoolean, - isFilterEmpty: () => isFilterEmpty, - isFloat: () => isFloat, - isInt: () => isInt, - isObject: () => utils_isObject, - isString: () => isString -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/types.js - - - -//#region src/tools/types.ts -/** -* Confirm whether the inputted tool is an instance of `StructuredToolInterface`. -* -* @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`. -* @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`. -*/ -function isStructuredTool(tool) { - return tool !== void 0 && Array.isArray(tool.lc_namespace); -} -/** -* Confirm whether the inputted tool is an instance of `RunnableToolLike`. -* -* @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`. -* @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`. -*/ -function isRunnableToolLike(tool) { - return tool !== void 0 && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike"; -} -/** -* Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`. -* -* @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`. -* @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`. -*/ -function isStructuredToolParams(tool) { - return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === "object" && "type" in tool.schema && typeof tool.schema.type === "string" && [ - "null", - "boolean", - "object", - "array", - "number", - "string" - ].includes(tool.schema.type)); -} -/** -* Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. -* It returns `is StructuredToolParams` since that is the most minimal interface of the three, -* while still containing the necessary properties to be passed to a LLM for tool calling. -* -* @param {unknown | undefined} tool The tool to check if it is a LangChain tool. -* @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool. -*/ -function isLangChainTool(tool) { - return isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool); -} - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/index.js - - - - - - - - - - - - - - - - -//#region src/tools/index.ts -var tools_exports = {}; -__export(tools_exports, { - BaseToolkit: () => BaseToolkit, - DynamicStructuredTool: () => tools_DynamicStructuredTool, - DynamicTool: () => tools_DynamicTool, - StructuredTool: () => StructuredTool, - Tool: () => Tool, - ToolInputParsingException: () => ToolInputParsingException, - isLangChainTool: () => isLangChainTool, - isRunnableToolLike: () => isRunnableToolLike, - isStructuredTool: () => isStructuredTool, - isStructuredToolParams: () => isStructuredToolParams, - tool: () => tool -}); -/** -* Base class for Tools that accept input of any shape defined by a Zod schema. -*/ -var StructuredTool = class extends BaseLangChain { - /** - * Whether to return the tool's output directly. - * - * Setting this to true means that after the tool is called, - * an agent should stop looping. - */ - returnDirect = false; - verboseParsingErrors = false; - get lc_namespace() { - return ["langchain", "tools"]; - } - /** - * The tool response format. - * - * If "content" then the output of the tool is interpreted as the contents of a - * ToolMessage. If "content_and_artifact" then the output is expected to be a - * two-tuple corresponding to the (content, artifact) of a ToolMessage. - * - * @default "content" - */ - responseFormat = "content"; - /** - * Default config object for the tool runnable. - */ - defaultConfig; - constructor(fields) { - super(fields ?? {}); - this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors; - this.responseFormat = fields?.responseFormat ?? this.responseFormat; - this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig; - this.metadata = fields?.metadata ?? this.metadata; - } - /** - * Invokes the tool with the provided input and configuration. - * @param input The input for the tool. - * @param config Optional configuration for the tool. - * @returns A Promise that resolves with the tool's output. - */ - async invoke(input, config) { - let toolInput; - let enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config)); - if (_isToolCall(input)) { - toolInput = input.args; - enrichedConfig = { - ...enrichedConfig, - toolCall: input - }; - } else toolInput = input; - return this.call(toolInput, enrichedConfig); - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - * - * Calls the tool with the provided argument, configuration, and tags. It - * parses the input according to the schema, handles any errors, and - * manages callbacks. - * @param arg The input argument for the tool. - * @param configArg Optional configuration or callbacks for the tool. - * @param tags Optional tags for the tool. - * @returns A Promise that resolves with a string. - */ - async call(arg, configArg, tags) { - const inputForValidation = _isToolCall(arg) ? arg.args : arg; - let parsed; - if (isInteropZodSchema(this.schema)) try { - parsed = await interopParseAsync(this.schema, inputForValidation); - } catch (e) { - let message = `Received tool input did not match expected schema`; - if (this.verboseParsingErrors) message = `${message}\nDetails: ${e.message}`; - if (e instanceof Error && e.constructor.name === "ZodError") message = `${message}\n\n${prettifyError(e)}`; - throw new ToolInputParsingException(message, JSON.stringify(arg)); - } - else { - const result$1 = validate_validate(inputForValidation, this.schema); - if (!result$1.valid) { - let message = `Received tool input did not match expected schema`; - if (this.verboseParsingErrors) message = `${message}\nDetails: ${result$1.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join("\n")}`; - throw new ToolInputParsingException(message, JSON.stringify(arg)); - } - parsed = inputForValidation; - } - const config = parseCallbackConfigArg(configArg); - const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose }); - const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === "string" ? arg : JSON.stringify(arg), config.runId, void 0, void 0, void 0, config.runName); - delete config.runId; - let result; - try { - result = await this._call(parsed, runManager, config); - } catch (e) { - await runManager?.handleToolError(e); - throw e; - } - let content; - let artifact; - if (this.responseFormat === "content_and_artifact") if (Array.isArray(result) && result.length === 2) [content, artifact] = result; - else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`); - else content = result; - let toolCallId; - if (_isToolCall(arg)) toolCallId = arg.id; - if (!toolCallId && _configHasToolCallId(config)) toolCallId = config.toolCall.id; - const formattedOutput = _formatToolOutput({ - content, - artifact, - toolCallId, - name: this.name, - metadata: this.metadata - }); - await runManager?.handleToolEnd(formattedOutput); - return formattedOutput; - } -}; -/** -* Base class for Tools that accept input as a string. -*/ -var Tool = class extends StructuredTool { - schema = objectType({ input: stringType().optional() }).transform((obj) => obj.input); - constructor(fields) { - super(fields); - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - * - * Calls the tool with the provided argument and callbacks. It handles - * string inputs specifically. - * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema. - * @param callbacks Optional callbacks for the tool. - * @returns A Promise that resolves with a string. - */ - call(arg, callbacks) { - const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg; - return super.call(structuredArg, callbacks); - } -}; -/** -* A tool that can be created dynamically from a function, name, and description. -*/ -var tools_DynamicTool = class extends Tool { - static lc_name() { - return "DynamicTool"; - } - name; - description; - func; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.func = fields.func; - this.returnDirect = fields.returnDirect ?? this.returnDirect; - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - */ - async call(arg, configArg) { - const config = parseCallbackConfigArg(configArg); - if (config.runName === void 0) config.runName = this.name; - return super.call(arg, config); - } - /** @ignore */ - async _call(input, runManager, parentConfig) { - return this.func(input, runManager, parentConfig); - } -}; -/** -* A tool that can be created dynamically from a function, name, and -* description, designed to work with structured data. It extends the -* StructuredTool class and overrides the _call method to execute the -* provided function when the tool is called. -* -* Schema can be passed as Zod or JSON schema. The tool will not validate -* input if JSON schema is passed. -*/ -var tools_DynamicStructuredTool = class extends StructuredTool { - static lc_name() { - return "DynamicStructuredTool"; - } - name; - description; - func; - schema; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.func = fields.func; - this.returnDirect = fields.returnDirect ?? this.returnDirect; - this.schema = fields.schema; - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - */ - async call(arg, configArg, tags) { - const config = parseCallbackConfigArg(configArg); - if (config.runName === void 0) config.runName = this.name; - return super.call(arg, config, tags); - } - _call(arg, runManager, parentConfig) { - return this.func(arg, runManager, parentConfig); - } -}; -/** -* Abstract base class for toolkits in LangChain. Toolkits are collections -* of tools that agents can use. Subclasses must implement the `tools` -* property to provide the specific tools for the toolkit. -*/ -var BaseToolkit = class { - getTools() { - return this.tools; - } -}; -function tool(func, fields) { - const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema); - const isStringJSONSchema = validatesOnlyStrings(fields.schema); - if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) return new tools_DynamicTool({ - ...fields, - description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`, - func: async (input, runManager, config) => { - return new Promise((resolve, reject) => { - const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - resolve(func(input, childConfig)); - } catch (e) { - reject(e); - } - }); - }); - } - }); - const schema = fields.schema; - const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`; - return new tools_DynamicStructuredTool({ - ...fields, - description, - schema, - func: async (input, runManager, config) => { - return new Promise((resolve, reject) => { - if (config?.signal) config.signal.addEventListener("abort", () => { - return reject(getAbortSignalError(config.signal)); - }); - const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - const result = await func(input, childConfig); - /** - * If the signal is aborted, we don't want to resolve the promise - * as the promise is already rejected. - */ - if (config?.signal?.aborted) return; - resolve(result); - } catch (e) { - reject(e); - } - }); - }); - } - }); -} -function _formatToolOutput(params) { - const { content, artifact, toolCallId, metadata } = params; - if (toolCallId && !isDirectToolOutput(content)) if (typeof content === "string" || Array.isArray(content) && content.every((item) => typeof item === "object")) return new ToolMessage({ - status: "success", - content, - artifact, - tool_call_id: toolCallId, - name: params.name, - metadata - }); - else return new ToolMessage({ - status: "success", - content: tools_stringify(content), - artifact, - tool_call_id: toolCallId, - name: params.name, - metadata - }); - else return content; -} -function tools_stringify(content) { - try { - return JSON.stringify(content, null, 2) ?? ""; - } catch (_noOp) { - return `${content}`; - } -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/run_collector.js - - - -//#region src/tracers/run_collector.ts -var run_collector_exports = {}; -__export(run_collector_exports, { RunCollectorCallbackHandler: () => RunCollectorCallbackHandler }); -/** -* A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object. -* For instance, it makes it easy to fetch the run ID and then do things with that, such as log feedback. -*/ -var RunCollectorCallbackHandler = class extends BaseTracer { - /** The name of the callback handler. */ - name = "run_collector"; - /** The ID of the example. */ - exampleId; - /** An array of traced runs. */ - tracedRuns; - /** - * Creates a new instance of the RunCollectorCallbackHandler class. - * @param exampleId The ID of the example. - */ - constructor({ exampleId } = {}) { - super({ _awaitHandler: true }); - this.exampleId = exampleId; - this.tracedRuns = []; - } - /** - * Persists the given run object. - * @param run The run object to persist. - */ - async persistRun(run) { - const run_ = { ...run }; - run_.reference_example_id = this.exampleId; - this.tracedRuns.push(run_); - } -}; - -//#endregion - -//# sourceMappingURL=run_collector.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/types/stream.js -//#region src/types/stream.ts -var stream_stream_exports = {}; - -//#endregion - -//# sourceMappingURL=stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/chunk_array.js - - -//#region src/utils/chunk_array.ts -var chunk_array_exports = {}; -__export(chunk_array_exports, { chunkArray: () => chunkArray }); -const chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => { - const chunkIndex = Math.floor(index / chunkSize); - const chunk = chunks[chunkIndex] || []; - chunks[chunkIndex] = chunk.concat([elem]); - return chunks; -}, []); - -//#endregion - -//# sourceMappingURL=chunk_array.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/event_source_parse.js - - - -//#region src/utils/event_source_parse.ts -var event_source_parse_exports = {}; -__export(event_source_parse_exports, { - EventStreamContentType: () => EventStreamContentType, - convertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream, - getBytes: () => getBytes, - getLines: () => getLines, - getMessages: () => getMessages -}); -const EventStreamContentType = "text/event-stream"; -/** -* Converts a ReadableStream into a callback pattern. -* @param stream The input ReadableStream. -* @param onChunk A function that will be called on each new byte chunk in the stream. -* @returns {Promise} A promise that will be resolved when the stream closes. -*/ -async function getBytes(stream, onChunk) { - if (stream instanceof ReadableStream) { - const reader = stream.getReader(); - while (true) { - const result = await reader.read(); - if (result.done) { - onChunk(new Uint8Array(), true); - break; - } - onChunk(result.value); - } - } else try { - for await (const chunk of stream) onChunk(new Uint8Array(chunk)); - onChunk(new Uint8Array(), true); - } catch (e) { - throw new Error([ - "Parsing event source stream failed.", - "Ensure your implementation of fetch returns a web or Node readable stream.", - `Error: ${e.message}` - ].join("\n")); - } -} -var ControlChars = /* @__PURE__ */ function(ControlChars$1) { - ControlChars$1[ControlChars$1["NewLine"] = 10] = "NewLine"; - ControlChars$1[ControlChars$1["CarriageReturn"] = 13] = "CarriageReturn"; - ControlChars$1[ControlChars$1["Space"] = 32] = "Space"; - ControlChars$1[ControlChars$1["Colon"] = 58] = "Colon"; - return ControlChars$1; -}(ControlChars || {}); -/** -* Parses arbitary byte chunks into EventSource line buffers. -* Each line should be of the format "field: value" and ends with \r, \n, or \r\n. -* @param onLine A function that will be called on each new EventSource line. -* @returns A function that should be called for each incoming byte chunk. -*/ -function getLines(onLine) { - let buffer; - let position; - let fieldLength; - let discardTrailingNewline = false; - return function onChunk(arr, flush) { - if (flush) { - onLine(arr, 0, true); - return; - } - if (buffer === void 0) { - buffer = arr; - position = 0; - fieldLength = -1; - } else buffer = event_source_parse_concat(buffer, arr); - const bufLength = buffer.length; - let lineStart = 0; - while (position < bufLength) { - if (discardTrailingNewline) { - if (buffer[position] === ControlChars.NewLine) lineStart = ++position; - discardTrailingNewline = false; - } - let lineEnd = -1; - for (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) { - case ControlChars.Colon: - if (fieldLength === -1) fieldLength = position - lineStart; - break; - case ControlChars.CarriageReturn: discardTrailingNewline = true; - case ControlChars.NewLine: - lineEnd = position; - break; - } - if (lineEnd === -1) break; - onLine(buffer.subarray(lineStart, lineEnd), fieldLength); - lineStart = position; - fieldLength = -1; - } - if (lineStart === bufLength) buffer = void 0; - else if (lineStart !== 0) { - buffer = buffer.subarray(lineStart); - position -= lineStart; - } - }; -} -/** -* Parses line buffers into EventSourceMessages. -* @param onId A function that will be called on each `id` field. -* @param onRetry A function that will be called on each `retry` field. -* @param onMessage A function that will be called on each message. -* @returns A function that should be called for each incoming line buffer. -*/ -function getMessages(onMessage, onId, onRetry) { - let message = newMessage(); - const decoder = new TextDecoder(); - return function onLine(line, fieldLength, flush) { - if (flush) { - if (!isEmpty(message)) { - onMessage?.(message); - message = newMessage(); - } - return; - } - if (line.length === 0) { - onMessage?.(message); - message = newMessage(); - } else if (fieldLength > 0) { - const field = decoder.decode(line.subarray(0, fieldLength)); - const valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1); - const value = decoder.decode(line.subarray(valueOffset)); - switch (field) { - case "data": - message.data = message.data ? message.data + "\n" + value : value; - break; - case "event": - message.event = value; - break; - case "id": - onId?.(message.id = value); - break; - case "retry": { - const retry = parseInt(value, 10); - if (!Number.isNaN(retry)) onRetry?.(message.retry = retry); - break; - } - } - } - }; -} -function event_source_parse_concat(a, b) { - const res = new Uint8Array(a.length + b.length); - res.set(a); - res.set(b, a.length); - return res; -} -function newMessage() { - return { - data: "", - event: "", - id: "", - retry: void 0 - }; -} -function convertEventStreamToIterableReadableDataStream(stream, onMetadataEvent) { - const dataStream = new ReadableStream({ async start(controller) { - const enqueueLine = getMessages((msg) => { - if (msg.event === "error") throw new Error(msg.data ?? "Unspecified event streaming error."); - else if (msg.event === "metadata") onMetadataEvent?.(msg); - else if (msg.data) controller.enqueue(msg.data); - }); - const onLine = (line, fieldLength, flush) => { - enqueueLine(line, fieldLength, flush); - if (flush) controller.close(); - }; - await getBytes(stream, getLines(onLine)); - } }); - return IterableReadableStream.fromReadableStream(dataStream); -} -function isEmpty(message) { - return message.data === "" && message.event === "" && message.id === "" && message.retry === void 0; -} - -//#endregion - -//# sourceMappingURL=event_source_parse.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/function_calling.js - - - - -//#region src/utils/function_calling.ts -var function_calling_exports = {}; -__export(function_calling_exports, { - convertToOpenAIFunction: () => convertToOpenAIFunction, - convertToOpenAITool: () => convertToOpenAITool, - isLangChainTool: () => isLangChainTool, - isRunnableToolLike: () => isRunnableToolLike, - isStructuredTool: () => isStructuredTool, - isStructuredToolParams: () => isStructuredToolParams -}); -/** -* Formats a `StructuredTool` or `RunnableToolLike` instance into a format -* that is compatible with OpenAI function calling. If `StructuredTool` or -* `RunnableToolLike` has a zod schema, the output will be converted into a -* JSON schema, which is then used as the parameters for the OpenAI tool. -* -* @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function. -* @returns {FunctionDefinition} The inputted tool in OpenAI function format. -*/ -function convertToOpenAIFunction(tool, fields) { - const fieldsCopy = typeof fields === "number" ? void 0 : fields; - return { - name: tool.name, - description: tool.description, - parameters: toJsonSchema(tool.schema), - ...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {} - }; -} -/** -* Formats a `StructuredTool` or `RunnableToolLike` instance into a -* format that is compatible with OpenAI tool calling. If `StructuredTool` or -* `RunnableToolLike` has a zod schema, the output will be converted into a -* JSON schema, which is then used as the parameters for the OpenAI tool. -* -* @param {StructuredToolInterface | Record | RunnableToolLike} tool The tool to convert to an OpenAI tool. -* @returns {ToolDefinition} The inputted tool in OpenAI tool format. -*/ -function convertToOpenAITool(tool, fields) { - const fieldsCopy = typeof fields === "number" ? void 0 : fields; - let toolDef; - if (isLangChainTool(tool)) toolDef = { - type: "function", - function: convertToOpenAIFunction(tool) - }; - else toolDef = tool; - if (fieldsCopy?.strict !== void 0) toolDef.function.strict = fieldsCopy.strict; - return toolDef; -} - -//#endregion - -//# sourceMappingURL=function_calling.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance/similarities.js -//#region src/utils/ml-distance/similarities.ts -/** -* Returns the average of cosine distances between vectors a and b -* @param a - first vector -* @param b - second vector -* -*/ -function cosine(a, b) { - let p = 0; - let p2 = 0; - let q2 = 0; - for (let i = 0; i < a.length; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; - } - return p / (Math.sqrt(p2) * Math.sqrt(q2)); -} - -//#endregion - -//# sourceMappingURL=similarities.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance/distances.js -//#region src/utils/ml-distance/distances.ts -/** -*Returns the Inner Product similarity between vectors a and b -* @link [Inner Product Similarity algorithm](https://www.naun.org/main/NAUN/ijmmas/mmmas-49.pdf) -* @param a - first vector -* @param b - second vector -* -*/ -function innerProduct(a, b) { - let ans = 0; - for (let i = 0; i < a.length; i++) ans += a[i] * b[i]; - return ans; -} - -//#endregion - -//# sourceMappingURL=distances.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js -//#region src/utils/ml-distance-euclidean/euclidean.ts -function squaredEuclidean(p, q) { - let d = 0; - for (let i = 0; i < p.length; i++) d += (p[i] - q[i]) * (p[i] - q[i]); - return d; -} -function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); -} - -//#endregion - -//# sourceMappingURL=euclidean.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/math.js - - - - - -//#region src/utils/math.ts -var math_exports = {}; -__export(math_exports, { - cosineSimilarity: () => cosineSimilarity, - euclideanDistance: () => euclideanDistance, - innerProduct: () => innerProduct$1, - matrixFunc: () => matrixFunc, - maximalMarginalRelevance: () => maximalMarginalRelevance, - normalize: () => normalize -}); -/** -* Apply a row-wise function between two matrices with the same number of columns. -* -* @param {number[][]} X - The first matrix. -* @param {number[][]} Y - The second matrix. -* @param {VectorFunction} func - The function to apply. -* -* @throws {Error} If the number of columns in X and Y are not the same. -* -* @returns {number[][] | [[]]} A matrix where each row represents the result of applying the function between the corresponding rows of X and Y. -*/ -function matrixFunc(X, Y, func) { - if (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) return [[]]; - if (X[0].length !== Y[0].length) throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`); - return X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity)); -} -function normalize(M, similarity = false) { - const max = matrixMaxVal(M); - return M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max)); -} -/** -* This function calculates the row-wise cosine similarity between two matrices with the same number of columns. -* -* @param {number[][]} X - The first matrix. -* @param {number[][]} Y - The second matrix. -* -* @throws {Error} If the number of columns in X and Y are not the same. -* -* @returns {number[][] | [[]]} A matrix where each row represents the cosine similarity values between the corresponding rows of X and Y. -*/ -function cosineSimilarity(X, Y) { - return matrixFunc(X, Y, cosine); -} -function innerProduct$1(X, Y) { - return matrixFunc(X, Y, innerProduct); -} -function euclideanDistance(X, Y) { - return matrixFunc(X, Y, euclidean); -} -/** -* This function implements the Maximal Marginal Relevance algorithm -* to select a set of embeddings that maximizes the diversity and relevance to a query embedding. -* -* @param {number[]|number[][]} queryEmbedding - The query embedding. -* @param {number[][]} embeddingList - The list of embeddings to select from. -* @param {number} [lambda=0.5] - The trade-off parameter between relevance and diversity. -* @param {number} [k=4] - The maximum number of embeddings to select. -* -* @returns {number[]} The indexes of the selected embeddings in the embeddingList. -*/ -function maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = .5, k = 4) { - if (Math.min(k, embeddingList.length) <= 0) return []; - const queryEmbeddingExpanded = Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding]; - const similarityToQuery = cosineSimilarity(queryEmbeddingExpanded, embeddingList)[0]; - const mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex; - const selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]]; - const selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex]; - while (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) { - let bestScore = -Infinity; - let bestIndex = -1; - const similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings); - similarityToQuery.forEach((queryScore, queryScoreIndex) => { - if (selectedEmbeddingsIndexes.includes(queryScoreIndex)) return; - const maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]); - const score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected; - if (score > bestScore) { - bestScore = score; - bestIndex = queryScoreIndex; - } - }); - selectedEmbeddings.push(embeddingList[bestIndex]); - selectedEmbeddingsIndexes.push(bestIndex); - } - return selectedEmbeddingsIndexes; -} -/** -* Finds the index of the maximum value in the given array. -* @param {number[]} array - The input array. -* -* @returns {number} The index of the maximum value in the array. If the array is empty, returns -1. -*/ -function argMax(array) { - if (array.length === 0) return { - maxIndex: -1, - maxValue: NaN - }; - let maxValue = array[0]; - let maxIndex = 0; - for (let i = 1; i < array.length; i += 1) if (array[i] > maxValue) { - maxIndex = i; - maxValue = array[i]; - } - return { - maxIndex, - maxValue - }; -} -function matrixMaxVal(arrays) { - return arrays.reduce((acc, array) => Math.max(acc, argMax(array).maxValue), 0); -} - -//#endregion - -//# sourceMappingURL=math.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/chat_models.js - - - - - - - -//#region src/utils/testing/chat_models.ts -var FakeChatModel = class extends BaseChatModel { - _combineLLMOutput() { - return []; - } - _llmType() { - return "fake"; - } - async _generate(messages, options, runManager) { - if (options?.stop?.length) return { generations: [{ - message: new AIMessage(options.stop[0]), - text: options.stop[0] - }] }; - const text = messages.map((m) => { - if (typeof m.content === "string") return m.content; - return JSON.stringify(m.content, null, 2); - }).join("\n"); - await runManager?.handleLLMNewToken(text); - return { - generations: [{ - message: new AIMessage(text), - text - }], - llmOutput: {} - }; - } -}; -var FakeStreamingChatModel = class FakeStreamingChatModel extends BaseChatModel { - sleep = 50; - responses = []; - chunks = []; - toolStyle = "openai"; - thrownErrorString; - tools = []; - constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString,...rest }) { - super(rest); - this.sleep = sleep; - this.responses = responses; - this.chunks = chunks; - this.toolStyle = toolStyle; - this.thrownErrorString = thrownErrorString; - } - _llmType() { - return "fake"; - } - bindTools(tools) { - const merged = [...this.tools, ...tools]; - const toolDicts = merged.map((t) => { - switch (this.toolStyle) { - case "openai": return { - type: "function", - function: { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - } - }; - case "anthropic": return { - name: t.name, - description: t.description, - input_schema: toJsonSchema(t.schema) - }; - case "bedrock": return { toolSpec: { - name: t.name, - description: t.description, - inputSchema: toJsonSchema(t.schema) - } }; - case "google": return { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - }; - default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); - } - }); - const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; - const next = new FakeStreamingChatModel({ - sleep: this.sleep, - responses: this.responses, - chunks: this.chunks, - toolStyle: this.toolStyle, - thrownErrorString: this.thrownErrorString - }); - next.tools = merged; - return next.withConfig({ tools: wrapped }); - } - async _generate(messages, _options, _runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const content = this.responses?.[0]?.content ?? messages[0].content ?? ""; - const generation = { generations: [{ - text: "", - message: new AIMessage({ - content, - tool_calls: this.chunks?.[0]?.tool_calls - }) - }] }; - return generation; - } - async *_streamResponseChunks(_messages, _options, runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - if (this.chunks?.length) { - for (const msgChunk of this.chunks) { - const cg = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: msgChunk.content, - tool_calls: msgChunk.tool_calls, - additional_kwargs: msgChunk.additional_kwargs ?? {} - }), - text: msgChunk.content?.toString() ?? "" - }); - yield cg; - await runManager?.handleLLMNewToken(msgChunk.content, void 0, void 0, void 0, void 0, { chunk: cg }); - } - return; - } - const fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : ""); - const text = typeof fallback.content === "string" ? fallback.content : ""; - for (const ch of text) { - await new Promise((r) => setTimeout(r, this.sleep)); - const cg = new ChatGenerationChunk({ - message: new AIMessageChunk({ content: ch }), - text: ch - }); - yield cg; - await runManager?.handleLLMNewToken(ch, void 0, void 0, void 0, void 0, { chunk: cg }); - } - } -}; -/** -* A fake Chat Model that returns a predefined list of responses. It can be used -* for testing purposes. -* @example -* ```typescript -* const chat = new FakeListChatModel({ -* responses: ["I'll callback later.", "You 'console' them!"] -* }); -* -* const firstMessage = new HumanMessage("You want to hear a JavaScript joke?"); -* const secondMessage = new HumanMessage("How do you cheer up a JavaScript developer?"); -* -* // Call the chat model with a message and log the response -* const firstResponse = await chat.call([firstMessage]); -* console.log({ firstResponse }); -* -* const secondResponse = await chat.call([secondMessage]); -* console.log({ secondResponse }); -* ``` -*/ -var FakeListChatModel = class extends BaseChatModel { - static lc_name() { - return "FakeListChatModel"; - } - lc_serializable = true; - responses; - i = 0; - sleep; - emitCustomEvent = false; - constructor(params) { - super(params); - const { responses, sleep, emitCustomEvent } = params; - this.responses = responses; - this.sleep = sleep; - this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent; - } - _combineLLMOutput() { - return []; - } - _llmType() { - return "fake-list"; - } - async _generate(_messages, options, runManager) { - await this._sleepIfRequested(); - if (options?.thrownErrorString) throw new Error(options.thrownErrorString); - if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); - if (options?.stop?.length) return { generations: [this._formatGeneration(options.stop[0])] }; - else { - const response = this._currentResponse(); - this._incrementResponse(); - return { - generations: [this._formatGeneration(response)], - llmOutput: {} - }; - } - } - _formatGeneration(text) { - return { - message: new AIMessage(text), - text - }; - } - async *_streamResponseChunks(_messages, options, runManager) { - const response = this._currentResponse(); - this._incrementResponse(); - if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); - for await (const text of response) { - await this._sleepIfRequested(); - if (options?.thrownErrorString) throw new Error(options.thrownErrorString); - const chunk = this._createResponseChunk(text); - yield chunk; - runManager?.handleLLMNewToken(text); - } - } - async _sleepIfRequested() { - if (this.sleep !== void 0) await this._sleep(); - } - async _sleep() { - return new Promise((resolve) => { - setTimeout(() => resolve(), this.sleep); - }); - } - _createResponseChunk(text) { - return new ChatGenerationChunk({ - message: new AIMessageChunk({ content: text }), - text - }); - } - _currentResponse() { - return this.responses[this.i]; - } - _incrementResponse() { - if (this.i < this.responses.length - 1) this.i += 1; - else this.i = 0; - } - withStructuredOutput(_params, _config) { - return RunnableLambda.from(async (input) => { - const message = await this.invoke(input); - if (message.tool_calls?.[0]?.args) return message.tool_calls[0].args; - if (typeof message.content === "string") return JSON.parse(message.content); - throw new Error("No structured output found"); - }); - } -}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/embeddings.js - - -//#region src/utils/testing/embeddings.ts -/** -* A class that provides synthetic embeddings by overriding the -* embedDocuments and embedQuery methods to generate embeddings based on -* the input documents. The embeddings are generated by converting each -* document into chunks, calculating a numerical value for each chunk, and -* returning an array of these values as the embedding. -*/ -var SyntheticEmbeddings = class extends Embeddings { - vectorSize; - constructor(params) { - super(params ?? {}); - this.vectorSize = params?.vectorSize ?? 4; - } - /** - * Generates synthetic embeddings for a list of documents. - * @param documents List of documents to generate embeddings for. - * @returns A promise that resolves with a list of synthetic embeddings for each document. - */ - async embedDocuments(documents) { - return Promise.all(documents.map((doc) => this.embedQuery(doc))); - } - /** - * Generates a synthetic embedding for a document. The document is - * converted into chunks, a numerical value is calculated for each chunk, - * and an array of these values is returned as the embedding. - * @param document The document to generate an embedding for. - * @returns A promise that resolves with a synthetic embedding for the document. - */ - async embedQuery(document) { - let doc = document; - doc = doc.toLowerCase().replaceAll(/[^a-z ]/g, ""); - const padMod = doc.length % this.vectorSize; - const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod; - const padSize = doc.length + padGapSize; - doc = doc.padEnd(padSize, " "); - const chunkSize = doc.length / this.vectorSize; - const docChunk = []; - for (let co = 0; co < doc.length; co += chunkSize) docChunk.push(doc.slice(co, co + chunkSize)); - const ret = docChunk.map((s) => { - let sum = 0; - for (let co = 0; co < s.length; co += 1) sum += s === " " ? 0 : s.charCodeAt(co); - const ret$1 = sum % 26 / 26; - return ret$1; - }); - return ret; - } -}; -/** -* A class that provides fake embeddings by overriding the embedDocuments -* and embedQuery methods to return fixed values. -*/ -var FakeEmbeddings = class extends Embeddings { - constructor(params) { - super(params ?? {}); - } - /** - * Generates fixed embeddings for a list of documents. - * @param documents List of documents to generate embeddings for. - * @returns A promise that resolves with a list of fixed embeddings for each document. - */ - embedDocuments(documents) { - return Promise.resolve(documents.map(() => [ - .1, - .2, - .3, - .4 - ])); - } - /** - * Generates a fixed embedding for a query. - * @param _ The query to generate an embedding for. - * @returns A promise that resolves with a fixed embedding for the query. - */ - embedQuery(_) { - return Promise.resolve([ - .1, - .2, - .3, - .4 - ]); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/llms.js - - -//#region src/utils/testing/llms.ts -var FakeLLM = class extends LLM { - response; - thrownErrorString; - constructor(fields) { - super(fields); - this.response = fields.response; - this.thrownErrorString = fields.thrownErrorString; - } - _llmType() { - return "fake"; - } - async _call(prompt, _options, runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const response = this.response ?? prompt; - await runManager?.handleLLMNewToken(response); - return response; - } -}; -var FakeStreamingLLM = class extends LLM { - sleep = 50; - responses; - thrownErrorString; - constructor(fields) { - super(fields); - this.sleep = fields.sleep ?? this.sleep; - this.responses = fields.responses; - this.thrownErrorString = fields.thrownErrorString; - } - _llmType() { - return "fake"; - } - async _call(prompt) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const response = this.responses?.[0]; - this.responses = this.responses?.slice(1); - return response ?? prompt; - } - async *_streamResponseChunks(input, _options, runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const response = this.responses?.[0]; - this.responses = this.responses?.slice(1); - for (const c of response ?? input) { - await new Promise((resolve) => setTimeout(resolve, this.sleep)); - yield { - text: c, - generationInfo: {} - }; - await runManager?.handleLLMNewToken(c); - } - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/message_history.js - - - - - - -//#region src/utils/testing/message_history.ts -var FakeChatMessageHistory = class extends BaseChatMessageHistory { - lc_namespace = [ - "langchain_core", - "message", - "fake" - ]; - messages = []; - constructor() { - super(); - } - async getMessages() { - return this.messages; - } - async addMessage(message) { - this.messages.push(message); - } - async addUserMessage(message) { - this.messages.push(new HumanMessage(message)); - } - async addAIMessage(message) { - this.messages.push(new AIMessage(message)); - } - async clear() { - this.messages = []; - } -}; -var FakeListChatMessageHistory = class extends BaseListChatMessageHistory { - lc_namespace = [ - "langchain_core", - "message", - "fake" - ]; - messages = []; - constructor() { - super(); - } - async addMessage(message) { - this.messages.push(message); - } - async getMessages() { - return this.messages; - } -}; -var FakeTracer = class extends BaseTracer { - name = "fake_tracer"; - runs = []; - constructor() { - super(); - } - persistRun(run) { - this.runs.push(run); - return Promise.resolve(); - } -}; - -//#endregion - -//# sourceMappingURL=message_history.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/output_parsers.js - - -//#region src/utils/testing/output_parsers.ts -/** -* Parser for comma-separated values. It splits the input text by commas -* and trims the resulting values. -*/ -var FakeSplitIntoListParser = class extends BaseOutputParser { - lc_namespace = ["tests", "fake"]; - getFormatInstructions() { - return ""; - } - async parse(text) { - return text.split(",").map((value) => value.trim()); - } -}; - -//#endregion - -//# sourceMappingURL=output_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/retrievers.js - - - -//#region src/utils/testing/retrievers.ts -var FakeRetriever = class extends BaseRetriever { - lc_namespace = ["test", "fake"]; - output = [new Document({ pageContent: "foo" }), new Document({ pageContent: "bar" })]; - constructor(fields) { - super(); - this.output = fields?.output ?? this.output; - } - async _getRelevantDocuments(_query) { - return this.output; - } -}; - -//#endregion - -//# sourceMappingURL=retrievers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/runnables.js - - -//#region src/utils/testing/runnables.ts -var FakeRunnable = class extends Runnable { - lc_namespace = ["tests", "fake"]; - returnOptions; - constructor(fields) { - super(fields); - this.returnOptions = fields.returnOptions; - } - async invoke(input, options) { - if (this.returnOptions) return options ?? {}; - return { input }; - } -}; - -//#endregion - -//# sourceMappingURL=runnables.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/tools.js - - -//#region src/utils/testing/tools.ts -var FakeTool = class extends StructuredTool { - name; - description; - schema; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - async _call(arg, _runManager) { - return JSON.stringify(arg); - } -}; - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/tracers.js - - -//#region src/utils/testing/tracers.ts -var SingleRunExtractor = class extends BaseTracer { - runPromiseResolver; - runPromise; - /** The name of the callback handler. */ - name = "single_run_extractor"; - constructor() { - super(); - this.runPromise = new Promise((extract) => { - this.runPromiseResolver = extract; - }); - } - async persistRun(run) { - this.runPromiseResolver(run); - } - async extract() { - return this.runPromise; - } -}; - -//#endregion - -//# sourceMappingURL=tracers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/vectorstores.js - - - - -//#region src/utils/testing/vectorstores.ts -/** -* Class that extends `VectorStore` to store vectors in memory. Provides -* methods for adding documents, performing similarity searches, and -* creating instances from texts, documents, or an existing index. -*/ -var FakeVectorStore = class FakeVectorStore extends VectorStore { - memoryVectors = []; - similarity; - _vectorstoreType() { - return "memory"; - } - constructor(embeddings, { similarity,...rest } = {}) { - super(embeddings, rest); - this.similarity = similarity ?? cosine; - } - /** - * Method to add documents to the memory vector store. It extracts the - * text from each document, generates embeddings for them, and adds the - * resulting vectors to the store. - * @param documents Array of `Document` instances to be added to the store. - * @returns Promise that resolves when all documents have been added. - */ - async addDocuments(documents) { - const texts = documents.map(({ pageContent }) => pageContent); - return this.addVectors(await this.embeddings.embedDocuments(texts), documents); - } - /** - * Method to add vectors to the memory vector store. It creates - * `MemoryVector` instances for each vector and document pair and adds - * them to the store. - * @param vectors Array of vectors to be added to the store. - * @param documents Array of `Document` instances corresponding to the vectors. - * @returns Promise that resolves when all vectors have been added. - */ - async addVectors(vectors, documents) { - const memoryVectors = vectors.map((embedding, idx) => ({ - content: documents[idx].pageContent, - embedding, - metadata: documents[idx].metadata - })); - this.memoryVectors = this.memoryVectors.concat(memoryVectors); - } - /** - * Method to perform a similarity search in the memory vector store. It - * calculates the similarity between the query vector and each vector in - * the store, sorts the results by similarity, and returns the top `k` - * results along with their scores. - * @param query Query vector to compare against the vectors in the store. - * @param k Number of top results to return. - * @param filter Optional filter function to apply to the vectors before performing the search. - * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score. - */ - async similaritySearchVectorWithScore(query, k, filter) { - const filterFunction = (memoryVector) => { - if (!filter) return true; - const doc = new Document({ - metadata: memoryVector.metadata, - pageContent: memoryVector.content - }); - return filter(doc); - }; - const filteredMemoryVectors = this.memoryVectors.filter(filterFunction); - const searches = filteredMemoryVectors.map((vector, index) => ({ - similarity: this.similarity(query, vector.embedding), - index - })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k); - const result = searches.map((search) => [new Document({ - metadata: filteredMemoryVectors[search.index].metadata, - pageContent: filteredMemoryVectors[search.index].content - }), search.similarity]); - return result; - } - /** - * Static method to create a `FakeVectorStore` instance from an array of - * texts. It creates a `Document` for each text and metadata pair, and - * adds them to the store. - * @param texts Array of texts to be added to the store. - * @param metadatas Array or single object of metadata corresponding to the texts. - * @param embeddings `Embeddings` instance used to generate embeddings for the texts. - * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. - * @returns Promise that resolves with a new `FakeVectorStore` instance. - */ - static async fromTexts(texts, metadatas, embeddings, dbConfig) { - const docs = []; - for (let i = 0; i < texts.length; i += 1) { - const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; - const newDoc = new Document({ - pageContent: texts[i], - metadata - }); - docs.push(newDoc); - } - return FakeVectorStore.fromDocuments(docs, embeddings, dbConfig); - } - /** - * Static method to create a `FakeVectorStore` instance from an array of - * `Document` instances. It adds the documents to the store. - * @param docs Array of `Document` instances to be added to the store. - * @param embeddings `Embeddings` instance used to generate embeddings for the documents. - * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. - * @returns Promise that resolves with a new `FakeVectorStore` instance. - */ - static async fromDocuments(docs, embeddings, dbConfig) { - const instance = new this(embeddings, dbConfig); - await instance.addDocuments(docs); - return instance; - } - /** - * Static method to create a `FakeVectorStore` instance from an existing - * index. It creates a new `FakeVectorStore` instance without adding any - * documents or vectors. - * @param embeddings `Embeddings` instance used to generate embeddings for the documents. - * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. - * @returns Promise that resolves with a new `FakeVectorStore` instance. - */ - static async fromExistingIndex(embeddings, dbConfig) { - const instance = new this(embeddings, dbConfig); - return instance; - } -}; - -//#endregion - -//# sourceMappingURL=vectorstores.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/index.js - - - - - - - - - - - - -//#region src/utils/testing/index.ts -var testing_exports = {}; -__export(testing_exports, { - FakeChatMessageHistory: () => FakeChatMessageHistory, - FakeChatModel: () => FakeChatModel, - FakeEmbeddings: () => FakeEmbeddings, - FakeLLM: () => FakeLLM, - FakeListChatMessageHistory: () => FakeListChatMessageHistory, - FakeListChatModel: () => FakeListChatModel, - FakeRetriever: () => FakeRetriever, - FakeRunnable: () => FakeRunnable, - FakeSplitIntoListParser: () => FakeSplitIntoListParser, - FakeStreamingChatModel: () => FakeStreamingChatModel, - FakeStreamingLLM: () => FakeStreamingLLM, - FakeTool: () => FakeTool, - FakeTracer: () => FakeTracer, - FakeVectorStore: () => FakeVectorStore, - SingleRunExtractor: () => SingleRunExtractor, - SyntheticEmbeddings: () => SyntheticEmbeddings -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/index.js - - - -//#region src/utils/types/index.ts -var types_exports = {}; -__export(types_exports, { - extendInteropZodObject: () => extendInteropZodObject, - getInteropZodDefaultGetter: () => getInteropZodDefaultGetter, - getInteropZodObjectShape: () => getInteropZodObjectShape, - getSchemaDescription: () => getSchemaDescription, - interopParse: () => interopParse, - interopParseAsync: () => interopParseAsync, - interopSafeParse: () => interopSafeParse, - interopSafeParseAsync: () => interopSafeParseAsync, - interopZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional, - interopZodObjectPartial: () => interopZodObjectPartial, - interopZodObjectPassthrough: () => interopZodObjectPassthrough, - interopZodObjectStrict: () => interopZodObjectStrict, - interopZodTransformInputSchema: () => interopZodTransformInputSchema, - isInteropZodLiteral: () => isInteropZodLiteral, - isInteropZodObject: () => isInteropZodObject, - isInteropZodSchema: () => isInteropZodSchema, - isShapelessZodSchema: () => isShapelessZodSchema, - isSimpleStringZodSchema: () => isSimpleStringZodSchema, - isZodArrayV4: () => isZodArrayV4, - isZodLiteralV3: () => isZodLiteralV3, - isZodLiteralV4: () => isZodLiteralV4, - isZodObjectV3: () => isZodObjectV3, - isZodObjectV4: () => isZodObjectV4, - isZodSchema: () => isZodSchema, - isZodSchemaV3: () => isZodSchemaV3, - isZodSchemaV4: () => isZodSchemaV4 -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/import_map.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//#region src/load/import_map.ts -var import_map_exports = {}; -__export(import_map_exports, { - agents: () => agents_exports, - caches: () => caches_base_base_exports, - callbacks__base: () => base_exports, - callbacks__manager: () => manager_exports, - callbacks__promises: () => promises_exports, - chat_history: () => chat_history_exports, - document_loaders__base: () => document_loaders_base_base_exports, - document_loaders__langsmith: () => langsmith_exports, - documents: () => documents_exports, - embeddings: () => embeddings_exports, - example_selectors: () => example_selectors_exports, - index: () => src_exports, - indexing: () => indexing_exports, - language_models__base: () => language_models_base_base_exports, - language_models__chat_models: () => chat_models_exports, - language_models__llms: () => llms_exports, - load__serializable: () => serializable_exports, - memory: () => memory_exports, - messages: () => messages_exports, - messages__tool: () => tool_exports, - output_parsers: () => output_parsers_exports, - output_parsers__openai_functions: () => openai_functions_exports, - output_parsers__openai_tools: () => openai_tools_exports, - outputs: () => outputs_exports, - prompt_values: () => prompt_values_exports, - prompts: () => prompts_exports, - retrievers: () => retrievers_exports, - retrievers__document_compressors: () => document_compressors_base_base_exports, - runnables: () => runnables_exports, - runnables__graph: () => graph_exports, - singletons: () => singletons_exports, - stores: () => stores_exports, - structured_query: () => structured_query_exports, - tools: () => tools_exports, - tracers__base: () => base_base_exports, - tracers__console: () => console_exports, - tracers__log_stream: () => log_stream_exports, - tracers__run_collector: () => run_collector_exports, - tracers__tracer_langchain: () => tracer_langchain_exports, - types__stream: () => stream_stream_exports, - utils__async_caller: () => async_caller_exports, - utils__chunk_array: () => chunk_array_exports, - utils__env: () => env_exports, - utils__event_source_parse: () => event_source_parse_exports, - utils__function_calling: () => function_calling_exports, - utils__hash: () => hash_exports, - utils__json_patch: () => json_patch_exports, - utils__json_schema: () => json_schema_exports, - utils__math: () => math_exports, - utils__stream: () => stream_exports, - utils__testing: () => testing_exports, - utils__tiktoken: () => tiktoken_exports, - utils__types: () => types_exports, - vectorstores: () => vectorstores_exports -}); - -//#endregion - -//# sourceMappingURL=import_map.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/index.js - - - - - - -//#region src/load/index.ts -function combineAliasesAndInvert(constructor) { - const aliases = {}; - for (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases")); - return Object.entries(aliases).reduce((acc, [key, value]) => { - acc[value] = key; - return acc; - }, {}); -} -async function reviver(value) { - const { optionalImportsMap = {}, optionalImportEntrypoints: optionalImportEntrypoints$1 = [], importMap = {}, secretsMap = {}, path = ["$"] } = this; - const pathStr = path.join("."); - if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && value.lc === 1 && value.type === "secret") { - const serialized = value; - const [key] = serialized.id; - if (key in secretsMap) return secretsMap[key]; - else { - const secretValueInEnv = getEnvironmentVariable(key); - if (secretValueInEnv) return secretValueInEnv; - else throw new Error(`Missing key "${key}" for ${pathStr} in load(secretsMap={})`); - } - } else if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && value.lc === 1 && value.type === "not_implemented") { - const serialized = value; - const str = JSON.stringify(serialized); - throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`); - } else if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && "kwargs" in value && value.lc === 1) { - const serialized = value; - const str = JSON.stringify(serialized); - const [name, ...namespaceReverse] = serialized.id.slice().reverse(); - const namespace = namespaceReverse.reverse(); - const importMaps = { - langchain_core: import_map_exports, - langchain: importMap - }; - let module = null; - const optionalImportNamespaceAliases = [namespace.join("/")]; - if (namespace[0] === "langchain_community") optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/")); - const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap); - if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) if (matchingNamespaceAlias !== void 0) module = await optionalImportsMap[matchingNamespaceAlias]; - else throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`); - else { - let finalImportMap; - if (namespace[0] === "langchain" || namespace[0] === "langchain_core") { - finalImportMap = importMaps[namespace[0]]; - namespace.shift(); - } else throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - if (namespace.length === 0) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - let importMapKey; - do { - importMapKey = namespace.join("__"); - if (importMapKey in finalImportMap) break; - else namespace.pop(); - } while (namespace.length > 0); - if (importMapKey in finalImportMap) module = finalImportMap[importMapKey]; - } - if (typeof module !== "object" || module === null) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name); - if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`); - const kwargs = await reviver.call({ - ...this, - path: [...path, "kwargs"] - }, serialized.kwargs); - if (serialized.type === "constructor") { - const instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder))); - Object.defineProperty(instance.constructor, "name", { value: name }); - return instance; - } else throw new Error(`Invalid type: ${pathStr} -> ${str}`); - } else if (typeof value === "object" && value !== null) if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({ - ...this, - path: [...path, `${i}`] - }, v))); - else return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, value$1]) => [key, await reviver.call({ - ...this, - path: [...path, key] - }, value$1)]))); - return value; -} -async function load(text, mappings) { - const json = JSON.parse(text); - return reviver.call({ ...mappings }, json); -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js - - - -//#region src/serde/jsonplus.ts -function isLangChainSerializedObject(value) { - return value !== null && value.lc === 1 && value.type === "constructor" && Array.isArray(value.id); -} -/** -* The replacer in stringify does not allow delegation to built-in LangChain -* serialization methods, and instead immediately calls `.toJSON()` and -* continues to stringify subfields. -* -* We therefore must start from the most nested elements in the input and -* deserialize upwards rather than top-down. -*/ -async function _reviver(value) { - if (value && typeof value === "object") if (Array.isArray(value)) { - const revivedArray = await Promise.all(value.map((item) => _reviver(item))); - return revivedArray; - } else { - const revivedObj = {}; - for (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v); - if (revivedObj.lc === 2 && revivedObj.type === "undefined") return void 0; - else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) try { - const constructorName = revivedObj.id[revivedObj.id.length - 1]; - let constructor; - switch (constructorName) { - case "Set": - constructor = Set; - break; - case "Map": - constructor = Map; - break; - case "RegExp": - constructor = RegExp; - break; - case "Error": - constructor = Error; - break; - default: return revivedObj; - } - if (revivedObj.method) return constructor[revivedObj.method](...revivedObj.args || []); - else return new constructor(...revivedObj.args || []); - } catch (error) { - return revivedObj; - } - else if (isLangChainSerializedObject(revivedObj)) return load(JSON.stringify(revivedObj)); - return revivedObj; - } - return value; -} -function _encodeConstructorArgs(constructor, method, args, kwargs) { - return { - lc: 2, - type: "constructor", - id: [constructor.name], - method: method ?? null, - args: args ?? [], - kwargs: kwargs ?? {} - }; -} -function jsonplus_default(obj) { - if (obj === void 0) return { - lc: 2, - type: "undefined" - }; - else if (obj instanceof Set || obj instanceof Map) return _encodeConstructorArgs(obj.constructor, void 0, [Array.from(obj)]); - else if (obj instanceof RegExp) return _encodeConstructorArgs(RegExp, void 0, [obj.source, obj.flags]); - else if (obj instanceof Error) return _encodeConstructorArgs(obj.constructor, void 0, [obj.message]); - else if (obj?.lg_name === "Send") return { - node: obj.node, - args: obj.args - }; - else return obj; -} -var JsonPlusSerializer = class { - _dumps(obj) { - const encoder = new TextEncoder(); - return encoder.encode(fast_safe_stringify_stringify(obj, (_, value) => { - return jsonplus_default(value); - })); - } - async dumpsTyped(obj) { - if (obj instanceof Uint8Array) return ["bytes", obj]; - else return ["json", this._dumps(obj)]; - } - async _loads(data) { - const parsed = JSON.parse(data); - return _reviver(parsed); - } - async loadsTyped(type, data) { - if (type === "bytes") return typeof data === "string" ? new TextEncoder().encode(data) : data; - else if (type === "json") return this._loads(typeof data === "string" ? data : new TextDecoder().decode(data)); - else throw new Error(`Unknown serialization type: ${type}`); - } -}; - -//#endregion - -//# sourceMappingURL=jsonplus.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/base.js - - - - -//#region src/base.ts -function deepCopy(obj) { - if (typeof obj !== "object" || obj === null) return obj; - const newObj = Array.isArray(obj) ? [] : {}; - for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]); - return newObj; -} -/** @hidden */ -function emptyCheckpoint() { - return { - v: 4, - id: uuid6(-2), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: {}, - channel_versions: {}, - versions_seen: {} - }; -} -/** @hidden */ -function copyCheckpoint(checkpoint) { - return { - v: checkpoint.v, - id: checkpoint.id, - ts: checkpoint.ts, - channel_values: { ...checkpoint.channel_values }, - channel_versions: { ...checkpoint.channel_versions }, - versions_seen: deepCopy(checkpoint.versions_seen) - }; -} -var BaseCheckpointSaver = class { - serde = new JsonPlusSerializer(); - constructor(serde) { - this.serde = serde || this.serde; - } - async get(config) { - const value = await this.getTuple(config); - return value ? value.checkpoint : void 0; - } - /** - * Generate the next version ID for a channel. - * - * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions, - * as long as they are monotonically increasing. - */ - getNextVersion(current) { - if (typeof current === "string") throw new Error("Please override this method to use string versions."); - return current !== void 0 && typeof current === "number" ? current + 1 : 1; - } -}; -function compareChannelVersions(a, b) { - if (typeof a === "number" && typeof b === "number") return Math.sign(a - b); - return String(a).localeCompare(String(b)); -} -function maxChannelVersion(...versions) { - return versions.reduce((max, version, idx) => { - if (idx === 0) return version; - return compareChannelVersions(max, version) >= 0 ? max : version; - }); -} -/** -* Mapping from error type to error index. -* Regular writes just map to their index in the list of writes being saved. -* Special writes (e.g. errors) map to negative indices, to avoid those writes from -* conflicting with regular writes. -* Each Checkpointer implementation should use this mapping in put_writes. -*/ -const WRITES_IDX_MAP = { - [types_ERROR]: -1, - [SCHEDULED]: -2, - [INTERRUPT]: -3, - [RESUME]: -4 -}; -function getCheckpointId(config) { - return config.configurable?.checkpoint_id || config.configurable?.thread_ts || ""; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/memory.js - - - -//#region src/memory.ts -function _generateKey(threadId, checkpointNamespace, checkpointId) { - return JSON.stringify([ - threadId, - checkpointNamespace, - checkpointId - ]); -} -function _parseKey(key) { - const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key); - return { - threadId, - checkpointNamespace, - checkpointId - }; -} -var MemorySaver = class extends BaseCheckpointSaver { - storage = {}; - writes = {}; - constructor(serde) { - super(serde); - } - /** @internal */ - async _migratePendingSends(mutableCheckpoint, threadId, checkpointNs, parentCheckpointId) { - const deseriablizableCheckpoint = mutableCheckpoint; - const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId); - const pendingSends = await Promise.all(Object.values(this.writes[parentKey] ?? {}).filter(([_taskId, channel]) => channel === TASKS).map(async ([_taskId, _channel, writes]) => await this.serde.loadsTyped("json", writes))); - deseriablizableCheckpoint.channel_values ??= {}; - deseriablizableCheckpoint.channel_values[TASKS] = pendingSends; - deseriablizableCheckpoint.channel_versions ??= {}; - deseriablizableCheckpoint.channel_versions[TASKS] = Object.keys(deseriablizableCheckpoint.channel_versions).length > 0 ? maxChannelVersion(...Object.values(deseriablizableCheckpoint.channel_versions)) : this.getNextVersion(void 0); - } - async getTuple(config) { - const thread_id = config.configurable?.thread_id; - const checkpoint_ns = config.configurable?.checkpoint_ns ?? ""; - let checkpoint_id = getCheckpointId(config); - if (checkpoint_id) { - const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id]; - if (saved !== void 0) { - const [checkpoint, metadata, parentCheckpointId] = saved; - const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); - const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const checkpointTuple = { - config, - checkpoint: deserializedCheckpoint, - metadata: await this.serde.loadsTyped("json", metadata), - pendingWrites - }; - if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { - thread_id, - checkpoint_ns, - checkpoint_id: parentCheckpointId - } }; - return checkpointTuple; - } - } else { - const checkpoints = this.storage[thread_id]?.[checkpoint_ns]; - if (checkpoints !== void 0) { - checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0]; - const saved = checkpoints[checkpoint_id]; - const [checkpoint, metadata, parentCheckpointId] = saved; - const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); - const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const checkpointTuple = { - config: { configurable: { - thread_id, - checkpoint_id, - checkpoint_ns - } }, - checkpoint: deserializedCheckpoint, - metadata: await this.serde.loadsTyped("json", metadata), - pendingWrites - }; - if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { - thread_id, - checkpoint_ns, - checkpoint_id: parentCheckpointId - } }; - return checkpointTuple; - } - } - return void 0; - } - async *list(config, options) { - let { before, limit, filter } = options ?? {}; - const threadIds = config.configurable?.thread_id ? [config.configurable?.thread_id] : Object.keys(this.storage); - const configCheckpointNamespace = config.configurable?.checkpoint_ns; - const configCheckpointId = config.configurable?.checkpoint_id; - for (const threadId of threadIds) for (const checkpointNamespace of Object.keys(this.storage[threadId] ?? {})) { - if (configCheckpointNamespace !== void 0 && checkpointNamespace !== configCheckpointNamespace) continue; - const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {}; - const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) => b[0].localeCompare(a[0])); - for (const [checkpointId, [checkpoint, metadataStr, parentCheckpointId]] of sortedCheckpoints) { - if (configCheckpointId && checkpointId !== configCheckpointId) continue; - if (before && before.configurable?.checkpoint_id && checkpointId >= before.configurable.checkpoint_id) continue; - const metadata = await this.serde.loadsTyped("json", metadataStr); - if (filter && !Object.entries(filter).every(([key$1, value]) => metadata[key$1] === value)) continue; - if (limit !== void 0) { - if (limit <= 0) break; - limit -= 1; - } - const key = _generateKey(threadId, checkpointNamespace, checkpointId); - const writes = Object.values(this.writes[key] || {}); - const pendingWrites = await Promise.all(writes.map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, threadId, checkpointNamespace, parentCheckpointId); - const checkpointTuple = { - config: { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: checkpointId - } }, - checkpoint: deserializedCheckpoint, - metadata, - pendingWrites - }; - if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: parentCheckpointId - } }; - yield checkpointTuple; - } - } - } - async put(config, checkpoint, metadata) { - const preparedCheckpoint = copyCheckpoint(checkpoint); - const threadId = config.configurable?.thread_id; - const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; - if (threadId === void 0) throw new Error(`Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property.`); - if (!this.storage[threadId]) this.storage[threadId] = {}; - if (!this.storage[threadId][checkpointNamespace]) this.storage[threadId][checkpointNamespace] = {}; - const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([this.serde.dumpsTyped(preparedCheckpoint), this.serde.dumpsTyped(metadata)]); - this.storage[threadId][checkpointNamespace][checkpoint.id] = [ - serializedCheckpoint, - serializedMetadata, - config.configurable?.checkpoint_id - ]; - return { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: checkpoint.id - } }; - } - async putWrites(config, writes, taskId) { - const threadId = config.configurable?.thread_id; - const checkpointNamespace = config.configurable?.checkpoint_ns; - const checkpointId = config.configurable?.checkpoint_id; - if (threadId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property`); - if (checkpointId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.`); - const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId); - const outerWrites_ = this.writes[outerKey]; - if (this.writes[outerKey] === void 0) this.writes[outerKey] = {}; - await Promise.all(writes.map(async ([channel, value], idx) => { - const [, serializedValue] = await this.serde.dumpsTyped(value); - const innerKey = [taskId, WRITES_IDX_MAP[channel] || idx]; - const innerKeyStr = `${innerKey[0]},${innerKey[1]}`; - if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) return; - this.writes[outerKey][innerKeyStr] = [ - taskId, - channel, - serializedValue - ]; - })); - } - async deleteThread(threadId) { - delete this.storage[threadId]; - for (const key of Object.keys(this.writes)) if (_parseKey(key).threadId === threadId) delete this.writes[key]; - } -}; - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/base.js -//#region src/store/base.ts -/** -* Error thrown when an invalid namespace is provided. -*/ -var InvalidNamespaceError = class extends Error { - constructor(message) { - super(message); - this.name = "InvalidNamespaceError"; - } -}; -/** -* Validates the provided namespace. -* @param namespace The namespace to validate. -* @throws {InvalidNamespaceError} If the namespace is invalid. -*/ -function validateNamespace(namespace) { - if (namespace.length === 0) throw new InvalidNamespaceError("Namespace cannot be empty."); - for (const label of namespace) { - if (typeof label !== "string") throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`); - if (label.includes(".")) throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`); - if (label === "") throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`); - } - if (namespace[0] === "langgraph") throw new InvalidNamespaceError(`Root label for namespace cannot be "langgraph". Got: ${namespace}`); -} -/** -* Utility function to get text at a specific JSON path -*/ -function getTextAtPath(obj, path) { - const parts = path.split("."); - let current = obj; - for (const part of parts) { - if (part.includes("[")) { - const [arrayName, indexStr] = part.split("["); - const index = indexStr.replace("]", ""); - if (!current[arrayName]) return []; - if (index === "*") { - const results = []; - for (const item of current[arrayName]) if (typeof item === "string") results.push(item); - return results; - } - const idx = parseInt(index, 10); - if (Number.isNaN(idx)) return []; - current = current[arrayName][idx]; - } else current = current[part]; - if (current === void 0) return []; - } - return typeof current === "string" ? [current] : []; -} -/** -* Tokenizes a JSON path into parts -*/ -function tokenizePath(path) { - return path.split("."); -} -/** -* Abstract base class for persistent key-value stores. -* -* Stores enable persistence and memory that can be shared across threads, -* scoped to user IDs, assistant IDs, or other arbitrary namespaces. -* -* Features: -* - Hierarchical namespaces for organization -* - Key-value storage with metadata -* - Vector similarity search (if configured) -* - Filtering and pagination -*/ -var base_BaseStore = class { - /** - * Retrieve a single item by its namespace and key. - * - * @param namespace Hierarchical path for the item - * @param key Unique identifier within the namespace - * @returns Promise resolving to the item or null if not found - */ - async get(namespace, key) { - return (await this.batch([{ - namespace, - key - }]))[0]; - } - /** - * Search for items within a namespace prefix. - * Supports both metadata filtering and vector similarity search. - * - * @param namespacePrefix Hierarchical path prefix to search within - * @param options Search options for filtering and pagination - * @returns Promise resolving to list of matching items with relevance scores - * - * @example - * // Search with filters - * await store.search(["documents"], { - * filter: { type: "report", status: "active" }, - * limit: 5, - * offset: 10 - * }); - * - * // Vector similarity search - * await store.search(["users", "content"], { - * query: "technical documentation about APIs", - * limit: 20 - * }); - */ - async search(namespacePrefix, options = {}) { - const { filter, limit = 10, offset = 0, query } = options; - return (await this.batch([{ - namespacePrefix, - filter, - limit, - offset, - query - }]))[0]; - } - /** - * Store or update an item. - * - * @param namespace Hierarchical path for the item - * @param key Unique identifier within the namespace - * @param value Object containing the item's data - * @param index Optional indexing configuration - * - * @example - * // Simple storage - * await store.put(["docs"], "report", { title: "Annual Report" }); - * - * // With specific field indexing - * await store.put( - * ["docs"], - * "report", - * { - * title: "Q4 Report", - * chapters: [{ content: "..." }, { content: "..." }] - * }, - * ["title", "chapters[*].content"] - * ); - */ - async put(namespace, key, value, index) { - validateNamespace(namespace); - await this.batch([{ - namespace, - key, - value, - index - }]); - } - /** - * Delete an item from the store. - * - * @param namespace Hierarchical path for the item - * @param key Unique identifier within the namespace - */ - async delete(namespace, key) { - await this.batch([{ - namespace, - key, - value: null - }]); - } - /** - * List and filter namespaces in the store. - * Used to explore data organization and navigate the namespace hierarchy. - * - * @param options Options for listing namespaces - * @returns Promise resolving to list of namespace paths - * - * @example - * // List all namespaces under "documents" - * await store.listNamespaces({ - * prefix: ["documents"], - * maxDepth: 2 - * }); - * - * // List namespaces ending with "v1" - * await store.listNamespaces({ - * suffix: ["v1"], - * limit: 50 - * }); - */ - async listNamespaces(options = {}) { - const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options; - const matchConditions = []; - if (prefix) matchConditions.push({ - matchType: "prefix", - path: prefix - }); - if (suffix) matchConditions.push({ - matchType: "suffix", - path: suffix - }); - return (await this.batch([{ - matchConditions: matchConditions.length ? matchConditions : void 0, - maxDepth, - limit, - offset - }]))[0]; - } - /** - * Start the store. Override if initialization is needed. - */ - start() {} - /** - * Stop the store. Override if cleanup is needed. - */ - stop() {} -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js - - -//#region src/store/batch.ts -/** -* Extracts and returns the underlying store from an `AsyncBatchedStore`, -* or returns the input if it is not an `AsyncBatchedStore`. -*/ -const extractStore = (input) => { - if ("lg_name" in input && input.lg_name === "AsyncBatchedStore") return input.store; - return input; -}; -var AsyncBatchedStore = class extends base_BaseStore { - lg_name = "AsyncBatchedStore"; - store; - queue = /* @__PURE__ */ new Map(); - nextKey = 0; - running = false; - processingTask = null; - constructor(store) { - super(); - this.store = extractStore(store); - } - get isRunning() { - return this.running; - } - /** - * @ignore - * Batch is not implemented here as we're only extending `BaseStore` - * to allow it to be passed where `BaseStore` is expected, and implement - * the convenience methods (get, search, put, delete). - */ - async batch(_operations) { - throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong."); - } - async get(namespace, key) { - return this.enqueueOperation({ - namespace, - key - }); - } - async search(namespacePrefix, options) { - const { filter, limit = 10, offset = 0, query } = options || {}; - return this.enqueueOperation({ - namespacePrefix, - filter, - limit, - offset, - query - }); - } - async put(namespace, key, value) { - return this.enqueueOperation({ - namespace, - key, - value - }); - } - async delete(namespace, key) { - return this.enqueueOperation({ - namespace, - key, - value: null - }); - } - start() { - if (!this.running) { - this.running = true; - this.processingTask = this.processBatchQueue(); - } - } - async stop() { - this.running = false; - if (this.processingTask) await this.processingTask; - } - enqueueOperation(operation) { - return new Promise((resolve, reject) => { - const key = this.nextKey; - this.nextKey += 1; - this.queue.set(key, { - operation, - resolve, - reject - }); - }); - } - async processBatchQueue() { - while (this.running) { - await new Promise((resolve) => { - setTimeout(resolve, 0); - }); - if (this.queue.size === 0) continue; - const batch = new Map(this.queue); - this.queue.clear(); - try { - const operations = Array.from(batch.values()).map(({ operation }) => operation); - const results = await this.store.batch(operations); - batch.forEach(({ resolve }, key) => { - const index = Array.from(batch.keys()).indexOf(key); - resolve(results[index]); - }); - } catch (e) { - batch.forEach(({ reject }) => { - reject(e); - }); - } - } - } - toJSON() { - return { - queue: this.queue, - nextKey: this.nextKey, - running: this.running, - store: "[LangGraphStore]" - }; - } -}; - -//#endregion - -//# sourceMappingURL=batch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/utils.js -//#region src/store/utils.ts -/** -* Tokenize a JSON path into parts. -* @example -* tokenizePath("metadata.title") // -> ["metadata", "title"] -* tokenizePath("chapters[*].content") // -> ["chapters[*]", "content"] -*/ -function utils_tokenizePath(path) { - if (!path) return []; - const tokens = []; - let current = []; - let i = 0; - while (i < path.length) { - const char = path[i]; - if (char === "[") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - let bracketCount = 1; - const indexChars = ["["]; - i += 1; - while (i < path.length && bracketCount > 0) { - if (path[i] === "[") bracketCount += 1; - else if (path[i] === "]") bracketCount -= 1; - indexChars.push(path[i]); - i += 1; - } - tokens.push(indexChars.join("")); - continue; - } else if (char === "{") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - let braceCount = 1; - const fieldChars = ["{"]; - i += 1; - while (i < path.length && braceCount > 0) { - if (path[i] === "{") braceCount += 1; - else if (path[i] === "}") braceCount -= 1; - fieldChars.push(path[i]); - i += 1; - } - tokens.push(fieldChars.join("")); - continue; - } else if (char === ".") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - } else current.push(char); - i += 1; - } - if (current.length) tokens.push(current.join("")); - return tokens; -} -/** -* Type guard to check if an object is a FilterOperators -*/ -function isFilterOperators(obj) { - return typeof obj === "object" && obj !== null && Object.keys(obj).every((key) => key === "$eq" || key === "$ne" || key === "$gt" || key === "$gte" || key === "$lt" || key === "$lte" || key === "$in" || key === "$nin"); -} -/** -* Compare values for filtering, supporting operator-based comparisons. -*/ -function compareValues(itemValue, filterValue) { - if (isFilterOperators(filterValue)) { - const operators = Object.keys(filterValue).filter((k) => k.startsWith("$")); - return operators.every((op) => { - const value = filterValue[op]; - switch (op) { - case "$eq": return itemValue === value; - case "$ne": return itemValue !== value; - case "$gt": return Number(itemValue) > Number(value); - case "$gte": return Number(itemValue) >= Number(value); - case "$lt": return Number(itemValue) < Number(value); - case "$lte": return Number(itemValue) <= Number(value); - case "$in": return Array.isArray(value) ? value.includes(itemValue) : false; - case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true; - default: return false; - } - }); - } - return itemValue === filterValue; -} -/** -* Extract text from a value at a specific JSON path. -* -* Supports: -* - Simple paths: "field1.field2" -* - Array indexing: "[0]", "[*]", "[-1]" -* - Wildcards: "*" -* - Multi-field selection: "{field1,field2}" -* - Nested paths in multi-field: "{field1,nested.field2}" -*/ -function utils_getTextAtPath(obj, path) { - if (!path || path === "$") return [JSON.stringify(obj, null, 2)]; - const tokens = Array.isArray(path) ? path : utils_tokenizePath(path); - function extractFromObj(obj$1, tokens$1, pos) { - if (pos >= tokens$1.length) { - if (typeof obj$1 === "string" || typeof obj$1 === "number" || typeof obj$1 === "boolean") return [String(obj$1)]; - if (obj$1 === null || obj$1 === void 0) return []; - if (Array.isArray(obj$1) || typeof obj$1 === "object") return [JSON.stringify(obj$1, null, 2)]; - return []; - } - const token = tokens$1[pos]; - const results = []; - if (pos === 0 && token === "$") results.push(JSON.stringify(obj$1, null, 2)); - if (token.startsWith("[") && token.endsWith("]")) { - if (!Array.isArray(obj$1)) return []; - const index = token.slice(1, -1); - if (index === "*") for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1)); - else try { - let idx = parseInt(index, 10); - if (idx < 0) idx = obj$1.length + idx; - if (idx >= 0 && idx < obj$1.length) results.push(...extractFromObj(obj$1[idx], tokens$1, pos + 1)); - } catch { - return []; - } - } else if (token.startsWith("{") && token.endsWith("}")) { - if (typeof obj$1 !== "object" || obj$1 === null) return []; - const fields = token.slice(1, -1).split(",").map((f) => f.trim()); - for (const field of fields) { - const nestedTokens = utils_tokenizePath(field); - if (nestedTokens.length) { - let currentObj = obj$1; - for (const nestedToken of nestedTokens) if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) currentObj = currentObj[nestedToken]; - else { - currentObj = void 0; - break; - } - if (currentObj !== void 0) { - if (typeof currentObj === "string" || typeof currentObj === "number" || typeof currentObj === "boolean") results.push(String(currentObj)); - else if (Array.isArray(currentObj) || typeof currentObj === "object") results.push(JSON.stringify(currentObj, null, 2)); - } - } - } - } else if (token === "*") { - if (Array.isArray(obj$1)) for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1)); - else if (typeof obj$1 === "object" && obj$1 !== null) for (const value of Object.values(obj$1)) results.push(...extractFromObj(value, tokens$1, pos + 1)); - } else if (typeof obj$1 === "object" && obj$1 !== null && token in obj$1) results.push(...extractFromObj(obj$1[token], tokens$1, pos + 1)); - return results; - } - return extractFromObj(obj, tokens, 0); -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/memory.js - - - -//#region src/store/memory.ts -/** -* In-memory key-value store with optional vector search. -* -* A lightweight store implementation using JavaScript Maps. Supports basic -* key-value operations and vector search when configured with embeddings. -* -* @example -* ```typescript -* // Basic key-value storage -* const store = new InMemoryStore(); -* await store.put(["users", "123"], "prefs", { theme: "dark" }); -* const item = await store.get(["users", "123"], "prefs"); -* -* // Vector search with embeddings -* import { OpenAIEmbeddings } from "@langchain/openai"; -* const store = new InMemoryStore({ -* index: { -* dims: 1536, -* embeddings: new OpenAIEmbeddings({ modelName: "text-embedding-3-small" }), -* } -* }); -* -* // Store documents -* await store.put(["docs"], "doc1", { text: "Python tutorial" }); -* await store.put(["docs"], "doc2", { text: "TypeScript guide" }); -* -* // Search by similarity -* const results = await store.search(["docs"], { query: "python programming" }); -* ``` -* -* **Warning**: This store keeps all data in memory. Data is lost when the process exits. -* For persistence, use a database-backed store. -*/ -var memory_InMemoryStore = class extends base_BaseStore { - data = /* @__PURE__ */ new Map(); - vectors = /* @__PURE__ */ new Map(); - _indexConfig; - constructor(options) { - super(); - if (options?.index) this._indexConfig = { - ...options.index, - __tokenizedFields: (options.index.fields ?? ["$"]).map((p) => [p, p === "$" ? [p] : utils_tokenizePath(p)]) - }; - } - async batch(operations) { - const results = []; - const putOps = /* @__PURE__ */ new Map(); - const searchOps = /* @__PURE__ */ new Map(); - for (let i = 0; i < operations.length; i += 1) { - const op = operations[i]; - if ("key" in op && "namespace" in op && !("value" in op)) results.push(this.getOperation(op)); - else if ("namespacePrefix" in op) { - const candidates = this.filterItems(op); - searchOps.set(i, [op, candidates]); - results.push(null); - } else if ("value" in op) { - const key = `${op.namespace.join(":")}:${op.key}`; - putOps.set(key, op); - results.push(null); - } else if ("matchConditions" in op) results.push(this.listNamespacesOperation(op)); - } - if (searchOps.size > 0) if (this._indexConfig?.embeddings) { - const queries = /* @__PURE__ */ new Set(); - for (const [op] of searchOps.values()) if (op.query) queries.add(op.query); - const queryEmbeddings = queries.size > 0 ? await Promise.all(Array.from(queries).map((q) => this._indexConfig.embeddings.embedQuery(q))) : []; - const queryVectors = Object.fromEntries(Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])); - for (const [i, [op, candidates]] of searchOps.entries()) if (op.query && queryVectors[op.query]) { - const queryVector = queryVectors[op.query]; - const scoredResults = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10); - results[i] = scoredResults; - } else results[i] = this.paginateResults(candidates.map((item) => ({ - ...item, - score: void 0 - })), op.offset ?? 0, op.limit ?? 10); - } else for (const [i, [op, candidates]] of searchOps.entries()) results[i] = this.paginateResults(candidates.map((item) => ({ - ...item, - score: void 0 - })), op.offset ?? 0, op.limit ?? 10); - if (putOps.size > 0 && this._indexConfig?.embeddings) { - const toEmbed = this.extractTexts(Array.from(putOps.values())); - if (Object.keys(toEmbed).length > 0) { - const embeddings = await this._indexConfig.embeddings.embedDocuments(Object.keys(toEmbed)); - this.insertVectors(toEmbed, embeddings); - } - } - for (const op of putOps.values()) this.putOperation(op); - return results; - } - getOperation(op) { - const namespaceKey = op.namespace.join(":"); - const item = this.data.get(namespaceKey)?.get(op.key); - return item ?? null; - } - putOperation(op) { - const namespaceKey = op.namespace.join(":"); - if (!this.data.has(namespaceKey)) this.data.set(namespaceKey, /* @__PURE__ */ new Map()); - const namespaceMap = this.data.get(namespaceKey); - if (op.value === null) namespaceMap.delete(op.key); - else { - const now = /* @__PURE__ */ new Date(); - if (namespaceMap.has(op.key)) { - const item = namespaceMap.get(op.key); - item.value = op.value; - item.updatedAt = now; - } else namespaceMap.set(op.key, { - value: op.value, - key: op.key, - namespace: op.namespace, - createdAt: now, - updatedAt: now - }); - } - } - listNamespacesOperation(op) { - const allNamespaces = Array.from(this.data.keys()).map((ns) => ns.split(":")); - let namespaces = allNamespaces; - if (op.matchConditions && op.matchConditions.length > 0) namespaces = namespaces.filter((ns) => op.matchConditions.every((condition) => this.doesMatch(condition, ns))); - if (op.maxDepth !== void 0) namespaces = Array.from(new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(":")))).map((ns) => ns.split(":")); - namespaces.sort((a, b) => a.join(":").localeCompare(b.join(":"))); - return namespaces.slice(op.offset ?? 0, (op.offset ?? 0) + (op.limit ?? namespaces.length)); - } - doesMatch(matchCondition, key) { - const { matchType, path } = matchCondition; - if (matchType === "prefix") { - if (path.length > key.length) return false; - return path.every((pElem, index) => { - const kElem = key[index]; - return pElem === "*" || kElem === pElem; - }); - } else if (matchType === "suffix") { - if (path.length > key.length) return false; - return path.every((pElem, index) => { - const kElem = key[key.length - path.length + index]; - return pElem === "*" || kElem === pElem; - }); - } - throw new Error(`Unsupported match type: ${matchType}`); - } - filterItems(op) { - const candidates = []; - for (const [namespace, items] of this.data.entries()) if (namespace.startsWith(op.namespacePrefix.join(":"))) candidates.push(...items.values()); - let filteredCandidates = candidates; - if (op.filter) filteredCandidates = candidates.filter((item) => Object.entries(op.filter).every(([key, value]) => compareValues(item.value[key], value))); - return filteredCandidates; - } - scoreResults(candidates, queryVector, offset = 0, limit = 10) { - const flatItems = []; - const flatVectors = []; - const scoreless = []; - for (const item of candidates) { - const vectors = this.getVectors(item); - if (vectors.length) for (const vector of vectors) { - flatItems.push(item); - flatVectors.push(vector); - } - else scoreless.push(item); - } - const scores = this.cosineSimilarity(queryVector, flatVectors); - const sortedResults = scores.map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]); - const seen = /* @__PURE__ */ new Set(); - const kept = []; - for (const [score, item] of sortedResults) { - const key = `${item.namespace.join(":")}:${item.key}`; - if (seen.has(key)) continue; - const ix = seen.size; - if (ix >= offset + limit) break; - if (ix < offset) { - seen.add(key); - continue; - } - seen.add(key); - kept.push([score, item]); - } - if (scoreless.length && kept.length < limit) for (const item of scoreless.slice(0, limit - kept.length)) { - const key = `${item.namespace.join(":")}:${item.key}`; - if (!seen.has(key)) { - seen.add(key); - kept.push([void 0, item]); - } - } - return kept.map(([score, item]) => ({ - ...item, - score - })); - } - paginateResults(results, offset, limit) { - return results.slice(offset, offset + limit); - } - extractTexts(ops) { - if (!ops.length || !this._indexConfig) return {}; - const toEmbed = {}; - for (const op of ops) if (op.value !== null && op.index !== false) { - const paths = op.index === null || op.index === void 0 ? this._indexConfig.__tokenizedFields ?? [] : op.index.map((ix) => [ix, utils_tokenizePath(ix)]); - for (const [path, field] of paths) { - const texts = utils_getTextAtPath(op.value, field); - if (texts.length) if (texts.length > 1) texts.forEach((text, i) => { - if (!toEmbed[text]) toEmbed[text] = []; - toEmbed[text].push([ - op.namespace, - op.key, - `${path}.${i}` - ]); - }); - else { - if (!toEmbed[texts[0]]) toEmbed[texts[0]] = []; - toEmbed[texts[0]].push([ - op.namespace, - op.key, - path - ]); - } - } - } - return toEmbed; - } - insertVectors(texts, embeddings) { - for (const [text, metadata] of Object.entries(texts)) { - const embedding = embeddings.shift(); - if (!embedding) throw new Error(`No embedding found for text: ${text}`); - for (const [namespace, key, field] of metadata) { - const namespaceKey = namespace.join(":"); - if (!this.vectors.has(namespaceKey)) this.vectors.set(namespaceKey, /* @__PURE__ */ new Map()); - const namespaceMap = this.vectors.get(namespaceKey); - if (!namespaceMap.has(key)) namespaceMap.set(key, /* @__PURE__ */ new Map()); - const itemMap = namespaceMap.get(key); - itemMap.set(field, embedding); - } - } - } - getVectors(item) { - const namespaceKey = item.namespace.join(":"); - const itemKey = item.key; - if (!this.vectors.has(namespaceKey)) return []; - const namespaceMap = this.vectors.get(namespaceKey); - if (!namespaceMap.has(itemKey)) return []; - const itemMap = namespaceMap.get(itemKey); - const vectors = Array.from(itemMap.values()); - if (!vectors.length) return []; - return vectors; - } - cosineSimilarity(X, Y) { - if (!Y.length) return []; - const dotProducts = Y.map((vector) => vector.reduce((acc, val, i) => acc + val * X[i], 0)); - const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0)); - const magnitudes2 = Y.map((vector) => Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))); - return dotProducts.map((dot, i) => { - const magnitude2 = magnitudes2[i]; - return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0; - }); - } - get indexConfig() { - return this._indexConfig; - } -}; -/** @deprecated Alias for InMemoryStore */ -var MemoryStore = class extends (/* unused pure expression or super */ null && (memory_InMemoryStore)) {}; - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js - - -//#region src/cache/base.ts -var cache_base_BaseCache = class { - serde = new JsonPlusSerializer(); - /** - * Initialize the cache with a serializer. - * - * @param serde - The serializer to use. - */ - constructor(serde) { - this.serde = serde || this.serde; - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/memory.js - - -//#region src/cache/memory.ts -var memory_InMemoryCache = class extends (/* unused pure expression or super */ null && (BaseCache)) { - cache = {}; - async get(keys) { - if (!keys.length) return []; - const now = Date.now(); - return (await Promise.all(keys.map(async (fullKey) => { - const [namespace, key] = fullKey; - const strNamespace = namespace.join(","); - if (strNamespace in this.cache && key in this.cache[strNamespace]) { - const cached = this.cache[strNamespace][key]; - if (cached.exp == null || now < cached.exp) { - const value = await this.serde.loadsTyped(cached.enc, cached.val); - return [{ - key: fullKey, - value - }]; - } else delete this.cache[strNamespace][key]; - } - return []; - }))).flat(); - } - async set(pairs) { - const now = Date.now(); - for (const { key: fullKey, value, ttl } of pairs) { - const [namespace, key] = fullKey; - const strNamespace = namespace.join(","); - const [enc, val] = await this.serde.dumpsTyped(value); - const exp = ttl != null ? ttl * 1e3 + now : null; - this.cache[strNamespace] ??= {}; - this.cache[strNamespace][key] = { - enc, - val, - exp - }; - } - } - async clear(namespaces) { - if (!namespaces.length) { - this.cache = {}; - return; - } - for (const namespace of namespaces) { - const strNamespace = namespace.join(","); - if (strNamespace in this.cache) delete this.cache[strNamespace]; - } - } -}; - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/index.js - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/index.js - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/base.js - - - -//#region src/channels/base.ts -function isBaseChannel(obj) { - return obj != null && obj.lg_is_channel === true; -} -/** @internal */ -var BaseChannel = class { - ValueType; - UpdateType; - /** @ignore */ - lg_is_channel = true; - /** - * Mark the current value of the channel as consumed. By default, no-op. - * A channel can use this method to modify its state, preventing the value - * from being consumed again. - * - * Returns True if the channel was updated, False otherwise. - */ - consume() { - return false; - } - /** - * Notify the channel that the Pregel run is finishing. By default, no-op. - * A channel can use this method to modify its state, preventing finish. - * - * Returns True if the channel was updated, False otherwise. - */ - finish() { - return false; - } - /** - * Return True if the channel is available (not empty), False otherwise. - * Subclasses should override this method to provide a more efficient - * implementation than calling get() and catching EmptyChannelError. - */ - isAvailable() { - try { - this.get(); - return true; - } catch (error) { - if (error.name === EmptyChannelError.unminifiable_name) return false; - throw error; - } - } -}; -const IS_ONLY_BASE_CHANNEL = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); -function getOnlyChannels(channels) { - if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels; - const newChannels = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; - const value = channels[k]; - if (isBaseChannel(value)) newChannels[k] = value; - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); - return newChannels; -} -function emptyChannels(channels, checkpoint) { - const filteredChannels = getOnlyChannels(channels); - const newChannels = {}; - for (const k in filteredChannels) { - if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue; - const channelValue = checkpoint.channel_values[k]; - newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); - return newChannels; -} -function createCheckpoint(checkpoint, channels, step, options) { - let values; - if (channels === void 0) values = checkpoint.channel_values; - else { - values = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; - try { - values[k] = channels[k].checkpoint(); - } catch (error) { - if (error.name === EmptyChannelError.unminifiable_name) {} else throw error; - } - } - } - return { - v: 4, - id: options?.id ?? uuid6(step), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: values, - channel_versions: checkpoint.channel_versions, - versions_seen: checkpoint.versions_seen - }; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/binop.js - - - -//#region src/channels/binop.ts -/** -* Stores the result of applying a binary operator to the current value and each new value. -*/ -var BinaryOperatorAggregate = class BinaryOperatorAggregate extends BaseChannel { - lc_graph_name = "BinaryOperatorAggregate"; - value; - operator; - initialValueFactory; - constructor(operator, initialValueFactory) { - super(); - this.operator = operator; - this.initialValueFactory = initialValueFactory; - this.value = initialValueFactory?.(); - } - fromCheckpoint(checkpoint) { - const empty = new BinaryOperatorAggregate(this.operator, this.initialValueFactory); - if (typeof checkpoint !== "undefined") empty.value = checkpoint; - return empty; - } - update(values) { - let newValues = values; - if (!newValues.length) return false; - if (this.value === void 0) { - [this.value] = newValues; - newValues = newValues.slice(1); - } - for (const value of newValues) if (this.value !== void 0) this.value = this.operator(this.value, value); - return true; - } - get() { - if (this.value === void 0) throw new EmptyChannelError(); - return this.value; - } - checkpoint() { - if (this.value === void 0) throw new EmptyChannelError(); - return this.value; - } - isAvailable() { - return this.value !== void 0; - } -}; - -//#endregion - -//# sourceMappingURL=binop.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/last_value.js - - - -//#region src/channels/last_value.ts -/** -* Stores the last value received, can receive at most one value per step. -* -* Since `update` is only called once per step and value can only be of length 1, -* LastValue always stores the last value of a single node. If multiple nodes attempt to -* write to this channel in a single step, an error will be thrown. -* @internal -*/ -var LastValue = class LastValue extends BaseChannel { - lc_graph_name = "LastValue"; - value = []; - fromCheckpoint(checkpoint) { - const empty = new LastValue(); - if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) return false; - if (values.length !== 1) throw new InvalidUpdateError("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } -}; -/** -* Stores the last value received, but only made available after finish(). -* Once made available, clears the value. -*/ -var LastValueAfterFinish = class LastValueAfterFinish extends BaseChannel { - lc_graph_name = "LastValueAfterFinish"; - value = []; - finished = false; - fromCheckpoint(checkpoint) { - const empty = new LastValueAfterFinish(); - if (typeof checkpoint !== "undefined") { - const [value, finished] = checkpoint; - empty.value = [value]; - empty.finished = finished; - } - return empty; - } - update(values) { - if (values.length === 0) return false; - this.finished = false; - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0 || !this.finished) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) return void 0; - return [this.value[0], this.finished]; - } - consume() { - if (this.finished) { - this.finished = false; - this.value = []; - return true; - } - return false; - } - finish() { - if (!this.finished && this.value.length > 0) { - this.finished = true; - return true; - } - return false; - } - isAvailable() { - return this.value.length !== 0 && this.finished; - } -}; - -//#endregion - -//# sourceMappingURL=last_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/annotation.js - - - -//#region src/graph/annotation.ts -/** -* Should not be instantiated directly. See {@link Annotation}. -*/ -var AnnotationRoot = class { - lc_graph_name = "AnnotationRoot"; - spec; - constructor(s) { - this.spec = s; - } -}; -/** -* Helper that instantiates channels within a StateGraph state. -* -* Can be used as a field in an {@link Annotation.Root} wrapper in one of two ways: -* 1. **Directly**: Creates a channel that stores the most recent value returned from a node. -* 2. **With a reducer**: Creates a channel that applies the reducer on a node's return value. -* -* @example -* ```ts -* import { StateGraph, Annotation } from "@langchain/langgraph"; -* -* // Define a state with a single string key named "currentOutput" -* const SimpleAnnotation = Annotation.Root({ -* currentOutput: Annotation, -* }); -* -* const graphBuilder = new StateGraph(SimpleAnnotation); -* -* // A node in the graph that returns an object with a "currentOutput" key -* // replaces the value in the state. You can get the state type as shown below: -* const myNode = (state: typeof SimpleAnnotation.State) => { -* return { -* currentOutput: "some_new_value", -* }; -* } -* -* const graph = graphBuilder -* .addNode("myNode", myNode) -* ... -* .compile(); -* ``` -* -* @example -* ```ts -* import { type BaseMessage, AIMessage } from "@langchain/core/messages"; -* import { StateGraph, Annotation } from "@langchain/langgraph"; -* -* // Define a state with a single key named "messages" that will -* // combine a returned BaseMessage or arrays of BaseMessages -* const AnnotationWithReducer = Annotation.Root({ -* messages: Annotation({ -* // Different types are allowed for updates -* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { -* if (Array.isArray(right)) { -* return left.concat(right); -* } -* return left.concat([right]); -* }, -* default: () => [], -* }), -* }); -* -* const graphBuilder = new StateGraph(AnnotationWithReducer); -* -* // A node in the graph that returns an object with a "messages" key -* // will update the state by combining the existing value with the returned one. -* const myNode = (state: typeof AnnotationWithReducer.State) => { -* return { -* messages: [new AIMessage("Some new response")], -* }; -* }; -* -* const graph = graphBuilder -* .addNode("myNode", myNode) -* ... -* .compile(); -* ``` -* @namespace -* @property Root -* Helper function that instantiates a StateGraph state. See {@link Annotation} for usage. -*/ -const Annotation = function(annotation) { - if (annotation) return getChannel(annotation); - else return new LastValue(); -}; -Annotation.Root = (sd) => new AnnotationRoot(sd); -function getChannel(reducer) { - if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) return new BinaryOperatorAggregate(reducer.reducer, reducer.default); - if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) return new BinaryOperatorAggregate(reducer.value, reducer.default); - return new LastValue(); -} - -//#endregion - -//# sourceMappingURL=annotation.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/constants.js -//#region src/constants.ts -/** Special reserved node name denoting the start of a graph. */ -const START = "__start__"; -/** Special reserved node name denoting the end of a graph. */ -const END = "__end__"; -const INPUT = "__input__"; -const COPY = "__copy__"; -const constants_ERROR = "__error__"; -/** Special reserved cache namespaces */ -const CACHE_NS_WRITES = "__pregel_ns_writes"; -const CONFIG_KEY_SEND = "__pregel_send"; -/** config key containing function used to call a node (push task) */ -const constants_CONFIG_KEY_CALL = "__pregel_call"; -const CONFIG_KEY_READ = "__pregel_read"; -const CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer"; -const CONFIG_KEY_RESUMING = "__pregel_resuming"; -const CONFIG_KEY_TASK_ID = "__pregel_task_id"; -const CONFIG_KEY_STREAM = "__pregel_stream"; -const CONFIG_KEY_RESUME_VALUE = "__pregel_resume_value"; -const CONFIG_KEY_RESUME_MAP = "__pregel_resume_map"; -const constants_CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad"; -/** config key containing state from previous invocation of graph for the given thread */ -const constants_CONFIG_KEY_PREVIOUS_STATE = "__pregel_previous"; -const CONFIG_KEY_DURABILITY = "__pregel_durability"; -const CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id"; -const CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns"; -const CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished"; -const CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map"; -const CONFIG_KEY_ABORT_SIGNALS = "__pregel_abort_signals"; -/** Special channel reserved for graph interrupts */ -const constants_INTERRUPT = "__interrupt__"; -/** Special channel reserved for graph resume */ -const constants_RESUME = "__resume__"; -/** Special channel reserved for cases when a task exits without any writes */ -const NO_WRITES = "__no_writes__"; -/** Special channel reserved for graph return */ -const RETURN = "__return__"; -/** Special channel reserved for graph previous state */ -const PREVIOUS = "__previous__"; -const TAG_HIDDEN = "langsmith:hidden"; -const TAG_NOSTREAM = "langsmith:nostream"; -const SELF = "__self__"; -const constants_TASKS = "__pregel_tasks"; -const PUSH = "__pregel_push"; -const PULL = "__pregel_pull"; -const NULL_TASK_ID = "00000000-0000-0000-0000-000000000000"; -const RESERVED = [ - TAG_HIDDEN, - INPUT, - constants_INTERRUPT, - constants_RESUME, - constants_ERROR, - NO_WRITES, - CONFIG_KEY_SEND, - CONFIG_KEY_READ, - CONFIG_KEY_CHECKPOINTER, - CONFIG_KEY_DURABILITY, - CONFIG_KEY_STREAM, - CONFIG_KEY_RESUMING, - CONFIG_KEY_TASK_ID, - constants_CONFIG_KEY_CALL, - CONFIG_KEY_RESUME_VALUE, - constants_CONFIG_KEY_SCRATCHPAD, - constants_CONFIG_KEY_PREVIOUS_STATE, - CONFIG_KEY_CHECKPOINT_MAP, - CONFIG_KEY_CHECKPOINT_NS, - CONFIG_KEY_CHECKPOINT_ID -]; -const CHECKPOINT_NAMESPACE_SEPARATOR = "|"; -const CHECKPOINT_NAMESPACE_END = ":"; -/** @internal */ -const COMMAND_SYMBOL = Symbol.for("langgraph.command"); -/** -* Instance of a {@link Command} class. -* -* This is used to avoid IntelliSense suggesting public fields -* of {@link Command} class when a plain object is expected. -* -* @see {@link Command} -* @internal -*/ -var CommandInstance = class { - [COMMAND_SYMBOL]; - constructor(args) { - this[COMMAND_SYMBOL] = args; - } -}; -function _isSendInterface(x) { - const operation = x; - return operation !== null && operation !== void 0 && typeof operation.node === "string" && operation.args !== void 0; -} -/** -* -* A message or packet to send to a specific node in the graph. -* -* The `Send` class is used within a `StateGraph`'s conditional edges to -* dynamically invoke a node with a custom state at the next step. -* -* Importantly, the sent state can differ from the core graph's state, -* allowing for flexible and dynamic workflow management. -* -* One such example is a "map-reduce" workflow where your graph invokes -* the same node multiple times in parallel with different states, -* before aggregating the results back into the main graph's state. -* -* @example -* ```typescript -* import { Annotation, Send, StateGraph } from "@langchain/langgraph"; -* -* const ChainState = Annotation.Root({ -* subjects: Annotation, -* jokes: Annotation({ -* reducer: (a, b) => a.concat(b), -* }), -* }); -* -* const continueToJokes = async (state: typeof ChainState.State) => { -* return state.subjects.map((subject) => { -* return new Send("generate_joke", { subjects: [subject] }); -* }); -* }; -* -* const graph = new StateGraph(ChainState) -* .addNode("generate_joke", (state) => ({ -* jokes: [`Joke about ${state.subjects}`], -* })) -* .addConditionalEdges("__start__", continueToJokes) -* .addEdge("generate_joke", "__end__") -* .compile(); -* -* const res = await graph.invoke({ subjects: ["cats", "dogs"] }); -* console.log(res); -* -* // Invoking with two subjects results in a generated joke for each -* // { subjects: ["cats", "dogs"], jokes: [`Joke about cats`, `Joke about dogs`] } -* ``` -*/ -var Send = class { - lg_name = "Send"; - node; - args; - constructor(node, args) { - this.node = node; - this.args = _deserializeCommandSendObjectGraph(args); - } - toJSON() { - return { - lg_name: this.lg_name, - node: this.node, - args: this.args - }; - } -}; -function _isSend(x) { - return x instanceof Send; -} -/** -* Checks if the given graph invoke / stream chunk contains interrupt. -* -* @example -* ```ts -* import { INTERRUPT, isInterrupted } from "@langchain/langgraph"; -* -* const values = await graph.invoke({ foo: "bar" }); -* if (isInterrupted(values)) { -* const interrupt = values[INTERRUPT][0].value; -* } -* ``` -* -* @param values - The values to check. -* @returns `true` if the values contain an interrupt, `false` otherwise. -*/ -function isInterrupted(values) { - if (!values || typeof values !== "object") return false; - if (!(constants_INTERRUPT in values)) return false; - return Array.isArray(values[constants_INTERRUPT]); -} -/** -* One or more commands to update the graph's state and send messages to nodes. -* Can be used to combine routing logic with state updates in lieu of conditional edges -* -* @example -* ```ts -* import { Annotation, Command } from "@langchain/langgraph"; -* -* // Define graph state -* const StateAnnotation = Annotation.Root({ -* foo: Annotation, -* }); -* -* // Define the nodes -* const nodeA = async (_state: typeof StateAnnotation.State) => { -* console.log("Called A"); -* // this is a replacement for a real conditional edge function -* const goto = Math.random() > .5 ? "nodeB" : "nodeC"; -* // note how Command allows you to BOTH update the graph state AND route to the next node -* return new Command({ -* // this is the state update -* update: { -* foo: "a", -* }, -* // this is a replacement for an edge -* goto, -* }); -* }; -* -* // Nodes B and C are unchanged -* const nodeB = async (state: typeof StateAnnotation.State) => { -* console.log("Called B"); -* return { -* foo: state.foo + "|b", -* }; -* } -* -* const nodeC = async (state: typeof StateAnnotation.State) => { -* console.log("Called C"); -* return { -* foo: state.foo + "|c", -* }; -* } -* -* import { StateGraph } from "@langchain/langgraph"; - -* // NOTE: there are no edges between nodes A, B and C! -* const graph = new StateGraph(StateAnnotation) -* .addNode("nodeA", nodeA, { -* ends: ["nodeB", "nodeC"], -* }) -* .addNode("nodeB", nodeB) -* .addNode("nodeC", nodeC) -* .addEdge("__start__", "nodeA") -* .compile(); -* -* await graph.invoke({ foo: "" }); -* -* // Randomly oscillates between -* // { foo: 'a|c' } and { foo: 'a|b' } -* ``` -*/ -var Command = class extends CommandInstance { - lg_name = "Command"; - lc_direct_tool_output = true; - /** - * Graph to send the command to. Supported values are: - * - None: the current graph (default) - * - The specific name of the graph to send the command to - * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph) - */ - graph; - /** - * Update to apply to the graph's state as a result of executing the node that is returning the command. - * Written to the state as if the node had simply returned this value instead of the Command object. - */ - update; - /** - * Value to resume execution with. To be used together with {@link interrupt}. - */ - resume; - /** - * Can be one of the following: - * - name of the node to navigate to next (any node that belongs to the specified `graph`) - * - sequence of node names to navigate to next - * - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object) - * - sequence of {@link Send} objects - */ - goto = []; - static PARENT = "__parent__"; - constructor(args) { - super(args); - this.resume = args.resume; - this.graph = args.graph; - this.update = args.update; - if (args.goto) this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)]; - } - /** - * Convert the update field to a list of {@link PendingWrite} tuples - * @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`. - * @internal - */ - _updateAsTuples() { - if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) return Object.entries(this.update); - else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) return this.update; - else return [["__root__", this.update]]; - } - toJSON() { - let serializedGoto; - if (typeof this.goto === "string") serializedGoto = this.goto; - else if (_isSend(this.goto)) serializedGoto = this.goto.toJSON(); - else serializedGoto = this.goto?.map((innerGoto) => { - if (typeof innerGoto === "string") return innerGoto; - else return innerGoto.toJSON(); - }); - return { - lg_name: this.lg_name, - update: this.update, - resume: this.resume, - goto: serializedGoto - }; - } -}; -/** -* A type guard to check if the given value is a {@link Command}. -* -* Useful for type narrowing when working with the {@link Command} object. -* -* @param x - The value to check. -* @returns `true` if the value is a {@link Command}, `false` otherwise. -*/ -function isCommand(x) { - if (typeof x !== "object") return false; - if (x === null || x === void 0) return false; - if ("lg_name" in x && x.lg_name === "Command") return true; - return false; -} -/** -* Reconstructs Command and Send objects from a deeply nested tree of anonymous objects -* matching their interfaces. -* -* This is only exported for testing purposes. It is NOT intended to be used outside of -* the Command and Send classes. -* -* @internal -* -* @param x - The command send tree to convert. -* @param seen - A map of seen objects to avoid infinite loops. -* @returns The converted command send tree. -*/ -function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map()) { - if (x !== void 0 && x !== null && typeof x === "object") { - if (seen.has(x)) return seen.get(x); - let result; - if (Array.isArray(x)) { - result = []; - seen.set(x, result); - x.forEach((item, index) => { - result[index] = _deserializeCommandSendObjectGraph(item, seen); - }); - } else if (isCommand(x) && !(x instanceof Command)) { - result = new Command(x); - seen.set(x, result); - } else if (_isSendInterface(x) && !(x instanceof Send)) { - result = new Send(x.node, x.args); - seen.set(x, result); - } else if (isCommand(x) || _isSend(x)) { - result = x; - seen.set(x, result); - } else if ("lc_serializable" in x && x.lc_serializable) { - result = x; - seen.set(x, result); - } else { - result = {}; - seen.set(x, result); - for (const [key, value] of Object.entries(x)) result[key] = _deserializeCommandSendObjectGraph(value, seen); - } - return result; - } - return x; -} - -//#endregion - -//# sourceMappingURL=constants.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/config.js - - - -//#region src/pregel/utils/config.ts -const COPIABLE_KEYS = [ - "tags", - "metadata", - "callbacks", - "configurable" -]; -const CONFIG_KEYS = [ - "tags", - "metadata", - "callbacks", - "runName", - "maxConcurrency", - "recursionLimit", - "configurable", - "runId", - "outputKeys", - "streamMode", - "store", - "writer", - "interrupt", - "context", - "interruptBefore", - "interruptAfter", - "checkpointDuring", - "durability", - "signal" -]; -const config_DEFAULT_RECURSION_LIMIT = 25; -function config_ensureLangGraphConfig(...configs) { - const empty = { - tags: [], - metadata: {}, - callbacks: void 0, - recursionLimit: config_DEFAULT_RECURSION_LIMIT, - configurable: {} - }; - const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (implicitConfig !== void 0) { - for (const [k, v] of Object.entries(implicitConfig)) if (v !== void 0) if (COPIABLE_KEYS.includes(k)) { - let copiedValue; - if (Array.isArray(v)) copiedValue = [...v]; - else if (typeof v === "object") if (k === "callbacks" && "copy" in v && typeof v.copy === "function") copiedValue = v.copy(); - else copiedValue = { ...v }; - else copiedValue = v; - empty[k] = copiedValue; - } else empty[k] = v; - } - for (const config of configs) { - if (config === void 0) continue; - for (const [k, v] of Object.entries(config)) if (v !== void 0 && CONFIG_KEYS.includes(k)) empty[k] = v; - } - for (const [key, value] of Object.entries(empty.configurable)) { - empty.metadata = empty.metadata ?? {}; - if (!key.startsWith("__") && (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && !(key in empty.metadata)) empty.metadata[key] = value; - } - return empty; -} -/** -* A helper utility function that returns the {@link BaseStore} that was set when the graph was initialized -* -* @returns a reference to the {@link BaseStore} that was set when the graph was initialized -*/ -function getStore(config) { - const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getStore` in such environment, pass the `config` from the node function directly."].join("\n")); - return runConfig?.store; -} -/** -* A helper utility function that returns the {@link LangGraphRunnableConfig#writer} if "custom" stream mode is enabled, otherwise undefined. -* -* @returns a reference to the {@link LangGraphRunnableConfig#writer} if "custom" stream mode is enabled, otherwise undefined -*/ -function getWriter(config) { - const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join("\n")); - return runConfig?.writer || runConfig?.configurable?.writer; -} -/** -* A helper utility function that returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized. -* -* Note: This only works when running in an environment that supports node:async_hooks and AsyncLocalStorage. If you're running this in a -* web environment, access the LangGraphRunnableConfig from the node function directly. -* -* @returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized -*/ -function getConfig() { - return async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); -} -/** -* A helper utility function that returns the input for the currently executing task -* -* @returns the input for the currently executing task -*/ -function getCurrentTaskInput(config) { - const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join("\n")); - if (runConfig.configurable?.[CONFIG_KEY_SCRATCHPAD]?.currentTaskInput === void 0) throw new Error("BUG: internal scratchpad not initialized."); - return runConfig.configurable[CONFIG_KEY_SCRATCHPAD].currentTaskInput; -} -function recastCheckpointNamespace(namespace) { - return namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR).filter((part) => !part.match(/^\d+$/)).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR); -} -function getParentCheckpointNamespace(namespace) { - const parts = namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR); - while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) parts.pop(); - return parts.slice(0, -1).join(CHECKPOINT_NAMESPACE_SEPARATOR); -} - -//#endregion - -//# sourceMappingURL=config.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/hash.js -//#region src/hash.ts -const n = (n$1) => BigInt(n$1); -const view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset); -const PRIME32_1 = n("0x9E3779B1"); -const PRIME32_2 = n("0x85EBCA77"); -const PRIME32_3 = n("0xC2B2AE3D"); -const PRIME64_1 = n("0x9E3779B185EBCA87"); -const PRIME64_2 = n("0xC2B2AE3D27D4EB4F"); -const PRIME64_3 = n("0x165667B19E3779F9"); -const PRIME64_4 = n("0x85EBCA77C2B2AE63"); -const PRIME64_5 = n("0x27D4EB2F165667C5"); -const PRIME_MX1 = n("0x165667919E3779F9"); -const PRIME_MX2 = n("0x9FB21C651E98DF25"); -const hexToUint8Array = (hex) => { - const strLen = hex.length; - if (strLen % 2 !== 0) throw new Error("String should have an even number of characters"); - const maxLength = strLen / 2; - const bytes = new Uint8Array(maxLength); - let read = 0; - let write = 0; - while (write < maxLength) { - const slice = hex.slice(read, read += 2); - bytes[write] = Number.parseInt(slice, 16); - write += 1; - } - return view(bytes); -}; -const kkey = hexToUint8Array("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); -const mask128 = (n(1) << n(128)) - n(1); -const mask64 = (n(1) << n(64)) - n(1); -const mask32 = (n(1) << n(32)) - n(1); -const STRIPE_LEN = 64; -const ACC_NB = STRIPE_LEN / 8; -const _U64 = 8; -const _U32 = 4; -function hash_assert(a) { - if (!a) throw new Error("Assert failed"); -} -function bswap64(a) { - const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); - scratchbuf.setBigUint64(0, a, true); - return scratchbuf.getBigUint64(0, false); -} -function bswap32(input) { - let a = input; - a = (a & n(65535)) << n(16) | (a & n(4294901760)) >> n(16); - a = (a & n(16711935)) << n(8) | (a & n(4278255360)) >> n(8); - return a; -} -function XXH_mult32to64(a, b) { - return (a & mask32) * (b & mask32) & mask64; -} -function rotl32(a, b) { - return (a << b | a >> n(32) - b) & mask32; -} -function XXH3_accumulate_512(acc, dataView, keyView) { - for (let i = 0; i < ACC_NB; i += 1) { - const data_val = dataView.getBigUint64(i * 8, true); - const data_key = data_val ^ keyView.getBigUint64(i * 8, true); - acc[i ^ 1] += data_val; - acc[i] += XXH_mult32to64(data_key, data_key >> n(32)); - } - return acc; -} -function XXH3_accumulate(acc, dataView, keyView, nbStripes) { - for (let n$1 = 0; n$1 < nbStripes; n$1 += 1) XXH3_accumulate_512(acc, view(dataView, n$1 * STRIPE_LEN), view(keyView, n$1 * 8)); - return acc; -} -function XXH3_scrambleAcc(acc, key) { - for (let i = 0; i < ACC_NB; i += 1) { - const key64 = key.getBigUint64(i * 8, true); - let acc64 = acc[i]; - acc64 = xorshift64(acc64, n(47)); - acc64 ^= key64; - acc64 *= PRIME32_1; - acc[i] = acc64 & mask64; - } - return acc; -} -function XXH3_mix2Accs(acc, key) { - return XXH3_mul128_fold64(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U64, true)); -} -function XXH3_mergeAccs(acc, key, start) { - let result64 = start; - result64 += XXH3_mix2Accs(acc.slice(0), view(key, 0 * _U32)); - result64 += XXH3_mix2Accs(acc.slice(2), view(key, 4 * _U32)); - result64 += XXH3_mix2Accs(acc.slice(4), view(key, 8 * _U32)); - result64 += XXH3_mix2Accs(acc.slice(6), view(key, 12 * _U32)); - return XXH3_avalanche(result64 & mask64); -} -function XXH3_hashLong(input, data, secret, f_acc, f_scramble) { - let acc = input; - const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN) / 8); - const block_len = STRIPE_LEN * nbStripesPerBlock; - const nb_blocks = Math.floor((data.byteLength - 1) / block_len); - for (let n$1 = 0; n$1 < nb_blocks; n$1 += 1) { - acc = XXH3_accumulate(acc, view(data, n$1 * block_len), secret, nbStripesPerBlock); - acc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN)); - } - { - const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN); - acc = XXH3_accumulate(acc, view(data, nb_blocks * block_len), secret, nbStripes); - acc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN), view(secret, secret.byteLength - STRIPE_LEN - 7)); - } - return acc; -} -function XXH3_hashLong_128b(data, secret) { - let acc = new BigUint64Array([ - PRIME32_3, - PRIME64_1, - PRIME64_2, - PRIME64_3, - PRIME64_4, - PRIME32_2, - PRIME64_5, - PRIME32_1 - ]); - hash_assert(data.byteLength > 128); - acc = XXH3_hashLong(acc, data, secret, XXH3_accumulate_512, XXH3_scrambleAcc); - hash_assert(acc.length * 8 === 64); - { - const low64 = XXH3_mergeAccs(acc, view(secret, 11), n(data.byteLength) * PRIME64_1 & mask64); - const high64 = XXH3_mergeAccs(acc, view(secret, secret.byteLength - STRIPE_LEN - 11), ~(n(data.byteLength) * PRIME64_2) & mask64); - return high64 << n(64) | low64; - } -} -function XXH3_mul128_fold64(a, b) { - const lll = a * b & mask128; - return lll & mask64 ^ lll >> n(64); -} -function XXH3_mix16B(dataView, keyView, seed) { - return XXH3_mul128_fold64((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask64, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask64); -} -function XXH3_mix32B(acc, data1, data2, key, seed) { - let accl = acc & mask64; - let acch = acc >> n(64) & mask64; - accl += XXH3_mix16B(data1, key, seed); - accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); - accl &= mask64; - acch += XXH3_mix16B(data2, view(key, 16), seed); - acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); - acch &= mask64; - return acch << n(64) | accl; -} -function XXH3_avalanche(input) { - let h64 = input; - h64 ^= h64 >> n(37); - h64 *= PRIME_MX1; - h64 &= mask64; - h64 ^= h64 >> n(32); - return h64; -} -function XXH3_avalanche64(input) { - let h64 = input; - h64 ^= h64 >> n(33); - h64 *= PRIME64_2; - h64 &= mask64; - h64 ^= h64 >> n(29); - h64 *= PRIME64_3; - h64 &= mask64; - h64 ^= h64 >> n(32); - return h64; -} -function XXH3_len_1to3_128b(data, key32, seed) { - const len = data.byteLength; - hash_assert(len > 0 && len <= 3); - const combined = n(data.getUint8(len - 1)) | n(len << 8) | n(data.getUint8(0) << 16) | n(data.getUint8(len >> 1) << 24); - const blow = (n(key32.getUint32(0, true)) ^ n(key32.getUint32(4, true))) + seed; - const low = (combined ^ blow) & mask64; - const bhigh = (n(key32.getUint32(8, true)) ^ n(key32.getUint32(12, true))) - seed; - const high = (rotl32(bswap32(combined), n(13)) ^ bhigh) & mask64; - return (XXH3_avalanche64(high) & mask64) << n(64) | XXH3_avalanche64(low); -} -function xorshift64(b, shift) { - return b ^ b >> shift; -} -function XXH3_len_4to8_128b(data, key32, seed) { - const len = data.byteLength; - hash_assert(len >= 4 && len <= 8); - { - const l1 = data.getUint32(0, true); - const l2 = data.getUint32(len - 4, true); - const l64 = n(l1) | n(l2) << n(32); - const bitflip = (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask64; - const keyed = l64 ^ bitflip; - let m128 = keyed * (PRIME64_1 + (n(len) << n(2))) & mask128; - m128 += (m128 & mask64) << n(65); - m128 &= mask128; - m128 ^= m128 >> n(67); - return xorshift64(xorshift64(m128 & mask64, n(35)) * PRIME_MX2 & mask64, n(28)) | XXH3_avalanche(m128 >> n(64)) << n(64); - } -} -function XXH3_len_9to16_128b(data, key64, seed) { - const len = data.byteLength; - hash_assert(len >= 9 && len <= 16); - { - const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask64; - const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask64; - const ll1 = data.getBigUint64(0, true); - let ll2 = data.getBigUint64(len - 8, true); - let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_1; - const m128_l = (m128 & mask64) + (n(len - 1) << n(54)); - m128 = m128 & (mask128 ^ mask64) | m128_l; - ll2 ^= bitfliph; - m128 += ll2 + (ll2 & mask32) * (PRIME32_2 - n(1)) << n(64); - m128 &= mask128; - m128 ^= bswap64(m128 >> n(64)); - let h128 = (m128 & mask64) * PRIME64_2; - h128 += (m128 >> n(64)) * PRIME64_2 << n(64); - h128 &= mask128; - return XXH3_avalanche(h128 & mask64) | XXH3_avalanche(h128 >> n(64)) << n(64); - } -} -function XXH3_len_0to16_128b(data, seed) { - const len = data.byteLength; - hash_assert(len <= 16); - if (len > 8) return XXH3_len_9to16_128b(data, kkey, seed); - if (len >= 4) return XXH3_len_4to8_128b(data, kkey, seed); - if (len > 0) return XXH3_len_1to3_128b(data, kkey, seed); - return XXH3_avalanche64(seed ^ kkey.getBigUint64(64, true) ^ kkey.getBigUint64(72, true)) | XXH3_avalanche64(seed ^ kkey.getBigUint64(80, true) ^ kkey.getBigUint64(88, true)) << n(64); -} -function inv64(x) { - return ~x + n(1) & mask64; -} -function XXH3_len_17to128_128b(data, secret, seed) { - let acc = n(data.byteLength) * PRIME64_1 & mask64; - let i = n(data.byteLength - 1) / n(32); - while (i >= 0) { - const ni = Number(i); - acc = XXH3_mix32B(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed); - i -= n(1); - } - let h128l = acc + (acc >> n(64)) & mask64; - h128l = XXH3_avalanche(h128l); - let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; - h128h &= mask64; - h128h = inv64(XXH3_avalanche(h128h)); - return h128l | h128h << n(64); -} -function XXH3_len_129to240_128b(data, secret, seed) { - let acc = n(data.byteLength) * PRIME64_1 & mask64; - for (let i = 32; i < 160; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed); - acc = XXH3_avalanche(acc & mask64) | XXH3_avalanche(acc >> n(64)) << n(64); - for (let i = 160; i <= data.byteLength; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed); - acc = XXH3_mix32B(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv64(seed)); - let h128l = acc + (acc >> n(64)) & mask64; - h128l = XXH3_avalanche(h128l); - let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; - h128h &= mask64; - h128h = inv64(XXH3_avalanche(h128h)); - return h128l | h128h << n(64); -} -function XXH3(input, seed = n(0)) { - const encoder = new TextEncoder(); - const data = view(typeof input === "string" ? encoder.encode(input) : input); - const len = data.byteLength; - const hexDigest = (data$1) => data$1.toString(16).padStart(32, "0"); - if (len <= 16) return hexDigest(XXH3_len_0to16_128b(data, seed)); - if (len <= 128) return hexDigest(XXH3_len_17to128_128b(data, kkey, seed)); - if (len <= 240) return hexDigest(XXH3_len_129to240_128b(data, kkey, seed)); - return hexDigest(XXH3_hashLong_128b(data, kkey)); -} -function isXXH3(value) { - return /^[0-9a-f]{32}$/.test(value); -} - -//#endregion - -//# sourceMappingURL=hash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/interrupt.js - - - - - -//#region src/interrupt.ts -/** -* Interrupts the execution of a graph node. -* This function can be used to pause execution of a node, and return the value of the `resume` -* input when the graph is re-invoked using `Command`. -* Multiple interrupts can be called within a single node, and each will be handled sequentially. -* -* When an interrupt is called: -* 1. If there's a `resume` value available (from a previous `Command`), it returns that value. -* 2. Otherwise, it throws a `GraphInterrupt` with the provided value -* 3. The graph can be resumed by passing a `Command` with a `resume` value -* -* Because the `interrupt` function propagates by throwing a special `GraphInterrupt` error, -* you should avoid using `try/catch` blocks around the `interrupt` function, -* or if you do, ensure that the `GraphInterrupt` error is thrown again within your `catch` block. -* -* @param value - The value to include in the interrupt. This will be available in task.interrupts[].value -* @returns The `resume` value provided when the graph is re-invoked with a Command -* -* @example -* ```typescript -* // Define a node that uses multiple interrupts -* const nodeWithInterrupts = () => { -* // First interrupt - will pause execution and include {value: 1} in task values -* const answer1 = interrupt({ value: 1 }); -* -* // Second interrupt - only called after first interrupt is resumed -* const answer2 = interrupt({ value: 2 }); -* -* // Use the resume values -* return { myKey: answer1 + " " + answer2 }; -* }; -* -* // Resume the graph after first interrupt -* await graph.stream(new Command({ resume: "answer 1" })); -* -* // Resume the graph after second interrupt -* await graph.stream(new Command({ resume: "answer 2" })); -* // Final result: { myKey: "answer 1 answer 2" } -* ``` -* -* @throws {Error} If called outside the context of a graph -* @throws {GraphInterrupt} When no resume value is available -*/ -function interrupt(value) { - const config = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (!config) throw new Error("Called interrupt() outside the context of a graph."); - const conf = config.configurable; - if (!conf) throw new Error("No configurable found in config"); - const checkpointer = conf[CONFIG_KEY_CHECKPOINTER]; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const scratchpad = conf[constants_CONFIG_KEY_SCRATCHPAD]; - scratchpad.interruptCounter += 1; - const idx = scratchpad.interruptCounter; - if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { - conf[CONFIG_KEY_SEND]?.([[constants_RESUME, scratchpad.resume]]); - return scratchpad.resume[idx]; - } - if (scratchpad.nullResume !== void 0) { - if (scratchpad.resume.length !== idx) throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); - const v = scratchpad.consumeNullResume(); - scratchpad.resume.push(v); - conf[CONFIG_KEY_SEND]?.([[constants_RESUME, scratchpad.resume]]); - return v; - } - const ns = conf[CONFIG_KEY_CHECKPOINT_NS]?.split(CHECKPOINT_NAMESPACE_SEPARATOR); - const id = ns ? XXH3(ns.join(CHECKPOINT_NAMESPACE_SEPARATOR)) : void 0; - throw new GraphInterrupt([{ - id, - value - }]); -} - -//#endregion - -//# sourceMappingURL=interrupt.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/utils.js - - - - -//#region src/utils.ts -var RunnableCallable = class extends Runnable { - lc_namespace = ["langgraph"]; - func; - tags; - config; - trace = true; - recurse = true; - constructor(fields) { - super(); - this.name = fields.name ?? fields.func.name; - this.func = fields.func; - this.config = fields.tags ? { tags: fields.tags } : void 0; - this.trace = fields.trace ?? this.trace; - this.recurse = fields.recurse ?? this.recurse; - } - async _tracedInvoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { - try { - const output = await this.func(input, childConfig); - resolve(output); - } catch (e) { - reject(e); - } - }); - }); - } - async invoke(input, options) { - let returnValue; - const config = config_ensureLangGraphConfig(options); - const mergedConfig = mergeConfigs(this.config, config); - if (this.trace) returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); - else returnValue = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); - if (Runnable.isRunnable(returnValue) && this.recurse) return await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); - return returnValue; - } -}; -function* prefixGenerator(generator, prefix) { - if (prefix === void 0) yield* generator; - else for (const value of generator) yield [prefix, value]; -} -async function gatherIterator(i) { - const out = []; - for await (const item of await i) out.push(item); - return out; -} -function gatherIteratorSync(i) { - const out = []; - for (const item of i) out.push(item); - return out; -} -function patchConfigurable(config, patch) { - if (!config) return { configurable: patch }; - else if (!("configurable" in config)) return { - ...config, - configurable: patch - }; - else return { - ...config, - configurable: { - ...config.configurable, - ...patch - } - }; -} -function utils_isAsyncGeneratorFunction(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; -} -function utils_isGeneratorFunction(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/write.js - - - - - -//#region src/pregel/write.ts -const SKIP_WRITE = { [Symbol.for("LG_SKIP_WRITE")]: true }; -function _isSkipWrite(x) { - return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== void 0; -} -const PASSTHROUGH = { [Symbol.for("LG_PASSTHROUGH")]: true }; -function _isPassthrough(x) { - return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== void 0; -} -const IS_WRITER = Symbol("IS_WRITER"); -/** -* Mapping of write channels to Runnables that return the value to be written, -* or None to skip writing. -*/ -var ChannelWrite = class ChannelWrite extends RunnableCallable { - writes; - constructor(writes, tags) { - const name = `ChannelWrite<${writes.map((packet) => { - if (_isSend(packet)) return packet.node; - else if ("channel" in packet) return packet.channel; - return "..."; - }).join(",")}>`; - super({ - writes, - name, - tags, - func: async (input, config) => { - return this._write(input, config ?? {}); - } - }); - this.writes = writes; - } - async _write(input, config) { - const writes = this.writes.map((write) => { - if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) return { - mapper: write.mapper, - value: input - }; - else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) return { - channel: write.channel, - value: input, - skipNone: write.skipNone, - mapper: write.mapper - }; - else return write; - }); - await ChannelWrite.doWrite(config, writes); - return input; - } - static async doWrite(config, writes) { - for (const w of writes) { - if (_isChannelWriteEntry(w)) { - if (w.channel === constants_TASKS) throw new InvalidUpdateError("Cannot write to the reserved channel TASKS"); - if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); - } - if (_isChannelWriteTupleEntry(w)) { - if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); - } - } - const writeEntries = []; - for (const w of writes) if (_isSend(w)) writeEntries.push([constants_TASKS, w]); - else if (_isChannelWriteTupleEntry(w)) { - const mappedResult = await w.mapper.invoke(w.value, config); - if (mappedResult != null && mappedResult.length > 0) writeEntries.push(...mappedResult); - } else if (_isChannelWriteEntry(w)) { - const mappedValue = w.mapper !== void 0 ? await w.mapper.invoke(w.value, config) : w.value; - if (_isSkipWrite(mappedValue)) continue; - if (w.skipNone && mappedValue === void 0) continue; - writeEntries.push([w.channel, mappedValue]); - } else throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); - const write = config.configurable?.[CONFIG_KEY_SEND]; - write(writeEntries); - } - static isWriter(runnable) { - return runnable instanceof ChannelWrite || IS_WRITER in runnable && !!runnable[IS_WRITER]; - } - static registerWriter(runnable) { - return Object.defineProperty(runnable, IS_WRITER, { value: true }); - } -}; -function _isChannelWriteEntry(x) { - return x !== void 0 && typeof x.channel === "string"; -} -function _isChannelWriteTupleEntry(x) { - return x !== void 0 && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper); -} - -//#endregion - -//# sourceMappingURL=write.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/read.js - - - - - -//#region src/pregel/read.ts -var ChannelRead = class ChannelRead extends RunnableCallable { - lc_graph_name = "ChannelRead"; - channel; - fresh = false; - mapper; - constructor(channel, mapper, fresh = false) { - super({ func: (_, config) => ChannelRead.doRead(config, this.channel, this.fresh, this.mapper) }); - this.fresh = fresh; - this.mapper = mapper; - this.channel = channel; - this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; - } - static doRead(config, channel, fresh, mapper) { - const read = config.configurable?.[CONFIG_KEY_READ]; - if (!read) throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); - if (mapper) return mapper(read(channel, fresh)); - else return read(channel, fresh); - } -}; -const defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough(); -var PregelNode = class PregelNode extends RunnableBinding { - lc_graph_name = "PregelNode"; - channels; - triggers = []; - mapper; - writers = []; - bound = defaultRunnableBound; - kwargs = {}; - metadata = {}; - tags = []; - retryPolicy; - cachePolicy; - subgraphs; - ends; - constructor(fields) { - const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; - const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; - super({ - ...fields, - bound: fields.bound ?? defaultRunnableBound, - config: { - ...fields.config ? fields.config : {}, - tags: mergedTags - } - }); - this.channels = channels; - this.triggers = triggers; - this.mapper = mapper; - this.writers = writers ?? this.writers; - this.bound = bound ?? this.bound; - this.kwargs = kwargs ?? this.kwargs; - this.metadata = metadata ?? this.metadata; - this.tags = mergedTags; - this.retryPolicy = retryPolicy; - this.cachePolicy = cachePolicy; - this.subgraphs = subgraphs; - this.ends = ends; - } - getWriters() { - const newWriters = [...this.writers]; - while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) { - const endWriters = newWriters.slice(-2); - const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); - newWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags); - newWriters.pop(); - } - return newWriters; - } - getNode() { - const writers = this.getWriters(); - if (this.bound === defaultRunnableBound && writers.length === 0) return void 0; - else if (this.bound === defaultRunnableBound && writers.length === 1) return writers[0]; - else if (this.bound === defaultRunnableBound) return new RunnableSequence({ - first: writers[0], - middle: writers.slice(1, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else if (writers.length > 0) return new RunnableSequence({ - first: this.bound, - middle: writers.slice(0, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else return this.bound; - } - join(channels) { - if (!Array.isArray(channels)) throw new Error("channels must be a list"); - if (typeof this.channels !== "object") throw new Error("all channels must be named when using .join()"); - return new PregelNode({ - channels: { - ...this.channels, - ...Object.fromEntries(channels.map((chan) => [chan, chan])) - }, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - } - pipe(coerceable) { - if (ChannelWrite.isWriter(coerceable)) return new PregelNode({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: [...this.writers, coerceable], - bound: this.bound, - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else if (this.bound === defaultRunnableBound) return new PregelNode({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: _coerceToRunnable(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else return new PregelNode({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound.pipe(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - } -}; - -//#endregion - -//# sourceMappingURL=read.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js -//#region src/pregel/utils/subgraph.ts -function isRunnableSequence(x) { - return "steps" in x && Array.isArray(x.steps); -} -function isPregelLike(x) { - return "lg_is_pregel" in x && x.lg_is_pregel === true; -} -function findSubgraphPregel(candidate) { - const candidates = [candidate]; - for (const candidate$1 of candidates) if (isPregelLike(candidate$1)) return candidate$1; - else if (isRunnableSequence(candidate$1)) candidates.push(...candidate$1.steps); - return void 0; -} - -//#endregion - -//# sourceMappingURL=subgraph.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/io.js - - - - -//#region src/pregel/io.ts -function readChannel(channels, chan, catchErrors = true, returnException = false) { - try { - return channels[chan].get(); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) { - if (returnException) return e; - else if (catchErrors) return null; - } - throw e; - } -} -function readChannels(channels, select, skipEmpty = true) { - if (Array.isArray(select)) { - const values = {}; - for (const k of select) try { - values[k] = readChannel(channels, k, !skipEmpty); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) continue; - } - return values; - } else return readChannel(channels, select); -} -/** -* Map input chunk to a sequence of pending writes in the form (channel, value). -*/ -function* mapCommand(cmd, pendingWrites) { - if (cmd.graph === Command.PARENT) throw new InvalidUpdateError("There is no parent graph."); - if (cmd.goto) { - let sends; - if (Array.isArray(cmd.goto)) sends = cmd.goto; - else sends = [cmd.goto]; - for (const send of sends) if (_isSend(send)) yield [ - NULL_TASK_ID, - constants_TASKS, - send - ]; - else if (typeof send === "string") yield [ - NULL_TASK_ID, - `branch:to:${send}`, - "__start__" - ]; - else throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); - } - if (cmd.resume) if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) for (const [tid, resume] of Object.entries(cmd.resume)) { - const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === constants_RESUME).map((w) => w[2]).slice(0, 1) ?? []; - existing.push(resume); - yield [ - tid, - constants_RESUME, - existing - ]; - } - else yield [ - NULL_TASK_ID, - constants_RESUME, - cmd.resume - ]; - if (cmd.update) { - if (typeof cmd.update !== "object" || !cmd.update) throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); - if (Array.isArray(cmd.update)) for (const [k, v] of cmd.update) yield [ - NULL_TASK_ID, - k, - v - ]; - else for (const [k, v] of Object.entries(cmd.update)) yield [ - NULL_TASK_ID, - k, - v - ]; - } -} -/** -* Map input chunk to a sequence of pending writes in the form [channel, value]. -*/ -function* mapInput(inputChannels, chunk) { - if (chunk !== void 0 && chunk !== null) if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { - for (const k in chunk) if (inputChannels.includes(k)) yield [k, chunk[k]]; - } else if (Array.isArray(inputChannels)) throw new Error(`Input chunk must be an object when "inputChannels" is an array`); - else yield [inputChannels, chunk]; -} -/** -* Map pending writes (a sequence of tuples (channel, value)) to output chunk. -*/ -function* mapOutputValues(outputChannels, pendingWrites, channels) { - if (Array.isArray(outputChannels)) { - if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) yield readChannels(channels, outputChannels); - } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) yield readChannel(channels, outputChannels); -} -/** -* Map pending writes (a sequence of tuples (channel, value)) to output chunk. -* @internal -* -* @param outputChannels - The channels to output. -* @param tasks - The tasks to output. -* @param cached - Whether the output is cached. -* -* @returns A generator that yields the output chunk (if any). -*/ -function* mapOutputUpdates(outputChannels, tasks, cached) { - const outputTasks = tasks.filter(([task, ww]) => { - return (task.config === void 0 || !task.config.tags?.includes(TAG_HIDDEN)) && ww[0][0] !== constants_ERROR && ww[0][0] !== constants_INTERRUPT; - }); - if (!outputTasks.length) return; - let updated; - if (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === RETURN))) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value])); - else if (!Array.isArray(outputChannels)) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value])); - else updated = outputTasks.flatMap(([task]) => { - const { writes } = task; - const counts = {}; - for (const [chan] of writes) if (outputChannels.includes(chan)) counts[chan] = (counts[chan] || 0) + 1; - if (Object.values(counts).some((count) => count > 1)) return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]); - else return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; - }); - const grouped = {}; - for (const [node, value] of updated) { - if (!(node in grouped)) grouped[node] = []; - grouped[node].push(value); - } - const flattened = {}; - for (const node in grouped) if (grouped[node].length === 1) { - const [write] = grouped[node]; - flattened[node] = write; - } else flattened[node] = grouped[node]; - if (cached) flattened["__metadata__"] = { cached }; - yield flattened; -} - -//#endregion - -//# sourceMappingURL=io.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/index.js - - -//#region src/pregel/utils/index.ts -function getNullChannelVersion(currentVersions) { - const startVersion = typeof currentVersions[START]; - if (startVersion === "number") return 0; - if (startVersion === "string") return ""; - for (const key in currentVersions) { - if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) continue; - const versionType = typeof currentVersions[key]; - if (versionType === "number") return 0; - if (versionType === "string") return ""; - break; - } - return void 0; -} -function getNewChannelVersions(previousVersions, currentVersions) { - if (Object.keys(previousVersions).length > 0) { - const nullVersion = getNullChannelVersion(currentVersions); - return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); - } else return currentVersions; -} -function utils_coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function utils_patchConfigurable(config, patch) { - if (config === null) return { configurable: patch }; - else if (config?.configurable === void 0) return { - ...config, - configurable: patch - }; - else return { - ...config, - configurable: { - ...config.configurable, - ...patch - } - }; -} -function patchCheckpointMap(config, metadata) { - const parents = metadata?.parents ?? {}; - if (Object.keys(parents).length > 0) return utils_patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_MAP]: { - ...parents, - [config.configurable?.checkpoint_ns ?? ""]: config.configurable?.checkpoint_id - } }); - else return config; -} -/** -* Combine multiple abort signals into a single abort signal. -* @param signals - The abort signals to combine. -* @returns A combined abort signal and a dispose function to remove the abort listener if unused. -*/ -function combineAbortSignals(...x) { - const signals = [...new Set(x.filter(Boolean))]; - if (signals.length === 0) return { - signal: void 0, - dispose: void 0 - }; - if (signals.length === 1) return { - signal: signals[0], - dispose: void 0 - }; - const combinedController = new AbortController(); - const listener = () => { - const reason = signals.find((s) => s.aborted)?.reason; - combinedController.abort(reason); - signals.forEach((s) => s.removeEventListener("abort", listener)); - }; - signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); - const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); - if (hasAlreadyAbortedSignal) combinedController.abort(hasAlreadyAbortedSignal.reason); - return { - signal: combinedController.signal, - dispose: () => { - signals.forEach((s) => s.removeEventListener("abort", listener)); - } - }; -} -/** -* Combine multiple callbacks into a single callback. -* @param callback1 - The first callback to combine. -* @param callback2 - The second callback to combine. -* @returns A single callback that is a combination of the input callbacks. -*/ -const combineCallbacks = (callback1, callback2) => { - if (!callback1 && !callback2) return void 0; - if (!callback1) return callback2; - if (!callback2) return callback1; - if (Array.isArray(callback1) && Array.isArray(callback2)) return [...callback1, ...callback2]; - if (Array.isArray(callback1)) return [...callback1, callback2]; - if (Array.isArray(callback2)) return [callback1, ...callback2]; - return [callback1, callback2]; -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/types.js -//#region src/pregel/types.ts -var Call = class { - func; - name; - input; - retry; - cache; - callbacks; - __lg_type = "call"; - constructor({ func, name, input, retry, cache, callbacks }) { - this.func = func; - this.name = name; - this.input = input; - this.retry = retry; - this.cache = cache; - this.callbacks = callbacks; - } -}; -function isCall(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; -} - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/call.js - - - - - - -//#region src/pregel/call.ts -/** -* Wraps a user function in a Runnable that writes the returned value to the RETURN channel. -*/ -function getRunnableForFunc(name, func) { - const run = new RunnableCallable({ - func: (input) => func(...input), - name, - trace: false, - recurse: false - }); - return new RunnableSequence({ - name, - first: run, - last: new ChannelWrite([{ - channel: RETURN, - value: PASSTHROUGH - }], [TAG_HIDDEN]) - }); -} -function getRunnableForEntrypoint(name, func) { - const run = new RunnableCallable({ - func: (input, config) => { - return func(input, config); - }, - name, - trace: false, - recurse: false - }); - return run; -} -function call_call({ func, name, cache, retry }, ...args) { - const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (typeof config.configurable?.[CONFIG_KEY_CALL] === "function") return config.configurable[CONFIG_KEY_CALL](func, name, args, { - retry, - cache, - callbacks: config.callbacks - }); - throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function."); -} - -//#endregion - -//# sourceMappingURL=call.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/algo.js - - - - - - - - - - - -//#region src/pregel/algo.ts -const increment = (current) => { - return current !== void 0 ? current + 1 : 1; -}; -function triggersNextStep(updatedChannels, triggerToNodes) { - if (triggerToNodes == null) return false; - for (const chan of updatedChannels) if (triggerToNodes[chan]) return true; - return false; -} -function maxChannelMapVersion(channelVersions) { - let maxVersion; - for (const chan in channelVersions) { - if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) continue; - if (maxVersion == null) maxVersion = channelVersions[chan]; - else maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); - } - return maxVersion; -} -function shouldInterrupt(checkpoint, interruptNodes, tasks) { - const nullVersion = getNullChannelVersion(checkpoint.channel_versions); - const seen = checkpoint.versions_seen[constants_INTERRUPT] ?? {}; - let anyChannelUpdated = false; - if ((checkpoint.channel_versions[START] ?? nullVersion) > (seen[START] ?? nullVersion)) anyChannelUpdated = true; - else for (const chan in checkpoint.channel_versions) { - if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) continue; - if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { - anyChannelUpdated = true; - break; - } - } - const anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name)); - return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; -} -function _localRead(checkpoint, channels, task, select, fresh = false) { - let updated = /* @__PURE__ */ new Set(); - if (!Array.isArray(select)) { - for (const [c] of task.writes) if (c === select) { - updated = new Set([c]); - break; - } - updated = updated || /* @__PURE__ */ new Set(); - } else updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c))); - let values; - if (fresh && updated.size > 0) { - const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); - const newCheckpoint = createCheckpoint(checkpoint, localChannels, -1); - const newChannels = emptyChannels(localChannels, newCheckpoint); - _applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], void 0, void 0); - values = readChannels({ - ...channels, - ...newChannels - }, select); - } else values = readChannels(channels, select); - return values; -} -function _localWrite(commit, processes, writes) { - for (const [chan, value] of writes) if ([PUSH, constants_TASKS].includes(chan) && value != null) { - if (!_isSend(value)) throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); - if (!(value.node in processes)) throw new InvalidUpdateError(`Invalid node name "${value.node}" in Send packet`); - } - commit(writes); -} -const IGNORE = new Set([ - NO_WRITES, - PUSH, - constants_RESUME, - constants_INTERRUPT, - RETURN, - constants_ERROR -]); -function _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { - tasks.sort((a, b) => { - const aPath = a.path?.slice(0, 3) || []; - const bPath = b.path?.slice(0, 3) || []; - for (let i = 0; i < Math.min(aPath.length, bPath.length); i += 1) { - if (aPath[i] < bPath[i]) return -1; - if (aPath[i] > bPath[i]) return 1; - } - return aPath.length - bPath.length; - }); - const bumpStep = tasks.some((task) => task.triggers.length > 0); - const onlyChannels = getOnlyChannels(channels); - for (const task of tasks) { - checkpoint.versions_seen[task.name] ??= {}; - for (const chan of task.triggers) if (chan in checkpoint.channel_versions) checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan]; - } - let maxVersion = maxChannelMapVersion(checkpoint.channel_versions); - const channelsToConsume = new Set(tasks.flatMap((task) => task.triggers).filter((chan) => !RESERVED.includes(chan))); - let usedNewVersion = false; - for (const chan of channelsToConsume) if (chan in onlyChannels && onlyChannels[chan].consume()) { - if (getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - usedNewVersion = true; - } - } - const pendingWritesByChannel = {}; - for (const task of tasks) for (const [chan, val] of task.writes) if (IGNORE.has(chan)) {} else if (chan in onlyChannels) { - pendingWritesByChannel[chan] ??= []; - pendingWritesByChannel[chan].push(val); - } - if (maxVersion != null && getNextVersion != null) maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; - const updatedChannels = /* @__PURE__ */ new Set(); - for (const [chan, vals] of Object.entries(pendingWritesByChannel)) if (chan in onlyChannels) { - const channel = onlyChannels[chan]; - let updated; - try { - updated = channel.update(vals); - } catch (e) { - if (e.name === InvalidUpdateError.unminifiable_name) { - const wrappedError = new InvalidUpdateError(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); - wrappedError.lc_error_code = e.lc_error_code; - throw wrappedError; - } else throw e; - } - if (updated && getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) updatedChannels.add(chan); - } - } - if (bumpStep) for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; - const channel = onlyChannels[chan]; - if (channel.isAvailable() && !updatedChannels.has(chan)) { - const updated = channel.update([]); - if (updated && getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) updatedChannels.add(chan); - } - } - } - if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; - const channel = onlyChannels[chan]; - if (channel.finish() && getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) updatedChannels.add(chan); - } - } - return updatedChannels; -} -function* candidateNodes(checkpoint, processes, extra) { - if (extra.updatedChannels != null && extra.triggerToNodes != null) { - const triggeredNodes = /* @__PURE__ */ new Set(); - for (const channel of extra.updatedChannels) { - const nodeIds = extra.triggerToNodes[channel]; - for (const id of nodeIds ?? []) triggeredNodes.add(id); - } - yield* [...triggeredNodes].sort(); - return; - } - const isEmptyChannelVersions = (() => { - for (const chan in checkpoint.channel_versions) if (checkpoint.channel_versions[chan] !== null) return false; - return true; - })(); - if (isEmptyChannelVersions) return; - for (const name in processes) { - if (!Object.prototype.hasOwnProperty.call(processes, name)) continue; - yield name; - } -} -/** -* Prepare the set of tasks that will make up the next Pregel step. -* This is the union of all PUSH tasks (Sends) and PULL tasks (nodes triggered -* by edges). -*/ -function _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { - const tasks = {}; - const tasksChannel = channels[constants_TASKS]; - if (tasksChannel?.isAvailable()) { - const len = tasksChannel.get().length; - for (let i = 0; i < len; i += 1) { - const task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config, forExecution, extra); - if (task !== void 0) tasks[task.id] = task; - } - } - for (const name of candidateNodes(checkpoint, processes, extra)) { - const task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config, forExecution, extra); - if (task !== void 0) tasks[task.id] = task; - } - return tasks; -} -/** -* Prepares a single task for the next Pregel step, given a task path, which -* uniquely identifies a PUSH or PULL task within the graph. -*/ -function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { - const { step, checkpointer, manager } = extra; - const configurable = config.configurable ?? {}; - const parentNamespace = configurable.checkpoint_ns ?? ""; - if (taskPath[0] === PUSH && isCall(taskPath[taskPath.length - 1])) { - const call = taskPath[taskPath.length - 1]; - const proc = getRunnableForFunc(call.name, call.func); - const triggers = [PUSH]; - const checkpointNamespace = parentNamespace === "" ? call.name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${call.name}`; - const id = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - call.name, - PUSH, - taskPath[1], - taskPath[2] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${id}`; - const outputTaskPath = [...taskPath.slice(0, 3), true]; - const metadata = { - langgraph_step: step, - langgraph_node: call.name, - langgraph_triggers: triggers, - langgraph_path: outputTaskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const writes = []; - const task = { - name: call.name, - input: call.input, - proc, - writes, - config: config_patchConfig(mergeConfigs(config, { - metadata, - store: extra.store ?? config.store - }), { - runName: call.name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: id, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name: call.name, - writes, - triggers, - path: outputTaskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId: id, - currentTaskInput: call.input, - resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: void 0, - checkpoint_ns: taskCheckpointNamespace - } - }), - triggers, - retry_policy: call.retry, - cache_key: call.cache ? { - key: XXH3((call.cache.keyFunc ?? JSON.stringify)([call.input])), - ns: [CACHE_NS_WRITES, call.name ?? "__dynamic__"], - ttl: call.cache.ttl - } : void 0, - id, - path: outputTaskPath, - writers: [] - }; - return task; - } else return { - id, - name: call.name, - interrupts: [], - path: outputTaskPath - }; - } else if (taskPath[0] === PUSH) { - const index = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); - if (!channels[constants_TASKS]?.isAvailable()) return void 0; - const sends = channels[constants_TASKS].get(); - if (index < 0 || index >= sends.length) return void 0; - const packet = _isSendInterface(sends[index]) && !_isSend(sends[index]) ? new Send(sends[index].node, sends[index].args) : sends[index]; - if (!_isSendInterface(packet)) { - console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); - return void 0; - } - if (!(packet.node in processes)) { - console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); - return void 0; - } - const triggers = [PUSH]; - const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${packet.node}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - packet.node, - PUSH, - index.toString() - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: packet.node, - langgraph_triggers: triggers, - langgraph_path: taskPath.slice(0, 3), - langgraph_checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const proc = processes[packet.node]; - const node = proc.getNode(); - if (node !== void 0) { - if (proc.metadata !== void 0) metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - return { - name: packet.node, - input: packet.args, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: config_patchConfig(mergeConfigs(config, { - metadata, - tags: proc.tags, - store: extra.store ?? config.store - }), { - runName: packet.node, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: taskId, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name: packet.node, - writes, - triggers, - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: packet.args, - resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: void 0, - checkpoint_ns: taskCheckpointNamespace - } - }), - triggers, - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), - ns: [ - CACHE_NS_WRITES, - proc.name ?? "__dynamic__", - packet.node - ], - ttl: proc.cachePolicy.ttl - } : void 0, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else return { - id: taskId, - name: packet.node, - interrupts: [], - path: taskPath - }; - } else if (taskPath[0] === PULL) { - const name = taskPath[1].toString(); - const proc = processes[name]; - if (proc === void 0) return void 0; - if (pendingWrites?.length) { - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL, - name - ]), checkpoint.id); - const hasSuccessfulWrites = pendingWrites.some((w) => w[0] === taskId && w[1] !== constants_ERROR); - if (hasSuccessfulWrites) return void 0; - } - const nullVersion = getNullChannelVersion(checkpoint.channel_versions); - if (nullVersion === void 0) return void 0; - const seen = checkpoint.versions_seen[name] ?? {}; - const trigger = proc.triggers.find((chan) => { - if (!channels[chan].isAvailable()) return false; - return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); - }); - if (trigger !== void 0) { - const val = _procInput(proc, channels, forExecution); - if (val === void 0) return void 0; - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL, - [trigger] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: name, - langgraph_triggers: [trigger], - langgraph_path: taskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const node = proc.getNode(); - if (node !== void 0) { - if (proc.metadata !== void 0) metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - return { - name, - input: val, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: config_patchConfig(mergeConfigs(config, { - metadata, - tags: proc.tags, - store: extra.store ?? config.store - }), { - runName: name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: taskId, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => { - writes.push(...items); - }, processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name, - writes, - triggers: [trigger], - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: val, - resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: void 0, - checkpoint_ns: taskCheckpointNamespace - } - }), - triggers: [trigger], - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), - ns: [ - CACHE_NS_WRITES, - proc.name ?? "__dynamic__", - name - ], - ttl: proc.cachePolicy.ttl - } : void 0, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else return { - id: taskId, - name, - interrupts: [], - path: taskPath - }; - } - } - return void 0; -} -/** -* Function injected under CONFIG_KEY_READ in task config, to read current state. -* Used by conditional edges to read a copy of the state with reflecting the writes -* from that node only. -* -* @internal -*/ -function _procInput(proc, channels, forExecution) { - let val; - if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { - val = {}; - for (const [k, chan] of Object.entries(proc.channels)) if (proc.triggers.includes(chan)) try { - val[k] = readChannel(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) return void 0; - else throw e; - } - else if (chan in channels) try { - val[k] = readChannel(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) continue; - else throw e; - } - } else if (Array.isArray(proc.channels)) { - let successfulRead = false; - for (const chan of proc.channels) try { - val = readChannel(channels, chan, false); - successfulRead = true; - break; - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) continue; - else throw e; - } - if (!successfulRead) return void 0; - } else throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); - if (forExecution && proc.mapper !== void 0) val = proc.mapper(val); - return val; -} -function _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { - const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === constants_RESUME)?.[2]; - const resume = (() => { - const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === constants_RESUME).flatMap(([_writeTaskId, _chan, resume$1]) => resume$1); - if (resumeMap != null && namespaceHash in resumeMap) { - const mappedResume = resumeMap[namespaceHash]; - result.push(mappedResume); - } - return result; - })(); - const scratchpad = { - callCounter: 0, - interruptCounter: -1, - resume, - nullResume, - subgraphCounter: 0, - currentTaskInput, - consumeNullResume: () => { - if (scratchpad.nullResume) { - delete scratchpad.nullResume; - pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === constants_RESUME), 1); - return nullResume; - } - return void 0; - } - }; - return scratchpad; -} - -//#endregion - -//# sourceMappingURL=algo.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/debug.js - - - - -//#region src/pregel/debug.ts -const COLORS_MAP = { - blue: { - start: "\x1B[34m", - end: "\x1B[0m" - }, - green: { - start: "\x1B[32m", - end: "\x1B[0m" - }, - yellow: { - start: "\x1B[33;1m", - end: "\x1B[0m" - } -}; -/** -* Wrap some text in a color for printing to the console. -*/ -const debug_wrap = (color, text) => `${color.start}${text}${color.end}`; -function* mapDebugTasks(tasks) { - for (const { id, name, input, config, triggers, writes } of tasks) { - if (config?.tags?.includes(TAG_HIDDEN)) continue; - const interrupts = writes.filter(([writeId, n]) => { - return writeId === id && n === constants_INTERRUPT; - }).map(([, v]) => { - return v; - }); - yield { - id, - name, - input, - triggers, - interrupts - }; - } -} -function isMultipleChannelWrite(value) { - if (typeof value !== "object" || value === null) return false; - return "$writes" in value && Array.isArray(value.$writes); -} -function mapTaskResultWrites(writes) { - const result = {}; - for (const [channel, value] of writes) { - const strChannel = String(channel); - if (strChannel in result) { - const channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; - channelWrites.push(value); - result[strChannel] = { $writes: channelWrites }; - } else result[strChannel] = value; - } - return result; -} -function* mapDebugTaskResults(tasks, streamChannels) { - for (const [{ id, name, config }, writes] of tasks) { - if (config?.tags?.includes(TAG_HIDDEN)) continue; - yield { - id, - name, - result: mapTaskResultWrites(writes.filter(([channel]) => { - return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; - })), - interrupts: writes.filter((w) => w[0] === constants_INTERRUPT).map((w) => w[1]) - }; - } -} -function* mapDebugCheckpoint(config, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { - function formatConfig(config$1) { - const pyConfig = {}; - if (config$1.callbacks != null) pyConfig.callbacks = config$1.callbacks; - if (config$1.configurable != null) pyConfig.configurable = config$1.configurable; - if (config$1.maxConcurrency != null) pyConfig.max_concurrency = config$1.maxConcurrency; - if (config$1.metadata != null) pyConfig.metadata = config$1.metadata; - if (config$1.recursionLimit != null) pyConfig.recursion_limit = config$1.recursionLimit; - if (config$1.runId != null) pyConfig.run_id = config$1.runId; - if (config$1.runName != null) pyConfig.run_name = config$1.runName; - if (config$1.tags != null) pyConfig.tags = config$1.tags; - return pyConfig; - } - const parentNs = config.configurable?.checkpoint_ns; - const taskStates = {}; - for (const task of tasks) { - const candidates = task.subgraphs?.length ? task.subgraphs : [task.proc]; - if (!candidates.find(findSubgraphPregel)) continue; - let taskNs = `${task.name}:${task.id}`; - if (parentNs) taskNs = `${parentNs}|${taskNs}`; - taskStates[task.id] = { configurable: { - thread_id: config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - } - yield { - config: formatConfig(config), - values: readChannels(channels, streamChannels), - metadata, - next: tasks.map((task) => task.name), - tasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys), - parentConfig: parentConfig ? formatConfig(parentConfig) : void 0 - }; -} -function tasksWithWrites(tasks, pendingWrites, states, outputKeys) { - return tasks.map((task) => { - const error = pendingWrites.find(([id, n]) => id === task.id && n === constants_ERROR)?.[2]; - const interrupts = pendingWrites.filter(([id, n]) => id === task.id && n === constants_INTERRUPT).map(([, , v]) => v); - const result = (() => { - if (error || interrupts.length || !pendingWrites.length) return void 0; - const idx = pendingWrites.findIndex(([tid, n]) => tid === task.id && n === RETURN); - if (idx >= 0) return pendingWrites[idx][2]; - if (typeof outputKeys === "string") return pendingWrites.find(([tid, n]) => tid === task.id && n === outputKeys)?.[2]; - if (Array.isArray(outputKeys)) { - const results = pendingWrites.filter(([tid, n]) => tid === task.id && outputKeys.includes(n)).map(([, n, v]) => [n, v]); - if (!results.length) return void 0; - return mapTaskResultWrites(results); - } - return void 0; - })(); - if (error) return { - id: task.id, - name: task.name, - path: task.path, - error, - interrupts, - result - }; - const taskState = states?.[task.id]; - return { - id: task.id, - name: task.name, - path: task.path, - interrupts, - ...taskState !== void 0 ? { state: taskState } : {}, - result - }; - }); -} -function printStepCheckpoint(step, channels, whitelist) { - console.log([ - `${debug_wrap(COLORS_MAP.blue, `[${step}:checkpoint]`)}`, - `\x1b[1m State at the end of step ${step}:\x1b[0m\n`, - JSON.stringify(readChannels(channels, whitelist), null, 2) - ].join("")); -} -function printStepTasks(step, nextTasks) { - const nTasks = nextTasks.length; - console.log([ - `${debug_wrap(COLORS_MAP.blue, `[${step}:tasks]`)}`, - `\x1b[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1b[0m\n`, - nextTasks.map((task) => `- ${debug_wrap(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join("\n") - ].join("")); -} -function printStepWrites(step, writes, whitelist) { - const byChannel = {}; - for (const [channel, value] of writes) if (whitelist.includes(channel)) { - if (!byChannel[channel]) byChannel[channel] = []; - byChannel[channel].push(value); - } - console.log([ - `${debug_wrap(COLORS_MAP.blue, `[${step}:writes]`)}`, - `\x1b[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1b[0m\n`, - Object.entries(byChannel).map(([name, vals]) => `- ${debug_wrap(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join("\n") - ].join("")); -} - -//#endregion - -//# sourceMappingURL=debug.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/stream.js - - -//#region src/pregel/stream.ts -/** -* A wrapper around an IterableReadableStream that allows for aborting the stream when -* {@link cancel} is called. -*/ -var IterableReadableStreamWithAbortSignal = class extends IterableReadableStream { - _abortController; - _innerReader; - /** - * @param readableStream - The stream to wrap. - * @param abortController - The abort controller to use. Optional. One will be created if not provided. - */ - constructor(readableStream, abortController) { - const reader = readableStream.getReader(); - const ac = abortController ?? new AbortController(); - super({ start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump(); - }); - } - } }); - this._abortController = ac; - this._innerReader = reader; - } - /** - * Aborts the stream, abandoning any pending operations in progress. Calling this triggers an - * {@link AbortSignal} that is propagated to the tasks that are producing the data for this stream. - * @param reason - The reason for aborting the stream. Optional. - */ - async cancel(reason) { - this._abortController.abort(reason); - this._innerReader.releaseLock(); - } - /** - * The {@link AbortSignal} for the stream. Aborted when {@link cancel} is called. - */ - get signal() { - return this._abortController.signal; - } -}; -var IterableReadableWritableStream = class extends IterableReadableStream { - modes; - controller; - passthroughFn; - _closed = false; - get closed() { - return this._closed; - } - constructor(params) { - let streamControllerPromiseResolver; - const streamControllerPromise = new Promise((resolve) => { - streamControllerPromiseResolver = resolve; - }); - super({ start: (controller) => { - streamControllerPromiseResolver(controller); - } }); - streamControllerPromise.then((controller) => { - this.controller = controller; - }); - this.passthroughFn = params.passthroughFn; - this.modes = params.modes; - } - push(chunk) { - this.passthroughFn?.(chunk); - this.controller.enqueue(chunk); - } - close() { - try { - this.controller.close(); - } catch (e) {} finally { - this._closed = true; - } - } - error(e) { - this.controller.error(e); - } -}; -function _stringifyAsDict(obj) { - return JSON.stringify(obj, function(key, value) { - const rawValue = this[key]; - if (rawValue != null && typeof rawValue === "object" && "toDict" in rawValue && typeof rawValue.toDict === "function") { - const { type, data } = rawValue.toDict(); - return { - ...data, - type - }; - } - return value; - }); -} -function _serializeError(error) { - if (error instanceof Error) return { - error: error.name, - message: error.message - }; - return { - error: "Error", - message: JSON.stringify(error) - }; -} -function _isRunnableConfig(config) { - if (typeof config !== "object" || config == null) return false; - return "configurable" in config && typeof config.configurable === "object" && config.configurable != null; -} -function _extractCheckpointFromConfig(config) { - if (!_isRunnableConfig(config) || !config.configurable.thread_id) return null; - return { - thread_id: config.configurable.thread_id, - checkpoint_ns: config.configurable.checkpoint_ns || "", - checkpoint_id: config.configurable.checkpoint_id || null, - checkpoint_map: config.configurable.checkpoint_map || null - }; -} -function _serializeConfig(config) { - if (_isRunnableConfig(config)) { - const configurable = Object.fromEntries(Object.entries(config.configurable).filter(([key]) => !key.startsWith("__"))); - const newConfig = { - ...config, - configurable - }; - delete newConfig.callbacks; - return newConfig; - } - return config; -} -function _serializeCheckpoint(payload) { - const result = { - ...payload, - checkpoint: _extractCheckpointFromConfig(payload.config), - parent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig), - config: _serializeConfig(payload.config), - parent_config: _serializeConfig(payload.parentConfig), - tasks: payload.tasks.map((task) => { - if (_isRunnableConfig(task.state)) { - const checkpoint = _extractCheckpointFromConfig(task.state); - if (checkpoint != null) { - const cloneTask = { - ...task, - checkpoint - }; - delete cloneTask.state; - return cloneTask; - } - } - return task; - }) - }; - delete result.parentConfig; - return result; -} -function toEventStream(stream) { - const encoder = new TextEncoder(); - return new ReadableStream({ async start(controller) { - const enqueueChunk = (sse) => { - controller.enqueue(encoder.encode(`event: ${sse.event}\ndata: ${_stringifyAsDict(sse.data)}\n\n`)); - }; - try { - for await (const payload of stream) { - const [ns, mode, chunk] = payload; - let data = chunk; - if (mode === "debug") { - const debugChunk = chunk; - if (debugChunk.type === "checkpoint") data = { - ...debugChunk, - payload: _serializeCheckpoint(debugChunk.payload) - }; - } - if (mode === "checkpoints") data = _serializeCheckpoint(chunk); - const event = ns?.length ? `${mode}|${ns.join("|")}` : mode; - enqueueChunk({ - event, - data - }); - } - } catch (error) { - enqueueChunk({ - event: "error", - data: _serializeError(error) - }); - } - controller.close(); - } }); -} - -//#endregion - -//# sourceMappingURL=stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/loop.js - - - - - - - - - - - - -//#region src/pregel/loop.ts -const INPUT_DONE = Symbol.for("INPUT_DONE"); -const INPUT_RESUMING = Symbol.for("INPUT_RESUMING"); -const DEFAULT_LOOP_LIMIT = 25; -function createDuplexStream(...streams) { - return new IterableReadableWritableStream({ - passthroughFn: (value) => { - for (const stream of streams) if (stream.modes.has(value[1])) stream.push(value); - }, - modes: new Set(streams.flatMap((s) => Array.from(s.modes))) - }); -} -var AsyncBatchedCache = class extends cache_base_BaseCache { - cache; - queue = Promise.resolve(); - constructor(cache) { - super(); - this.cache = cache; - } - async get(keys) { - return this.enqueueOperation("get", keys); - } - async set(pairs) { - return this.enqueueOperation("set", pairs); - } - async clear(namespaces) { - return this.enqueueOperation("clear", namespaces); - } - async stop() { - await this.queue; - } - enqueueOperation(type, ...args) { - const newPromise = this.queue.then(() => { - return this.cache[type](...args); - }); - this.queue = newPromise.then(() => void 0, () => void 0); - return newPromise; - } -}; -var PregelLoop = class PregelLoop { - input; - output; - config; - checkpointer; - checkpointerGetNextVersion; - channels; - checkpoint; - checkpointIdSaved; - checkpointConfig; - checkpointMetadata; - checkpointNamespace; - checkpointPendingWrites = []; - checkpointPreviousVersions; - step; - stop; - durability; - outputKeys; - streamKeys; - nodes; - skipDoneTasks; - prevCheckpointConfig; - updatedChannels; - status = "pending"; - tasks = {}; - stream; - checkpointerPromises = []; - isNested; - _checkpointerChainedPromise = Promise.resolve(); - store; - cache; - manager; - interruptAfter; - interruptBefore; - toInterrupt = []; - debug = false; - triggerToNodes; - get isResuming() { - let hasChannelVersions = false; - if (START in this.checkpoint.channel_versions) hasChannelVersions = true; - else for (const chan in this.checkpoint.channel_versions) if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { - hasChannelVersions = true; - break; - } - const configHasResumingFlag = this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0; - const configIsResuming = configHasResumingFlag && this.config.configurable?.[CONFIG_KEY_RESUMING]; - const inputIsNullOrUndefined = this.input === null || this.input === void 0; - const inputIsCommandResuming = isCommand(this.input) && this.input.resume != null; - const inputIsResuming = this.input === INPUT_RESUMING; - const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== void 0 && this.checkpointMetadata?.run_id !== void 0 && this.config.metadata.run_id === this.checkpointMetadata?.run_id; - return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); - } - constructor(params) { - this.input = params.input; - this.checkpointer = params.checkpointer; - if (this.checkpointer !== void 0) this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); - else this.checkpointerGetNextVersion = increment; - this.checkpoint = params.checkpoint; - this.checkpointMetadata = params.checkpointMetadata; - this.checkpointPreviousVersions = params.checkpointPreviousVersions; - this.channels = params.channels; - this.checkpointPendingWrites = params.checkpointPendingWrites; - this.step = params.step; - this.stop = params.stop; - this.config = params.config; - this.checkpointConfig = params.checkpointConfig; - this.isNested = params.isNested; - this.manager = params.manager; - this.outputKeys = params.outputKeys; - this.streamKeys = params.streamKeys; - this.nodes = params.nodes; - this.skipDoneTasks = params.skipDoneTasks; - this.store = params.store; - this.cache = params.cache ? new AsyncBatchedCache(params.cache) : void 0; - this.stream = params.stream; - this.checkpointNamespace = params.checkpointNamespace; - this.prevCheckpointConfig = params.prevCheckpointConfig; - this.interruptAfter = params.interruptAfter; - this.interruptBefore = params.interruptBefore; - this.durability = params.durability; - this.debug = params.debug; - this.triggerToNodes = params.triggerToNodes; - } - static async initialize(params) { - let { config, stream } = params; - if (stream !== void 0 && config.configurable?.[CONFIG_KEY_STREAM] !== void 0) stream = createDuplexStream(stream, config.configurable[CONFIG_KEY_STREAM]); - const skipDoneTasks = config.configurable ? !("checkpoint_id" in config.configurable) : true; - const scratchpad = config.configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; - if (config.configurable && scratchpad) { - if (scratchpad.subgraphCounter > 0) config = utils_patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_NS]: [config.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join(CHECKPOINT_NAMESPACE_SEPARATOR) }); - scratchpad.subgraphCounter += 1; - } - const isNested = CONFIG_KEY_READ in (config.configurable ?? {}); - if (!isNested && config.configurable?.checkpoint_ns !== void 0 && config.configurable?.checkpoint_ns !== "") config = utils_patchConfigurable(config, { - checkpoint_ns: "", - checkpoint_id: void 0 - }); - let checkpointConfig = config; - if (config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP]?.[config.configurable?.checkpoint_ns]) checkpointConfig = utils_patchConfigurable(config, { checkpoint_id: config.configurable[CONFIG_KEY_CHECKPOINT_MAP][config.configurable?.checkpoint_ns] }); - const checkpointNamespace = config.configurable?.checkpoint_ns?.split(CHECKPOINT_NAMESPACE_SEPARATOR) ?? []; - const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { - config, - checkpoint: emptyCheckpoint(), - metadata: { - source: "input", - step: -2, - parents: {} - }, - pendingWrites: [] - }; - checkpointConfig = { - ...config, - ...saved.config, - configurable: { - checkpoint_ns: "", - ...config.configurable, - ...saved.config.configurable - } - }; - const prevCheckpointConfig = saved.parentConfig; - const checkpoint = copyCheckpoint(saved.checkpoint); - const checkpointMetadata = { ...saved.metadata }; - const checkpointPendingWrites = saved.pendingWrites ?? []; - const channels = emptyChannels(params.channelSpecs, checkpoint); - const step = (checkpointMetadata.step ?? 0) + 1; - const stop = step + (config.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1; - const checkpointPreviousVersions = { ...checkpoint.channel_versions }; - const store = params.store ? new AsyncBatchedStore(params.store) : void 0; - if (store) await store.start(); - return new PregelLoop({ - input: params.input, - config, - checkpointer: params.checkpointer, - checkpoint, - checkpointMetadata, - checkpointConfig, - prevCheckpointConfig, - checkpointNamespace, - channels, - isNested, - manager: params.manager, - skipDoneTasks, - step, - stop, - checkpointPreviousVersions, - checkpointPendingWrites, - outputKeys: params.outputKeys ?? [], - streamKeys: params.streamKeys ?? [], - nodes: params.nodes, - stream, - store, - cache: params.cache, - interruptAfter: params.interruptAfter, - interruptBefore: params.interruptBefore, - durability: params.durability, - debug: params.debug, - triggerToNodes: params.triggerToNodes - }); - } - _checkpointerPutAfterPrevious(input) { - this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { - return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); - }); - this.checkpointerPromises.push(this._checkpointerChainedPromise); - } - /** - * Put writes for a task, to be read by the next tick. - * @param taskId - * @param writes - */ - putWrites(taskId, writes) { - let writesCopy = writes; - if (writesCopy.length === 0) return; - if (writesCopy.every(([key]) => key in WRITES_IDX_MAP)) writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); - this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); - for (const [c, v] of writesCopy) this.checkpointPendingWrites.push([ - taskId, - c, - v - ]); - const config = utils_patchConfigurable(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id - }); - if (this.durability !== "exit" && this.checkpointer != null) this.checkpointerPromises.push(this.checkpointer.putWrites(config, writesCopy, taskId)); - if (this.tasks) this._outputWrites(taskId, writesCopy); - if (!writes.length || !this.cache || !this.tasks) return; - const task = this.tasks[taskId]; - if (task == null || task.cache_key == null) return; - if (writes[0][0] === constants_ERROR || writes[0][0] === constants_INTERRUPT) return; - this.cache.set([{ - key: [task.cache_key.ns, task.cache_key.key], - value: task.writes, - ttl: task.cache_key.ttl - }]); - } - _outputWrites(taskId, writes, cached = false) { - const task = this.tasks[taskId]; - if (task !== void 0) { - if (task.config !== void 0 && (task.config.tags ?? []).includes(TAG_HIDDEN)) return; - if (writes.length > 0) { - if (writes[0][0] === constants_INTERRUPT) { - if (task.path?.[0] === PUSH && task.path?.at(-1) === true) return; - const interruptWrites = writes.filter((w) => w[0] === constants_INTERRUPT).flatMap((w) => w[1]); - this._emit([["updates", { [constants_INTERRUPT]: interruptWrites }], ["values", { [constants_INTERRUPT]: interruptWrites }]]); - } else if (writes[0][0] !== constants_ERROR) this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached), "updates"))); - } - if (!cached) this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), "tasks"))); - } - } - async _matchCachedWrites() { - if (!this.cache) return []; - const matched = []; - const serializeKey = ([ns, key]) => { - return `ns:${ns.join(",")}|key:${key}`; - }; - const keys = []; - const keyMap = {}; - for (const task of Object.values(this.tasks)) if (task.cache_key != null && !task.writes.length) { - keys.push([task.cache_key.ns, task.cache_key.key]); - keyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task; - } - if (keys.length === 0) return []; - const cache = await this.cache.get(keys); - for (const { key, value } of cache) { - const task = keyMap[serializeKey(key)]; - if (task != null) { - task.writes.push(...value); - matched.push({ - task, - result: value - }); - } - } - return matched; - } - /** - * Execute a single iteration of the Pregel loop. - * Returns true if more iterations are needed. - * @param params - */ - async tick(params) { - if (this.store && !this.store.isRunning) await this.store?.start(); - const { inputKeys = [] } = params; - if (this.status !== "pending") throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); - if (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) await this._first(inputKeys); - else if (this.toInterrupt.length > 0) { - this.status = "interrupt_before"; - throw new GraphInterrupt(); - } else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) { - const writes = Object.values(this.tasks).flatMap((t) => t.writes); - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), "values")); - this._emit(valuesOutput); - this.checkpointPendingWrites = []; - await this._putCheckpoint({ source: "loop" }); - if (shouldInterrupt(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { - this.status = "interrupt_after"; - throw new GraphInterrupt(); - } - if (this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0) delete this.config.configurable?.[CONFIG_KEY_RESUMING]; - } else return false; - if (this.step > this.stop) { - this.status = "out_of_steps"; - return false; - } - const nextTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { - step: this.step, - checkpointer: this.checkpointer, - isResuming: this.isResuming, - manager: this.manager, - store: this.store, - stream: this.stream, - triggerToNodes: this.triggerToNodes, - updatedChannels: this.updatedChannels - }); - this.tasks = nextTasks; - if (this.checkpointer) this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); - if (Object.values(this.tasks).length === 0) { - this.status = "done"; - return false; - } - if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === constants_ERROR || k === constants_INTERRUPT || k === constants_RESUME) continue; - const task = Object.values(this.tasks).find((t) => t.id === tid); - if (task) task.writes.push([k, v]); - } - for (const task of Object.values(this.tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); - } - if (Object.values(this.tasks).every((task) => task.writes.length > 0)) return this.tick({ inputKeys }); - if (shouldInterrupt(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { - this.status = "interrupt_before"; - throw new GraphInterrupt(); - } - const debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(Object.values(this.tasks)), "tasks")); - this._emit(debugOutput); - return true; - } - async finishAndHandleError(error) { - if (this.durability === "exit" && (!this.isNested || typeof error !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(CHECKPOINT_NAMESPACE_END)))) { - this._putCheckpoint(this.checkpointMetadata); - this._flushPendingWrites(); - } - const suppress = this._suppressInterrupt(error); - if (suppress || error === void 0) this.output = readChannels(this.channels, this.outputKeys); - if (suppress) { - if (this.tasks !== void 0 && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) { - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - this._emit(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); - } - if (isGraphInterrupt(error) && !error.interrupts.length) this._emit([["updates", { [constants_INTERRUPT]: [] }], ["values", { [constants_INTERRUPT]: [] }]]); - } - return suppress; - } - async acceptPush(task, writeIdx, call) { - if (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) { - this.toInterrupt.push(task); - return; - } - const pushed = _prepareSingleTask([ - PUSH, - task.path ?? [], - writeIdx, - task.id, - call - ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, { - step: this.step, - checkpointer: this.checkpointer, - manager: this.manager, - store: this.store, - stream: this.stream - }); - if (!pushed) return; - if (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) { - this.toInterrupt.push(pushed); - return; - } - this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), "tasks"))); - if (this.debug) printStepTasks(this.step, [pushed]); - this.tasks[pushed.id] = pushed; - if (this.skipDoneTasks) this._matchWrites({ [pushed.id]: pushed }); - const tasks = await this._matchCachedWrites(); - for (const { task: task$1 } of tasks) this._outputWrites(task$1.id, task$1.writes, true); - return pushed; - } - _suppressInterrupt(e) { - return isGraphInterrupt(e) && !this.isNested; - } - async _first(inputKeys) { - const { configurable } = this.config; - const scratchpad = configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; - if (scratchpad && scratchpad.nullResume !== void 0) this.putWrites(NULL_TASK_ID, [[constants_RESUME, scratchpad.nullResume]]); - if (isCommand(this.input)) { - const hasResume = this.input.resume != null; - if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH3)) { - this.config.configurable ??= {}; - this.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume; - } - if (hasResume && this.checkpointer == null) throw new Error("Cannot use Command(resume=...) without checkpointer"); - const writes = {}; - for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) { - writes[tid] ??= []; - writes[tid].push([key, value]); - } - if (Object.keys(writes).length === 0) throw new EmptyInputError("Received empty Command input"); - for (const [tid, ws] of Object.entries(writes)) this.putWrites(tid, ws); - } - const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) _applyWrites(this.checkpoint, this.channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], this.checkpointerGetNextVersion, this.triggerToNodes); - const isCommandUpdateOrGoto = isCommand(this.input) && nullWrites.length > 0; - if (this.isResuming || isCommandUpdateOrGoto) { - for (const channelName in this.channels) { - if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) continue; - if (this.checkpoint.channel_versions[channelName] !== void 0) { - const version = this.checkpoint.channel_versions[channelName]; - this.checkpoint.versions_seen[constants_INTERRUPT] = { - ...this.checkpoint.versions_seen[constants_INTERRUPT], - [channelName]: version - }; - } - } - const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), "values")); - this._emit(valuesOutput); - } - if (this.isResuming) this.input = INPUT_RESUMING; - else if (isCommandUpdateOrGoto) { - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE; - } else { - const inputWrites = await gatherIterator(mapInput(inputKeys, this.input)); - if (inputWrites.length > 0) { - const discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ - name: INPUT, - writes: inputWrites, - triggers: [] - }]), this.checkpointerGetNextVersion, this.triggerToNodes); - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE; - } else if (!(CONFIG_KEY_RESUMING in (this.config.configurable ?? {}))) throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); - else this.input = INPUT_DONE; - } - if (!this.isNested) this.config = utils_patchConfigurable(this.config, { [CONFIG_KEY_RESUMING]: this.isResuming }); - } - _emit(values) { - for (const [mode, payload] of values) { - if (this.stream.modes.has(mode)) this.stream.push([ - this.checkpointNamespace, - mode, - payload - ]); - if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { - const step = mode === "checkpoints" ? this.step - 1 : this.step; - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - const type = (() => { - if (mode === "checkpoints") return "checkpoint"; - else if (typeof payload === "object" && payload != null && "result" in payload) return "task_result"; - else return "task"; - })(); - this.stream.push([ - this.checkpointNamespace, - "debug", - { - step, - type, - timestamp, - payload - } - ]); - } - } - } - _putCheckpoint(inputMetadata) { - const exiting = this.checkpointMetadata === inputMetadata; - const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); - const storeCheckpoint = (checkpoint) => { - this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : void 0; - this.checkpointConfig = utils_patchConfigurable(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "" }); - const channelVersions = { ...this.checkpoint.channel_versions }; - const newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions); - this.checkpointPreviousVersions = channelVersions; - this._checkpointerPutAfterPrevious({ - config: { ...this.checkpointConfig }, - checkpoint: copyCheckpoint(checkpoint), - metadata: { ...this.checkpointMetadata }, - newVersions - }); - this.checkpointConfig = { - ...this.checkpointConfig, - configurable: { - ...this.checkpointConfig.configurable, - checkpoint_id: this.checkpoint.id - } - }; - }; - if (!exiting) this.checkpointMetadata = { - ...inputMetadata, - step: this.step, - parents: this.config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] ?? {} - }; - this.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : void 0, this.step, exiting ? { id: this.checkpoint.id } : void 0); - if (doCheckpoint) storeCheckpoint(this.checkpoint); - if (!exiting) this.step += 1; - } - _flushPendingWrites() { - if (this.checkpointer == null) return; - if (this.checkpointPendingWrites.length === 0) return; - const config = utils_patchConfigurable(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id - }); - const byTask = {}; - for (const [tid, key, value] of this.checkpointPendingWrites) { - byTask[tid] ??= []; - byTask[tid].push([key, value]); - } - for (const [tid, ws] of Object.entries(byTask)) this.checkpointerPromises.push(this.checkpointer.putWrites(config, ws, tid)); - } - _matchWrites(tasks) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === constants_ERROR || k === constants_INTERRUPT || k === constants_RESUME) continue; - const task = Object.values(tasks).find((t) => t.id === tid); - if (task) task.writes.push([k, v]); - } - for (const task of Object.values(tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); - } -}; - -//#endregion - -//# sourceMappingURL=loop.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/messages.js - - - - -//#region src/pregel/messages.ts -function messages_isChatGenerationChunk(x) { - return isBaseMessage(x?.message); -} -/** -* A callback handler that implements stream_mode=messages. -* Collects messages from (1) chat model stream events and (2) node outputs. -*/ -var StreamMessagesHandler = class extends BaseCallbackHandler { - name = "StreamMessagesHandler"; - streamFn; - metadatas = {}; - seen = {}; - emittedChatModelRunIds = {}; - stableMessageIdMap = {}; - lc_prefer_streaming = true; - constructor(streamFn) { - super(); - this.streamFn = streamFn; - } - _emit(meta, message, runId, dedupe = false) { - if (dedupe && message.id !== void 0 && this.seen[message.id] !== void 0) return; - let messageId = message.id; - if (runId != null) if (isToolMessage(message)) messageId ??= `run-${runId}-tool-${message.tool_call_id}`; - else { - if (messageId == null || messageId === `run-${runId}`) messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; - this.stableMessageIdMap[runId] ??= messageId; - } - if (messageId !== message.id) { - message.id = messageId; - message.lc_kwargs.id = messageId; - } - if (message.id != null) this.seen[message.id] = message; - this.streamFn([ - meta[0], - "messages", - [message, meta[1]] - ]); - } - handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { - if (metadata && (!tags || !tags.includes(TAG_NOSTREAM) && !tags.includes("nostream"))) this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; - } - handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { - const chunk = fields?.chunk; - this.emittedChatModelRunIds[runId] = true; - if (this.metadatas[runId] !== void 0) if (messages_isChatGenerationChunk(chunk)) this._emit(this.metadatas[runId], chunk.message, runId); - else this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); - } - handleLLMEnd(output, runId) { - if (this.metadatas[runId] === void 0) return; - if (!this.emittedChatModelRunIds[runId]) { - const chatGeneration = output.generations?.[0]?.[0]; - if (isBaseMessage(chatGeneration?.message)) this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); - delete this.emittedChatModelRunIds[runId]; - } - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; - } - handleLLMError(_err, runId) { - delete this.metadatas[runId]; - } - handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { - if (metadata !== void 0 && name === metadata.langgraph_node && (tags === void 0 || !tags.includes(TAG_HIDDEN))) { - this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; - if (typeof inputs === "object") { - for (const value of Object.values(inputs)) if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== void 0) this.seen[value.id] = value; - else if (Array.isArray(value)) { - for (const item of value) if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== void 0) this.seen[item.id] = item; - } - } - } - } - handleChainEnd(outputs, runId) { - const metadata = this.metadatas[runId]; - delete this.metadatas[runId]; - if (metadata !== void 0) { - if (isBaseMessage(outputs)) this._emit(metadata, outputs, runId, true); - else if (Array.isArray(outputs)) { - for (const value of outputs) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); - } else if (outputs != null && typeof outputs === "object") { - for (const value of Object.values(outputs)) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); - else if (Array.isArray(value)) { - for (const item of value) if (isBaseMessage(item)) this._emit(metadata, item, runId, true); - } - } - } - } - handleChainError(_err, runId) { - delete this.metadatas[runId]; - } -}; - -//#endregion - -//# sourceMappingURL=messages.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/retry.js - - - - - -//#region src/pregel/retry.ts -const DEFAULT_INITIAL_INTERVAL = 500; -const DEFAULT_BACKOFF_FACTOR = 2; -const DEFAULT_MAX_INTERVAL = 128e3; -const DEFAULT_MAX_RETRIES = 3; -const DEFAULT_STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 -]; -const DEFAULT_RETRY_ON_HANDLER = (error) => { - if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") return false; - if (error.name === "GraphValueError") return false; - if (error?.code === "ECONNABORTED") return false; - const status = error?.response?.status ?? error?.status; - if (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) return false; - if (error?.error?.code === "insufficient_quota") return false; - return true; -}; -async function _runWithRetry(pregelTask, retryPolicy, configurable, signal) { - const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; - let interval = resolvedRetryPolicy !== void 0 ? resolvedRetryPolicy.initialInterval ?? DEFAULT_INITIAL_INTERVAL : 0; - let attempts = 0; - let error; - let result; - let { config } = pregelTask; - if (configurable) config = utils_patchConfigurable(config, configurable); - config = { - ...config, - signal - }; - while (true) { - if (signal?.aborted) break; - pregelTask.writes.splice(0, pregelTask.writes.length); - error = void 0; - try { - result = await pregelTask.proc.invoke(pregelTask.input, config); - break; - } catch (e) { - error = e; - error.pregelTaskId = pregelTask.id; - if (isParentCommand(error)) { - const ns = config?.configurable?.checkpoint_ns; - const cmd = error.command; - if (cmd.graph === ns) { - for (const writer of pregelTask.writers) await writer.invoke(cmd, config); - error = void 0; - break; - } else if (cmd.graph === Command.PARENT) { - const parentNs = getParentCheckpointNamespace(ns); - error.command = new Command({ - ...error.command, - graph: parentNs - }); - } - } - if (isGraphBubbleUp(error)) break; - if (resolvedRetryPolicy === void 0) break; - attempts += 1; - if (attempts >= (resolvedRetryPolicy.maxAttempts ?? DEFAULT_MAX_RETRIES)) break; - const retryOn = resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER; - if (!retryOn(error)) break; - interval = Math.min(resolvedRetryPolicy.maxInterval ?? DEFAULT_MAX_INTERVAL, interval * (resolvedRetryPolicy.backoffFactor ?? DEFAULT_BACKOFF_FACTOR)); - const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1e3) : interval; - await new Promise((resolve) => setTimeout(resolve, intervalWithJitter)); - const errorName = error.name ?? error.constructor.unminifiable_name ?? error.constructor.name; - if (resolvedRetryPolicy?.logWarning ?? true) console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error}`); - config = utils_patchConfigurable(config, { [CONFIG_KEY_RESUMING]: true }); - } - } - return { - task: pregelTask, - result, - error, - signalAborted: signal?.aborted - }; -} - -//#endregion - -//# sourceMappingURL=retry.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/runner.js - - - - - - -//#region src/pregel/runner.ts -const PROMISE_ADDED_SYMBOL = Symbol.for("promiseAdded"); -function createPromiseBarrier() { - const barrier = { - next: () => void 0, - wait: Promise.resolve(PROMISE_ADDED_SYMBOL) - }; - function waitHandler(resolve) { - barrier.next = () => { - barrier.wait = new Promise(waitHandler); - resolve(PROMISE_ADDED_SYMBOL); - }; - } - barrier.wait = new Promise(waitHandler); - return barrier; -} -/** -* Responsible for handling task execution on each tick of the {@link PregelLoop}. -*/ -var PregelRunner = class { - nodeFinished; - loop; - /** - * Construct a new PregelRunner, which executes tasks from the provided PregelLoop. - * @param loop - The PregelLoop that produces tasks for this runner to execute. - */ - constructor({ loop, nodeFinished }) { - this.loop = loop; - this.nodeFinished = nodeFinished; - } - /** - * Execute tasks from the current step of the PregelLoop. - * - * Note: this method does NOT call {@link PregelLoop}#tick. That must be handled externally. - * @param options - Options for the execution. - */ - async tick(options = {}) { - const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; - const nodeErrors = /* @__PURE__ */ new Set(); - let graphBubbleUp; - const exceptionSignalController = new AbortController(); - const exceptionSignal = exceptionSignalController.signal; - const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : void 0; - const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); - const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ - exceptionSignal, - stepTimeoutSignal, - signal: options.signal - }); - const taskStream = this._executeTasksWithRetry(pendingTasks, { - signals, - retryPolicy, - maxConcurrency - }); - for await (const { task, error, signalAborted } of taskStream) { - this._commit(task, error); - if (isGraphInterrupt(error)) graphBubbleUp = error; - else if (isGraphBubbleUp(error) && !isGraphInterrupt(graphBubbleUp)) graphBubbleUp = error; - else if (error && (nodeErrors.size === 0 || !signalAborted)) { - exceptionSignalController.abort(); - nodeErrors.add(error); - } - } - disposeCombinedSignal?.(); - onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task) => task.writes).flat()); - if (nodeErrors.size === 1) throw Array.from(nodeErrors)[0]; - else if (nodeErrors.size > 1) throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); - if (isGraphInterrupt(graphBubbleUp)) throw graphBubbleUp; - if (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) throw graphBubbleUp; - } - /** - * Initializes the current AbortSignals for the PregelRunner, handling the various ways that - * AbortSignals must be chained together so that the PregelLoop can be interrupted if necessary - * while still allowing nodes to gracefully exit. - * - * This method must only be called once per PregelRunner#tick. It has the side effect of updating - * the PregelLoop#config with the new AbortSignals so they may be propagated correctly to future - * ticks and subgraph calls. - * - * @param options - Options for the initialization. - * @returns The current abort signals. - * @internal - */ - _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { - const previousSignals = this.loop.config.configurable?.[CONFIG_KEY_ABORT_SIGNALS] ?? {}; - const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; - const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; - const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal); - const signals = { - externalAbortSignal, - timeoutAbortSignal, - composedAbortSignal - }; - this.loop.config = utils_patchConfigurable(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals }); - return { - signals, - disposeCombinedSignal - }; - } - /** - * Concurrently executes tasks with the requested retry policy, yielding a {@link SettledPregelTask} for each task as it completes. - * @param tasks - The tasks to execute. - * @param options - Options for the execution. - */ - async *_executeTasksWithRetry(tasks, options) { - const { retryPolicy, maxConcurrency, signals } = options ?? {}; - const barrier = createPromiseBarrier(); - const executingTasksMap = {}; - const thisCall = { - executingTasksMap, - barrier, - retryPolicy, - scheduleTask: async (task, writeIdx, call$1) => this.loop.acceptPush(task, writeIdx, call$1) - }; - if (signals?.composedAbortSignal?.aborted) throw new Error("Abort"); - let startedTasksCount = 0; - let listener; - const timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal); - const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { - listener = () => reject(/* @__PURE__ */ new Error("Abort")); - timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); - }) : void 0; - while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { - for (; Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { - const task = tasks[startedTasksCount]; - executingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [constants_CONFIG_KEY_CALL]: runner_call?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error) => { - return { - task, - error, - signalAborted: signals?.composedAbortSignal?.aborted - }; - }); - } - const settledTask = await Promise.race([ - ...Object.values(executingTasksMap), - ...abortPromise ? [abortPromise] : [], - barrier.wait - ]); - if (settledTask === PROMISE_ADDED_SYMBOL) continue; - yield settledTask; - if (listener != null) { - timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); - timeoutOrCancelSignal.dispose?.(); - } - delete executingTasksMap[settledTask.task.id]; - } - } - /** - * Determines what writes to apply based on whether the task completed successfully, and what type of error occurred. - * - * Throws an error if the error is a {@link GraphBubbleUp} error and {@link PregelLoop}#isNested is true. - * - * @param task - The task to commit. - * @param error - The error that occurred, if any. - */ - _commit(task, error) { - if (error !== void 0) if (isGraphInterrupt(error)) { - if (error.interrupts.length) { - const interrupts = error.interrupts.map((interrupt) => [constants_INTERRUPT, interrupt]); - const resumes = task.writes.filter((w) => w[0] === constants_RESUME); - if (resumes.length) interrupts.push(...resumes); - this.loop.putWrites(task.id, interrupts); - } - } else if (isGraphBubbleUp(error) && task.writes.length) this.loop.putWrites(task.id, task.writes); - else this.loop.putWrites(task.id, [[constants_ERROR, { - message: error.message, - name: error.name - }]]); - else { - if (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes(TAG_HIDDEN))) this.nodeFinished(String(task.name)); - if (task.writes.length === 0) task.writes.push([NO_WRITES, null]); - this.loop.putWrites(task.id, task.writes); - } - } -}; -async function runner_call(runner, task, func, name, input, options = {}) { - const scratchpad = task.config?.configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; - if (!scratchpad) throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`); - const cnt = scratchpad.callCounter; - scratchpad.callCounter += 1; - const wcall = new Call({ - func, - name, - input, - cache: options.cache, - retry: options.retry, - callbacks: options.callbacks - }); - const nextTask = await this.scheduleTask(task, cnt, wcall); - if (!nextTask) return void 0; - const existingPromise = this.executingTasksMap[nextTask.id]; - if (existingPromise !== void 0) return existingPromise; - if (nextTask.writes.length > 0) { - const returns = nextTask.writes.filter(([c]) => c === RETURN); - const errors = nextTask.writes.filter(([c]) => c === constants_ERROR); - if (returns.length > 0) { - if (returns.length === 1) return Promise.resolve(returns[0][1]); - throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); - } - if (errors.length > 0) { - if (errors.length === 1) { - const errorValue = errors[0][1]; - const error = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); - return Promise.reject(error); - } - throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); - } - return void 0; - } else { - const prom = _runWithRetry(nextTask, options.retry, { [constants_CONFIG_KEY_CALL]: runner_call.bind(this, runner, nextTask) }); - this.executingTasksMap[nextTask.id] = prom; - this.barrier.next(); - return prom.then(({ result, error }) => { - if (error) return Promise.reject(error); - return result; - }); - } -} - -//#endregion - -//# sourceMappingURL=runner.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/validate.js - - - -//#region src/pregel/validate.ts -var GraphValidationError = class extends Error { - constructor(message) { - super(message); - this.name = "GraphValidationError"; - } -}; -function validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { - if (!channels) throw new GraphValidationError("Channels not provided"); - const subscribedChannels = /* @__PURE__ */ new Set(); - const allOutputChannels = /* @__PURE__ */ new Set(); - for (const [name, node] of Object.entries(nodes)) { - if (name === constants_INTERRUPT) throw new GraphValidationError(`"Node name ${constants_INTERRUPT} is reserved"`); - if (node.constructor === PregelNode) node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); - else throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`); - } - for (const chan of subscribedChannels) if (!(chan in channels)) throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`); - if (!Array.isArray(inputChannels)) { - if (!subscribedChannels.has(inputChannels)) throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`); - } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`); - if (!Array.isArray(outputChannels)) allOutputChannels.add(outputChannels); - else outputChannels.forEach((chan) => allOutputChannels.add(chan)); - if (streamChannels && !Array.isArray(streamChannels)) allOutputChannels.add(streamChannels); - else if (Array.isArray(streamChannels)) streamChannels.forEach((chan) => allOutputChannels.add(chan)); - for (const chan of allOutputChannels) if (!(chan in channels)) throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`); - if (interruptAfterNodes && interruptAfterNodes !== "*") { - for (const node of interruptAfterNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); - } - if (interruptBeforeNodes && interruptBeforeNodes !== "*") { - for (const node of interruptBeforeNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); - } -} -function validateKeys(keys, channels) { - if (Array.isArray(keys)) { - for (const key of keys) if (!(key in channels)) throw new Error(`Key ${String(key)} not found in channels`); - } else if (!(keys in channels)) throw new Error(`Key ${String(keys)} not found in channels`); -} - -//#endregion - -//# sourceMappingURL=validate.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/topic.js - - - -//#region src/channels/topic.ts -/** -* A configurable PubSub Topic. -*/ -var Topic = class Topic extends BaseChannel { - lc_graph_name = "Topic"; - unique = false; - accumulate = false; - seen; - values; - constructor(fields) { - super(); - this.unique = fields?.unique ?? this.unique; - this.accumulate = fields?.accumulate ?? this.accumulate; - this.seen = /* @__PURE__ */ new Set(); - this.values = []; - } - fromCheckpoint(checkpoint) { - const empty = new Topic({ - unique: this.unique, - accumulate: this.accumulate - }); - if (typeof checkpoint !== "undefined") { - empty.seen = new Set(checkpoint[0]); - empty.values = checkpoint[1]; - } - return empty; - } - update(values) { - let updated = false; - if (!this.accumulate) { - updated = this.values.length > 0; - this.values = []; - } - const flatValues = values.flat(); - if (flatValues.length > 0) if (this.unique) { - for (const value of flatValues) if (!this.seen.has(value)) { - updated = true; - this.seen.add(value); - this.values.push(value); - } - } else { - updated = true; - this.values.push(...flatValues); - } - return updated; - } - get() { - if (this.values.length === 0) throw new EmptyChannelError(); - return this.values; - } - checkpoint() { - return [[...this.seen], this.values]; - } - isAvailable() { - return this.values.length !== 0; - } -}; - -//#endregion - -//# sourceMappingURL=topic.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/index.js - - - - - - - - - - - - - - - - - - - - - - -//#region src/pregel/index.ts -/** -* Utility class for working with channels in the Pregel system. -* Provides static methods for subscribing to channels and writing to them. -* -* Channels are the communication pathways between nodes in a Pregel graph. -* They enable message passing and state updates between different parts of the graph. -*/ -var Channel = class { - static subscribeTo(channels, options) { - const { key, tags } = { - key: void 0, - tags: void 0, - ...options ?? {} - }; - if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels"); - let channelMappingOrArray; - if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels }; - else channelMappingOrArray = [channels]; - else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); - const triggers = Array.isArray(channels) ? channels : [channels]; - return new PregelNode({ - channels: channelMappingOrArray, - triggers, - tags - }); - } - /** - * Creates a ChannelWrite that specifies how to write values to channels. - * This is used to define how nodes send output to channels. - * - * @example - * ```typescript - * // Write to multiple channels - * const write = Channel.writeTo(["output", "state"]); - * - * // Write with specific values - * const write = Channel.writeTo(["output"], { - * state: "completed", - * result: calculateResult() - * }); - * - * // Write with a transformation function - * const write = Channel.writeTo(["output"], { - * result: (x) => processResult(x) - * }); - * ``` - * - * @param channels - Array of channel names to write to - * @param writes - Optional map of channel names to values or transformations - * @returns A ChannelWrite object that can be used to write to the specified channels - */ - static writeTo(channels, writes) { - const channelWriteEntries = []; - for (const channel of channels) channelWriteEntries.push({ - channel, - value: PASSTHROUGH, - skipNone: false - }); - for (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({ - channel: key, - value: PASSTHROUGH, - skipNone: true, - mapper: _coerceToRunnable(value) - }); - else channelWriteEntries.push({ - channel: key, - value, - skipNone: false - }); - return new ChannelWrite(channelWriteEntries); - } -}; -var PartialRunnable = class extends Runnable { - lc_namespace = ["langgraph", "pregel"]; - invoke(_input, _options) { - throw new Error("Not implemented"); - } - withConfig(_config) { - return super.withConfig(_config); - } - stream(input, options) { - return super.stream(input, options); - } -}; -/** -* The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model -* inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/). -* It provides the foundation for building reliable, controllable agent workflows that can evolve state over time. -* -* Key features: -* - Message passing between nodes in discrete "supersteps" -* - Built-in persistence layer through checkpointers -* - First-class streaming support for values, updates, and events -* - Human-in-the-loop capabilities via interrupts -* - Support for parallel node execution within supersteps -* -* The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs: -* - {@link StateGraph}: The main graph class for building agent workflows -* - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel` -* - Functional API: A declarative approach using tasks and entrypoints -* - A `Pregel` instance is returned by the {@link entrypoint} function -* -* @example -* ```typescript -* // Using StateGraph API -* const graph = new StateGraph(annotation) -* .addNode("nodeA", myNodeFunction) -* .addEdge("nodeA", "nodeB") -* .compile(); -* -* // The compiled graph is a Pregel instance -* const result = await graph.invoke(input); -* ``` -* -* @example -* ```typescript -* // Using Functional API -* import { task, entrypoint } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* -* // Define tasks that can be composed -* const addOne = task("add", async (x: number) => x + 1); -* -* // Create a workflow using the entrypoint function -* const workflow = entrypoint({ -* name: "workflow", -* checkpointer: new MemorySaver() -* }, async (numbers: number[]) => { -* // Tasks can be run in parallel -* const results = await Promise.all(numbers.map(n => addOne(n))); -* return results; -* }); -* -* // The workflow is a Pregel instance -* const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] -* ``` -* -* @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations -* @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations -* @typeParam ContextType - Type of context that can be passed to the graph -* @typeParam InputType - Type of input values accepted by the graph -* @typeParam OutputType - Type of output values produced by the graph -*/ -var Pregel = class extends PartialRunnable { - /** - * Name of the class when serialized - * @internal - */ - static lc_name() { - return "LangGraph"; - } - /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */ - lc_namespace = ["langgraph", "pregel"]; - /** @internal Flag indicating this is a Pregel instance - necessary for serialization */ - lg_is_pregel = true; - /** The nodes in the graph, mapping node names to their PregelNode instances */ - nodes; - /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */ - channels; - /** - * The input channels for the graph. These channels receive the initial input when the graph is invoked. - * Can be a single channel key or an array of channel keys. - */ - inputChannels; - /** - * The output channels for the graph. These channels contain the final output when the graph completes. - * Can be a single channel key or an array of channel keys. - */ - outputChannels; - /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */ - autoValidate = true; - /** - * The streaming modes enabled for this graph. Defaults to ["values"]. - * Supported modes: - * - "values": Streams the full state after each step - * - "updates": Streams state updates after each step - * - "messages": Streams messages from within nodes - * - "custom": Streams custom events from within nodes - * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution - */ - streamMode = ["values"]; - /** - * Optional channels to stream. If not specified, all channels will be streamed. - * Can be a single channel key or an array of channel keys. - */ - streamChannels; - /** - * Optional array of node names or "all" to interrupt after executing these nodes. - * Used for implementing human-in-the-loop workflows. - */ - interruptAfter; - /** - * Optional array of node names or "all" to interrupt before executing these nodes. - * Used for implementing human-in-the-loop workflows. - */ - interruptBefore; - /** Optional timeout in milliseconds for the execution of each superstep */ - stepTimeout; - /** Whether to enable debug logging. Defaults to false. */ - debug = false; - /** - * Optional checkpointer for persisting graph state. - * When provided, saves a checkpoint of the graph state at every superstep. - * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state. - */ - checkpointer; - /** Optional retry policy for handling failures in node execution */ - retryPolicy; - /** The default configuration for graph execution, can be overridden on a per-invocation basis */ - config; - /** - * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads - */ - store; - /** - * Optional cache for the graph, useful for caching tasks. - */ - cache; - /** - * Optional interrupt helper function. - * @internal - */ - userInterrupt; - /** - * The trigger to node mapping for the graph run. - * @internal - */ - triggerToNodes = {}; - /** - * Constructor for Pregel - meant for internal use only. - * - * @internal - */ - constructor(fields) { - super(fields); - let { streamMode } = fields; - if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode]; - this.nodes = fields.nodes; - this.channels = fields.channels; - if (constants_TASKS in this.channels && "lc_graph_name" in this.channels[constants_TASKS] && this.channels[constants_TASKS].lc_graph_name !== "Topic") throw new Error(`Channel '${constants_TASKS}' is reserved and cannot be used in the graph.`); - else this.channels[constants_TASKS] = new Topic({ accumulate: false }); - this.autoValidate = fields.autoValidate ?? this.autoValidate; - this.streamMode = streamMode ?? this.streamMode; - this.inputChannels = fields.inputChannels; - this.outputChannels = fields.outputChannels; - this.streamChannels = fields.streamChannels ?? this.streamChannels; - this.interruptAfter = fields.interruptAfter; - this.interruptBefore = fields.interruptBefore; - this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; - this.debug = fields.debug ?? this.debug; - this.checkpointer = fields.checkpointer; - this.retryPolicy = fields.retryPolicy; - this.config = fields.config; - this.store = fields.store; - this.cache = fields.cache; - this.name = fields.name; - this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; - this.userInterrupt = fields.userInterrupt; - if (this.autoValidate) this.validate(); - } - /** - * Creates a new instance of the Pregel graph with updated configuration. - * This method follows the immutable pattern - instead of modifying the current instance, - * it returns a new instance with the merged configuration. - * - * @example - * ```typescript - * // Create a new instance with debug enabled - * const debugGraph = graph.withConfig({ debug: true }); - * - * // Create a new instance with a specific thread ID - * const threadGraph = graph.withConfig({ - * configurable: { thread_id: "123" } - * }); - * ``` - * - * @param config - The configuration to merge with the current configuration - * @returns A new Pregel instance with the merged configuration - */ - withConfig(config) { - const mergedConfig = mergeConfigs(this.config, config); - return new this.constructor({ - ...this, - config: mergedConfig - }); - } - /** - * Validates the graph structure to ensure it is well-formed. - * Checks for: - * - No orphaned nodes - * - Valid input/output channel configurations - * - Valid interrupt configurations - * - * @returns this - The Pregel instance for method chaining - * @throws {GraphValidationError} If the graph structure is invalid - */ - validate() { - validateGraph({ - nodes: this.nodes, - channels: this.channels, - outputChannels: this.outputChannels, - inputChannels: this.inputChannels, - streamChannels: this.streamChannels, - interruptAfterNodes: this.interruptAfter, - interruptBeforeNodes: this.interruptBefore - }); - for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) { - this.triggerToNodes[trigger] ??= []; - this.triggerToNodes[trigger].push(name); - } - return this; - } - /** - * Gets a list of all channels that should be streamed. - * If streamChannels is specified, returns those channels. - * Otherwise, returns all channels in the graph. - * - * @returns Array of channel keys to stream - */ - get streamChannelsList() { - if (Array.isArray(this.streamChannels)) return this.streamChannels; - else if (this.streamChannels) return [this.streamChannels]; - else return Object.keys(this.channels); - } - /** - * Gets the channels to stream in their original format. - * If streamChannels is specified, returns it as-is (either single key or array). - * Otherwise, returns all channels in the graph as an array. - * - * @returns Channel keys to stream, either as a single key or array - */ - get streamChannelsAsIs() { - if (this.streamChannels) return this.streamChannels; - else return Object.keys(this.channels); - } - /** - * Gets a drawable representation of the graph structure. - * This is an async version of getGraph() and is the preferred method to use. - * - * @param config - Configuration for generating the graph visualization - * @returns A representation of the graph that can be visualized - */ - async getGraphAsync(config) { - return this.getGraph(config); - } - /** - * Gets all subgraphs within this graph. - * A subgraph is a Pregel instance that is nested within a node of this graph. - * - * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release. - * @param namespace - Optional namespace to filter subgraphs - * @param recurse - Whether to recursively get subgraphs of subgraphs - * @returns Generator yielding tuples of [name, subgraph] - */ - *getSubgraphs(namespace, recurse) { - for (const [name, node] of Object.entries(this.nodes)) { - if (namespace !== void 0) { - if (!namespace.startsWith(name)) continue; - } - const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; - for (const candidate of candidates) { - const graph = findSubgraphPregel(candidate); - if (graph !== void 0) { - if (name === namespace) { - yield [name, graph]; - return; - } - if (namespace === void 0) yield [name, graph]; - if (recurse) { - let newNamespace = namespace; - if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1); - for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph]; - } - } - } - } - } - /** - * Gets all subgraphs within this graph asynchronously. - * A subgraph is a Pregel instance that is nested within a node of this graph. - * - * @param namespace - Optional namespace to filter subgraphs - * @param recurse - Whether to recursively get subgraphs of subgraphs - * @returns AsyncGenerator yielding tuples of [name, subgraph] - */ - async *getSubgraphsAsync(namespace, recurse) { - yield* this.getSubgraphs(namespace, recurse); - } - /** - * Prepares a state snapshot from saved checkpoint data. - * This is an internal method used by getState and getStateHistory. - * - * @param config - Configuration for preparing the snapshot - * @param saved - Optional saved checkpoint data - * @param subgraphCheckpointer - Optional checkpointer for subgraphs - * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels - * @returns A snapshot of the graph state - * @internal - */ - async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) { - if (saved === void 0) return { - values: {}, - next: [], - config, - tasks: [] - }; - const channels = emptyChannels(this.channels, saved.checkpoint); - if (saved.pendingWrites?.length) { - const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]); - if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], void 0, this.triggerToNodes); - } - const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - store: this.store - })); - const subgraphs = await gatherIterator(this.getSubgraphsAsync()); - const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; - const taskStates = {}; - for (const task of nextTasks) { - const matchingSubgraph = subgraphs.find(([name]) => name === task.name); - if (!matchingSubgraph) continue; - let taskNs = `${String(task.name)}${CHECKPOINT_NAMESPACE_END}${task.id}`; - if (parentNamespace) taskNs = `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`; - if (subgraphCheckpointer === void 0) { - const config$1 = { configurable: { - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - taskStates[task.id] = config$1; - } else { - const subgraphConfig = { configurable: { - [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer, - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - const pregel = matchingSubgraph[1]; - taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); - } - } - if (applyPendingWrites && saved.pendingWrites?.length) { - const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task])); - for (const [taskId, channel, value] of saved.pendingWrites) { - if ([ - constants_ERROR, - constants_INTERRUPT, - SCHEDULED - ].includes(channel)) continue; - if (!(taskId in nextTaskById)) continue; - nextTaskById[taskId].writes.push([String(channel), value]); - } - const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0); - if (tasksWithWrites$1.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes); - } - let metadata = saved?.metadata; - if (metadata && saved?.config?.configurable?.thread_id) metadata = { - ...metadata, - thread_id: saved.config.configurable.thread_id - }; - const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name); - return { - values: readChannels(channels, this.streamChannelsAsIs), - next: nextList, - tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), - metadata, - config: patchCheckpointMap(saved.config, saved.metadata), - createdAt: saved.checkpoint.ts, - parentConfig: saved.parentConfig - }; - } - /** - * Gets the current state of the graph. - * Requires a checkpointer to be configured. - * - * @param config - Configuration for retrieving the state - * @param options - Additional options - * @returns A snapshot of the current graph state - * @throws {GraphValueError} If no checkpointer is configured - */ - async getState(config, options) { - const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs }); - throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`); - } - const mergedConfig = mergeConfigs(this.config, config); - const saved = await checkpointer.getTuple(config); - const snapshot = await this._prepareStateSnapshot({ - config: mergedConfig, - saved, - subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0, - applyPendingWrites: !config.configurable?.checkpoint_id - }); - return snapshot; - } - /** - * Gets the history of graph states. - * Requires a checkpointer to be configured. - * Useful for: - * - Debugging execution history - * - Implementing time travel - * - Analyzing graph behavior - * - * @param config - Configuration for retrieving the history - * @param options - Options for filtering the history - * @returns An async iterator of state snapshots - * @throws {Error} If no checkpointer is configured - */ - async *getStateHistory(config, options) { - const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) { - yield* pregel.getStateHistory(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options); - return; - } - throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`); - } - const mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } }); - for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({ - config: checkpointTuple.config, - saved: checkpointTuple - }); - } - /** - * Apply updates to the graph state in bulk. - * Requires a checkpointer to be configured. - * - * This method is useful for recreating a thread - * from a list of updates, especially if a checkpoint - * is created as a result of multiple tasks. - * - * @internal The API might change in the future. - * - * @param startConfig - Configuration for the update - * @param updates - The list of updates to apply to graph state - * @returns Updated configuration - * @throws {GraphValueError} If no checkpointer is configured - * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence. - */ - async bulkUpdateState(startConfig, supersteps) { - const checkpointer = startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - if (supersteps.length === 0) throw new Error("No supersteps provided"); - if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided"); - const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps); - throw new Error(`Subgraph "${recastNamespace}" not found`); - } - const updateSuperStep = async (inputConfig, updates) => { - const config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; - const saved = await checkpointer.getTuple(config); - const checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); - const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; - const step = saved?.metadata?.step ?? -1; - let checkpointConfig = patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" }); - let checkpointMetadata = config.metadata ?? {}; - if (saved?.config.configurable) { - checkpointConfig = patchConfigurable(config, saved.config.configurable); - checkpointMetadata = { - ...saved.metadata, - ...checkpointMetadata - }; - } - const { values, asNode } = updates[0]; - if (values == null && asNode === void 0) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`); - const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, {}); - return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); - } - const channels = emptyChannels(this.channels, checkpoint); - if (values === null && asNode === END) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`); - if (saved) { - const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - checkpointer, - store: this.store - }); - const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - for (const [taskId, k, v] of saved.pendingWrites || []) { - if ([ - constants_ERROR, - constants_INTERRUPT, - SCHEDULED - ].includes(k)) continue; - if (!(taskId in nextTasks)) continue; - nextTasks[taskId].writes.push([k, v]); - } - _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - } - const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), { - ...checkpointMetadata, - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); - return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); - } - if (asNode === COPY) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`); - if (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`); - const isCopyWithUpdates = (values$1) => { - if (!Array.isArray(values$1)) return false; - if (values$1.length === 0) return false; - return values$1.every((v) => Array.isArray(v) && v.length === 2); - }; - const nextCheckpoint = createCheckpoint(checkpoint, void 0, step); - const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, { - source: "fork", - step: step + 1, - parents: saved.metadata?.parents ?? {} - }, {}); - if (isCopyWithUpdates(values)) { - const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 }); - const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { - acc[name] ??= []; - acc[name].push({ id }); - return acc; - }, {}); - const userGroupBy = values.reduce((acc, item) => { - const [values$1, asNode$1] = item; - acc[asNode$1] ??= []; - const targetIdx = acc[asNode$1].length; - const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id; - acc[asNode$1].push({ - values: values$1, - asNode: asNode$1, - taskId - }); - return acc; - }, {}); - return updateSuperStep(patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat()); - } - return patchCheckpointMap(nextConfig$1, saved.metadata); - } - if (asNode === INPUT) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`); - const inputWrites = await gatherIterator(mapInput(this.inputChannels, values)); - if (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); - _applyWrites(checkpoint, channels, [{ - name: INPUT, - writes: inputWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; - const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), { - source: "input", - step: nextStep, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); - await checkpointer.putWrites(nextConfig$1, inputWrites, uuid5(INPUT, checkpoint.id)); - return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); - } - if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) { - const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - store: this.store, - checkpointer: this.checkpointer, - step: (saved.metadata?.step ?? -1) + 1 - }); - const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], void 0, this.triggerToNodes); - for (const [tid, k, v] of saved.pendingWrites) { - if ([ - constants_ERROR, - constants_INTERRUPT, - SCHEDULED - ].includes(k) || nextTasks[tid] === void 0) continue; - nextTasks[tid].writes.push([k, v]); - } - const tasks$1 = Object.values(nextTasks).filter((task) => { - return task.writes.length > 0; - }); - if (tasks$1.length > 0) _applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes); - } - const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { - return Object.values(seenVersions); - }).flat().find((v) => !!v); - const validUpdates = []; - if (updates.length === 1) { - let { values: values$1, asNode: asNode$1, taskId } = updates[0]; - if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes); - else if (asNode$1 === void 0 && nonNullVersion === void 0) { - if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels; - } else if (asNode$1 === void 0) { - const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => { - return Object.values(seen).map((v) => { - return [v, n]; - }); - }).flat().filter(([_, v]) => v !== constants_INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); - if (lastSeenByNode) { - if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1]; - else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1]; - } - } - if (asNode$1 === void 0) throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`); - validUpdates.push({ - values: values$1, - asNode: asNode$1, - taskId - }); - } else for (const { asNode: asNode$1, values: values$1, taskId } of updates) { - if (asNode$1 == null) throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`); - validUpdates.push({ - values: values$1, - asNode: asNode$1, - taskId - }); - } - const tasks = []; - for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) { - if (this.nodes[asNode$1] === void 0) throw new InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`); - const writers = this.nodes[asNode$1].getWriters(); - if (!writers.length) throw new InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`); - tasks.push({ - name: asNode$1, - input: values$1, - proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], - writes: [], - triggers: [constants_INTERRUPT], - id: taskId ?? uuid5(constants_INTERRUPT, checkpoint.id), - writers: [] - }); - } - for (const task of tasks) await task.proc.invoke(task.input, config_patchConfig({ - ...config, - store: config?.store ?? this.store - }, { - runName: config.runName ?? `${this.getName()}UpdateState`, - configurable: { - [CONFIG_KEY_SEND]: (items) => task.writes.push(...items), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_) - } - })); - for (const task of tasks) { - const channelWrites = task.writes.filter((w) => w[0] !== PUSH); - if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id); - } - _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions); - const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, newVersions); - for (const task of tasks) { - const pushWrites = task.writes.filter((w) => w[0] === PUSH); - if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id); - } - return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0); - }; - let currentConfig = startConfig; - for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates); - return currentConfig; - } - /** - * Updates the state of the graph with new values. - * Requires a checkpointer to be configured. - * - * This method can be used for: - * - Implementing human-in-the-loop workflows - * - Modifying graph state during breakpoints - * - Integrating external inputs into the graph - * - * @param inputConfig - Configuration for the update - * @param values - The values to update the state with - * @param asNode - Optional node name to attribute the update to - * @returns Updated configuration - * @throws {GraphValueError} If no checkpointer is configured - * @throws {InvalidUpdateError} If the update cannot be attributed to a node - */ - async updateState(inputConfig, values, asNode) { - return this.bulkUpdateState(inputConfig, [{ updates: [{ - values, - asNode - }] }]); - } - /** - * Gets the default values for various graph configuration options. - * This is an internal method used to process and normalize configuration options. - * - * @param config - The input configuration options - * @returns A tuple containing normalized values for: - * - debug mode - * - stream modes - * - input keys - * - output keys - * - remaining config - * - interrupt before nodes - * - interrupt after nodes - * - checkpointer - * - store - * - whether stream mode is single - * - node cache - * - whether checkpoint during is enabled - * @internal - */ - _defaults(config) { - const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config; - let streamModeSingle = true; - const defaultDebug = debug !== void 0 ? debug : this.debug; - let defaultOutputKeys = outputKeys; - if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs; - else validateKeys(defaultOutputKeys, this.channels); - let defaultInputKeys = inputKeys; - if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels; - else validateKeys(defaultInputKeys, this.channels); - const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; - const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; - let defaultStreamMode; - if (streamMode !== void 0) { - defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; - streamModeSingle = typeof streamMode === "string"; - } else { - if (config.configurable?.[CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"]; - else defaultStreamMode = this.streamMode; - streamModeSingle = true; - } - let defaultCheckpointer; - if (this.checkpointer === false) defaultCheckpointer = void 0; - else if (config !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER]; - else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs."); - else defaultCheckpointer = this.checkpointer; - const defaultStore = config.store ?? this.store; - const defaultCache = config.cache ?? this.cache; - if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); - const checkpointDuringDurability = (() => { - if (config.checkpointDuring == null) return void 0; - if (config.checkpointDuring === false) return "exit"; - return "async"; - })(); - const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[CONFIG_KEY_DURABILITY] ?? "async"; - return [ - defaultDebug, - defaultStreamMode, - defaultInputKeys, - defaultOutputKeys, - rest, - defaultInterruptBefore, - defaultInterruptAfter, - defaultCheckpointer, - defaultStore, - streamModeSingle, - defaultCache, - defaultDurability - ]; - } - /** - * Streams the execution of the graph, emitting state updates as they occur. - * This is the primary method for observing graph execution in real-time. - * - * Stream modes: - * - "values": Emits complete state after each step - * - "updates": Emits only state changes after each step - * - "debug": Emits detailed debug information - * - "messages": Emits messages from within nodes - * - "custom": Emits custom events from within nodes - * - "checkpoints": Emits checkpoints from within nodes - * - "tasks": Emits tasks from within nodes - * - * @param input - The input to start graph execution with - * @param options - Configuration options for streaming - * @returns An async iterable stream of graph state updates - */ - async stream(input, options) { - const abortController = new AbortController(); - const config = { - recursionLimit: this.config?.recursionLimit, - ...options, - signal: combineAbortSignals(options?.signal, abortController.signal).signal - }; - const stream = await super.stream(input, config); - return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream) : stream, abortController); - } - streamEvents(input, options, streamOptions) { - const abortController = new AbortController(); - const config = { - recursionLimit: this.config?.recursionLimit, - ...options, - callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks), - signal: combineAbortSignals(options?.signal, abortController.signal).signal - }; - return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController); - } - /** - * Validates the input for the graph. - * @param input - The input to validate - * @returns The validated input - * @internal - */ - async _validateInput(input) { - return input; - } - /** - * Validates the context options for the graph. - * @param context - The context options to validate - * @returns The validated context options - * @internal - */ - async _validateContext(context) { - return context; - } - /** - * Internal iterator used by stream() to generate state updates. - * This method handles the core logic of graph execution and streaming. - * - * @param input - The input to start graph execution with - * @param options - Configuration options for streaming - * @returns AsyncGenerator yielding state updates - * @internal - */ - async *_streamIterator(input, options) { - const streamEncoding = "version" in (options ?? {}) ? void 0 : options?.encoding ?? void 0; - const streamSubgraphs = options?.subgraphs; - const inputConfig = config_ensureLangGraphConfig(this.config, options); - if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`); - if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); - const validInput = await this._validateInput(input); - const { runId,...restConfig } = inputConfig; - const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig); - if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context); - else config.configurable = await this._validateContext(config.configurable); - const stream = new IterableReadableWritableStream({ modes: new Set(streamMode) }); - if (this.checkpointer === true) { - config.configurable ??= {}; - const ns = config.configurable[CONFIG_KEY_CHECKPOINT_NS] ?? ""; - config.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split(CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR); - } - if (streamMode.includes("messages")) { - const messageStreamer = new StreamMessagesHandler((chunk) => stream.push(chunk)); - const { callbacks } = config; - if (callbacks === void 0) config.callbacks = [messageStreamer]; - else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(messageStreamer, true); - config.callbacks = copiedCallbacks; - } - } - config.writer ??= (chunk) => { - if (!streamMode.includes("custom")) return; - const ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split(CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1); - stream.push([ - ns ?? [], - "custom", - chunk - ]); - }; - config.interrupt ??= this.userInterrupt ?? interrupt; - const callbackManager = await getCallbackManagerForConfig(config); - const runManager = await callbackManager?.handleChainStart(this.toJSON(), utils_coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName()); - const channelSpecs = getOnlyChannels(this.channels); - let loop; - let loopError; - /** - * The PregelLoop will yield events from concurrent tasks as soon as they are - * generated. Each task can push multiple events onto the stream in any order. - * - * We use a separate background method and stream here in order to yield events - * from the loop to the main stream and therefore back to the user as soon as - * they are available. - */ - const createAndRunLoop = async () => { - try { - loop = await PregelLoop.initialize({ - input: validInput, - config, - checkpointer, - nodes: this.nodes, - channelSpecs, - outputKeys, - streamKeys: this.streamChannelsAsIs, - store, - cache, - stream, - interruptAfter, - interruptBefore, - manager: runManager, - debug: this.debug, - triggerToNodes: this.triggerToNodes, - durability - }); - const runner = new PregelRunner({ - loop, - nodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED] - }); - if (options?.subgraphs) loop.config.configurable = { - ...loop.config.configurable, - [CONFIG_KEY_STREAM]: loop.stream - }; - await this._runLoop({ - loop, - runner, - debug, - config - }); - if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = e; - } finally { - try { - if (loop) { - await loop.store?.stop(); - await loop.cache?.stop(); - } - await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = loopError ?? e; - } - if (loopError) stream.error(loopError); - else stream.close(); - } - }; - const runLoopPromise = createAndRunLoop(); - try { - for await (const chunk of stream) { - if (chunk === void 0) throw new Error("Data structure error."); - const [namespace, mode, payload] = chunk; - if (streamMode.includes(mode)) { - if (streamEncoding === "text/event-stream") { - if (streamSubgraphs) yield [ - namespace, - mode, - payload - ]; - else yield [ - null, - mode, - payload - ]; - continue; - } - if (streamSubgraphs && !streamModeSingle) yield [ - namespace, - mode, - payload - ]; - else if (!streamModeSingle) yield [mode, payload]; - else if (streamSubgraphs) yield [namespace, payload]; - else yield payload; - } - } - } catch (e) { - await runManager?.handleChainError(loopError); - throw e; - } finally { - await runLoopPromise; - } - await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0); - } - /** - * Run the graph with a single input and config. - * @param input The input to the graph. - * @param options The configuration to use for the run. - */ - async invoke(input, options) { - const streamMode = options?.streamMode ?? "values"; - const config = { - ...options, - outputKeys: options?.outputKeys ?? this.outputChannels, - streamMode, - encoding: void 0 - }; - const chunks = []; - const stream = await this.stream(input, config); - const interruptChunks = []; - let latest; - for await (const chunk of stream) if (streamMode === "values") if (isInterrupted(chunk)) interruptChunks.push(chunk[constants_INTERRUPT]); - else latest = chunk; - else chunks.push(chunk); - if (streamMode === "values") { - if (interruptChunks.length > 0) { - const interrupts = interruptChunks.flat(1); - if (latest == null) return { [constants_INTERRUPT]: interrupts }; - if (typeof latest === "object") return { - ...latest, - [constants_INTERRUPT]: interrupts - }; - } - return latest; - } - return chunks; - } - async _runLoop(params) { - const { loop, runner, debug, config } = params; - let tickError; - try { - while (await loop.tick({ inputKeys: this.inputChannels })) { - for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true); - if (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); - if (debug) printStepTasks(loop.step, Object.values(loop.tasks)); - await runner.tick({ - timeout: this.stepTimeout, - retryPolicy: this.retryPolicy, - onStepWrite: (step, writes) => { - if (debug) printStepWrites(step, writes, this.streamChannelsList); - }, - maxConcurrency: config.maxConcurrency, - signal: config.signal - }); - } - if (loop.status === "out_of_steps") throw new GraphRecursionError([ - `Recursion limit of ${config.recursionLimit} reached`, - "without hitting a stop condition. You can increase the", - `limit by setting the "recursionLimit" config key.` - ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); - } catch (e) { - tickError = e; - const suppress = await loop.finishAndHandleError(tickError); - if (!suppress) throw e; - } finally { - if (tickError === void 0) await loop.finishAndHandleError(); - } - } - async clearCache() { - await this.cache?.clear([]); - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js - - - -//#region src/channels/ephemeral_value.ts -/** -* Stores the value received in the step immediately preceding, clears after. -*/ -var EphemeralValue = class EphemeralValue extends BaseChannel { - lc_graph_name = "EphemeralValue"; - guard; - value = []; - constructor(guard = true) { - super(); - this.guard = guard; - } - fromCheckpoint(checkpoint) { - const empty = new EphemeralValue(this.guard); - if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) { - const updated = this.value.length > 0; - this.value = []; - return updated; - } - if (values.length !== 1 && this.guard) throw new InvalidUpdateError("EphemeralValue can only receive one value per step."); - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } -}; - -//#endregion - -//# sourceMappingURL=ephemeral_value.js.map -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/errors.js - - -const errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper), - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper), - // enumerable: false, - }, - addIssue: { - value: (issue) => inst.issues.push(issue), - // enumerable: false, - }, - addIssues: { - value: (issues) => inst.issues.push(...issues), - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - }, - // enumerable: false, - }, - }); - // Object.defineProperty(inst, "isEmpty", { - // get() { - // return inst.issues.length === 0; - // }, - // }); -}; -const errors_ZodError = $constructor("ZodError", errors_initializer); -const ZodRealError = $constructor("ZodError", errors_initializer, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/parse.js - - -const classic_parse_parse = /* @__PURE__ */ _parse(ZodRealError); -const parse_parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/schemas.js - - - - - -const schemas_ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - inst.def = def; - Object.defineProperty(inst, "_def", { value: def }); - // base methods - inst.check = (...checks) => { - return inst.clone({ - ...def, - checks: [ - ...(def.checks ?? []), - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - } - // { parent: true } - ); - }; - inst.clone = (def, params) => clone(inst, def, params); - inst.brand = () => inst; - inst.register = ((reg, meta) => { - reg.add(inst, meta); - return inst; - }); - // parsing - inst.parse = (data, params) => classic_parse_parse(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => parse_safeParse(inst, data, params); - inst.parseAsync = async (data, params) => parse_parseAsync(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => parse_safeParseAsync(inst, data, params); - inst.spa = inst.safeParseAsync; - // refinements - inst.refine = (check, params) => inst.check(refine(check, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - // wrappers - inst.optional = () => optional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg) => union([inst, arg]); - inst.and = (arg) => intersection(inst, arg); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def) => schemas_default(inst, def); - inst.prefault = (def) => prefault(inst, def); - // inst.coalesce = (def, params) => coalesce(inst, def, params); - inst.catch = (params) => schemas_catch(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - // meta - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true, - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); - } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }; - // helpers - inst.isOptional = () => inst.safeParse(undefined).success; - inst.isNullable = () => inst.safeParse(null).success; - return inst; -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("_ZodString", (inst, def) => { - core.$ZodString.init(inst, def); - schemas_ZodType.init(inst, def); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - // validations - inst.regex = (...args) => inst.check(checks.regex(...args)); - inst.includes = (...args) => inst.check(checks.includes(...args)); - inst.startsWith = (...args) => inst.check(checks.startsWith(...args)); - inst.endsWith = (...args) => inst.check(checks.endsWith(...args)); - inst.min = (...args) => inst.check(checks.minLength(...args)); - inst.max = (...args) => inst.check(checks.maxLength(...args)); - inst.length = (...args) => inst.check(checks.length(...args)); - inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args)); - inst.lowercase = (params) => inst.check(checks.lowercase(params)); - inst.uppercase = (params) => inst.check(checks.uppercase(params)); - // transforms - inst.trim = () => inst.check(checks.trim()); - inst.normalize = (...args) => inst.check(checks.normalize(...args)); - inst.toLowerCase = () => inst.check(checks.toLowerCase()); - inst.toUpperCase = () => inst.check(checks.toUpperCase()); -}))); -const schemas_ZodString = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodString", (inst, def) => { - core.$ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(core._email(ZodEmail, params)); - inst.url = (params) => inst.check(core._url(ZodURL, params)); - inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params)); - inst.guid = (params) => inst.check(core._guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(core._guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(core._ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(core._base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(core._xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(core._e164(ZodE164, params)); - // iso - inst.datetime = (params) => inst.check(iso.datetime(params)); - inst.date = (params) => inst.check(iso.date(params)); - inst.time = (params) => inst.check(iso.time(params)); - inst.duration = (params) => inst.check(iso.duration(params)); -}))); -function string(params) { - return core._string(schemas_ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodStringFormat", (inst, def) => { - core.$ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}))); -const ZodEmail = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function email(params) { - return core._email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function url(params) { - return core._url(ZodURL, params); -} -const ZodEmoji = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -const ZodCUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodIPv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCIDRv4", (inst, def) => { - core.$ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCIDRv6", (inst, def) => { - core.$ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function e164(params) { - return core._e164(ZodE164, params); -} -const ZodJWT = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -const schemas_ZodNumber = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNumber", (inst, def) => { - core.$ZodNumber.init(inst, def); - schemas_ZodType.init(inst, def); - inst.gt = (value, params) => inst.check(checks.gt(value, params)); - inst.gte = (value, params) => inst.check(checks.gte(value, params)); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.lt = (value, params) => inst.check(checks.lt(value, params)); - inst.lte = (value, params) => inst.check(checks.lte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - inst.int = (params) => inst.check(schemas_int(params)); - inst.safe = (params) => inst.check(schemas_int(params)); - inst.positive = (params) => inst.check(checks.gt(0, params)); - inst.nonnegative = (params) => inst.check(checks.gte(0, params)); - inst.negative = (params) => inst.check(checks.lt(0, params)); - inst.nonpositive = (params) => inst.check(checks.lte(0, params)); - inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params)); - inst.step = (value, params) => inst.check(checks.multipleOf(value, params)); - // inst.finite = (params) => inst.check(core.finite(params)); - inst.finite = () => inst; - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}))); -function number(params) { - return core._number(schemas_ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNumberFormat", (inst, def) => { - core.$ZodNumberFormat.init(inst, def); - schemas_ZodNumber.init(inst, def); -}))); -function schemas_int(params) { - return core._int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const schemas_ZodBoolean = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBoolean", (inst, def) => { - core.$ZodBoolean.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function schemas_boolean(params) { - return core._boolean(schemas_ZodBoolean, params); -} -const schemas_ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - schemas_ZodType.init(inst, def); - inst.gte = (value, params) => inst.check(checks.gte(value, params)); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.gt = (value, params) => inst.check(checks.gt(value, params)); - inst.gte = (value, params) => inst.check(checks.gte(value, params)); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.lt = (value, params) => inst.check(checks.lt(value, params)); - inst.lte = (value, params) => inst.check(checks.lte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - inst.positive = (params) => inst.check(checks.gt(BigInt(0), params)); - inst.negative = (params) => inst.check(checks.lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}))); -function bigint(params) { - return core._bigint(schemas_ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - schemas_ZodBigInt.init(inst, def); -}))); -// int64 -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -// uint64 -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const schemas_ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function symbol(params) { - return core._symbol(schemas_ZodSymbol, params); -} -const schemas_ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function schemas_undefined(params) { - return core._undefined(schemas_ZodUndefined, params); -} - -const schemas_ZodNull = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNull", (inst, def) => { - core.$ZodNull.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function schemas_null(params) { - return core._null(schemas_ZodNull, params); -} - -const schemas_ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - schemas_ZodType.init(inst, def); -}); -function any() { - return _any(schemas_ZodAny); -} -const schemas_ZodUnknown = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUnknown", (inst, def) => { - core.$ZodUnknown.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function unknown() { - return core._unknown(schemas_ZodUnknown); -} -const schemas_ZodNever = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNever", (inst, def) => { - core.$ZodNever.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function schemas_never(params) { - return core._never(schemas_ZodNever, params); -} -const schemas_ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function schemas_void(params) { - return core._void(schemas_ZodVoid, params); -} - -const schemas_ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - schemas_ZodType.init(inst, def); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(schemas_ZodDate, params); -} -const schemas_ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - schemas_ZodType.init(inst, def); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; -}); -function array(element, params) { - return _array(schemas_ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return literal(Object.keys(shape)); -} -const schemas_ZodObject = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodObject", (inst, def) => { - core.$ZodObject.init(inst, def); - schemas_ZodType.init(inst, def); - util.defineLazy(inst, "shape", () => def.shape); - inst.keyof = () => schemas_enum(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - // inst.nonstrict = () => inst.clone({ ...inst._zod.def, catchall: api.unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: schemas_never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); - inst.extend = (incoming) => { - return util.extend(inst, incoming); - }; - inst.merge = (other) => util.merge(inst, other); - inst.pick = (mask) => util.pick(inst, mask); - inst.omit = (mask) => util.omit(inst, mask); - inst.partial = (...args) => util.partial(schemas_ZodOptional, inst, args[0]); - inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]); -}))); -function object(shape, params) { - const def = { - type: "object", - get shape() { - util.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - ...util.normalizeParams(params), - }; - return new schemas_ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new schemas_ZodObject({ - type: "object", - get shape() { - util.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - catchall: schemas_never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new schemas_ZodObject({ - type: "object", - get shape() { - util.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - catchall: unknown(), - ...util.normalizeParams(params), - }); -} -const schemas_ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - schemas_ZodType.init(inst, def); - inst.options = def.options; -}); -function union(options, params) { - return new schemas_ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const schemas_ZodDiscriminatedUnion = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDiscriminatedUnion", (inst, def) => { - schemas_ZodUnion.init(inst, def); - core.$ZodDiscriminatedUnion.init(inst, def); -}))); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new schemas_ZodDiscriminatedUnion({ - type: "union", - options, - discriminator, - ...util.normalizeParams(params), - }); -} -const schemas_ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - schemas_ZodType.init(inst, def); -}); -function intersection(left, right) { - return new schemas_ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const schemas_ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - core.$ZodTuple.init(inst, def); - schemas_ZodType.init(inst, def); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest: rest, - }); -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new schemas_ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const schemas_ZodRecord = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodRecord", (inst, def) => { - core.$ZodRecord.init(inst, def); - schemas_ZodType.init(inst, def); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}))); -function record(keyType, valueType, params) { - return new schemas_ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new schemas_ZodRecord({ - type: "record", - keyType: union([keyType, schemas_never()]), - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const schemas_ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - core.$ZodMap.init(inst, def); - schemas_ZodType.init(inst, def); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}))); -function map(keyType, valueType, params) { - return new schemas_ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const schemas_ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - core.$ZodSet.init(inst, def); - schemas_ZodType.init(inst, def); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function set(valueType, params) { - return new schemas_ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const schemas_ZodEnum = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodEnum", (inst, def) => { - core.$ZodEnum.init(inst, def); - schemas_ZodType.init(inst, def); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new schemas_ZodEnum({ - ...def, - checks: [], - ...util.normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new schemas_ZodEnum({ - ...def, - checks: [], - ...util.normalizeParams(params), - entries: newEntries, - }); - }; -}))); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new schemas_ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new schemas_ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const schemas_ZodLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodLiteral", (inst, def) => { - core.$ZodLiteral.init(inst, def); - schemas_ZodType.init(inst, def); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}))); -function literal(value, params) { - return new schemas_ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - schemas_ZodType.init(inst, def); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - _issue.continue ?? (_issue.continue = true); - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const schemas_ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function optional(innerType) { - return new schemas_ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const schemas_ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new schemas_ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return optional(nullable(innerType)); -} -const schemas_ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new schemas_ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const schemas_ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new schemas_ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), - }); -} - -const schemas_ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function nan(params) { - return core._nan(schemas_ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - schemas_ZodType.init(inst, def); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const schemas_ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - schemas_ZodType.init(inst, def); -}); -function readonly(innerType) { - return new schemas_ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - schemas_ZodType.init(inst, def); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const schemas_ZodLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodLazy", (inst, def) => { - core.$ZodLazy.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.getter(); -}))); -function lazy(getter) { - return new schemas_ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const schemas_ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - schemas_ZodType.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function promise(innerType) { - return new schemas_ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - schemas_ZodType.init(inst, def); -}); -// custom checks -function check(fn) { - const ch = new $ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function schemas_custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn) { - const ch = check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }); - return ch; -} -function _instanceof(cls, params = { - error: `Input not instance of ${cls.name}`, -}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Pipe: ZodPipe, - Boolean: schemas_ZodBoolean, - String: schemas_ZodString, - Transform: ZodTransform, -}, ...args); -function json(params) { - const jsonSchema = lazy(() => { - return union([string(params), number(), schemas_boolean(), schemas_null(), array(jsonSchema), record(string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */ -function preprocess(fn, schema) { - return pipe(transform(fn), schema); -} - -// EXTERNAL MODULE: ./node_modules/@langchain/langgraph/node_modules/uuid/dist/index.js -var langgraph_node_modules_uuid_dist = __nccwpck_require__(138); -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/node_modules/uuid/wrapper.mjs - -const node_modules_uuid_wrapper_v1 = langgraph_node_modules_uuid_dist.v1; -const node_modules_uuid_wrapper_v1ToV6 = langgraph_node_modules_uuid_dist/* v1ToV6 */.bV; -const node_modules_uuid_wrapper_v3 = langgraph_node_modules_uuid_dist.v3; -const node_modules_uuid_wrapper_v4 = langgraph_node_modules_uuid_dist.v4; -const node_modules_uuid_wrapper_v5 = langgraph_node_modules_uuid_dist.v5; -const node_modules_uuid_wrapper_v6 = langgraph_node_modules_uuid_dist.v6; -const node_modules_uuid_wrapper_v6ToV1 = langgraph_node_modules_uuid_dist/* v6ToV1 */.JE; -const node_modules_uuid_wrapper_v7 = langgraph_node_modules_uuid_dist.v7; -const node_modules_uuid_wrapper_NIL = langgraph_node_modules_uuid_dist/* NIL */.wD; -const node_modules_uuid_wrapper_MAX = langgraph_node_modules_uuid_dist/* MAX */.Zu; -const node_modules_uuid_wrapper_version = langgraph_node_modules_uuid_dist/* version */.rE; -const langgraph_node_modules_uuid_wrapper_validate = langgraph_node_modules_uuid_dist/* validate */.tf; -const node_modules_uuid_wrapper_stringify = langgraph_node_modules_uuid_dist/* stringify */.As; -const node_modules_uuid_wrapper_parse = langgraph_node_modules_uuid_dist/* parse */.qg; - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/graph.js - - - - - - - - - - - - - -//#region src/graph/graph.ts -var Branch = class { - path; - ends; - constructor(options) { - if (Runnable.isRunnable(options.path)) this.path = options.path; - else this.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch` }); - this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n) => { - acc[n] = n; - return acc; - }, {}) : options.pathMap; - } - run(writer, reader) { - return ChannelWrite.registerWriter(new RunnableCallable({ - name: "", - trace: false, - func: async (input, config) => { - try { - return await this._route(input, config, writer, reader); - } catch (e) { - if (e.name === NodeInterrupt.unminifiable_name) console.warn("[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\nNodeInterrupt should only be thrown inside a node, not in edge conditions."); - throw e; - } - } - })); - } - async _route(input, config, writer, reader) { - let result = await this.path.invoke(reader ? reader(config) : input, config); - if (!Array.isArray(result)) result = [result]; - let destinations; - if (this.ends) destinations = result.map((r) => _isSend(r) ? r : this.ends[r]); - else destinations = result; - if (destinations.some((dest) => !dest)) throw new Error("Branch condition returned unknown or null destination"); - if (destinations.filter(_isSend).some((packet) => packet.node === END)) throw new InvalidUpdateError("Cannot send a packet to the END node"); - const writeResult = await writer(destinations, config); - return writeResult ?? input; - } -}; -var Graph$1 = class { - nodes; - edges; - branches; - entryPoint; - compiled = false; - constructor() { - this.nodes = {}; - this.edges = /* @__PURE__ */ new Set(); - this.branches = {}; - } - warnIfCompiled(message) { - if (this.compiled) console.warn(message); - } - get allEdges() { - return this.edges; - } - addNode(...args) { - function isMutlipleNodes(args$1) { - return args$1.length >= 1 && typeof args$1[0] !== "string"; - } - const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - for (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); - if (key === END) throw new Error(`Node \`${key}\` is reserved.`); - const runnable = _coerceToRunnable(action); - this.nodes[key] = { - runnable, - metadata: options?.metadata, - subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends - }; - } - return this; - } - addEdge(startKey, endKey) { - this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (startKey === END) throw new Error("END cannot be a start node"); - if (endKey === START) throw new Error("START cannot be an end node"); - if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); - this.edges.add([startKey, endKey]); - return this; - } - addConditionalEdges(source, path, pathMap) { - const options = typeof source === "object" ? source : { - source, - path, - pathMap - }; - this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - if (!Runnable.isRunnable(options.path)) { - const pathDisplayValues = Array.isArray(options.pathMap) ? options.pathMap.join(",") : Object.keys(options.pathMap ?? {}).join(","); - options.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch<${options.source}${pathDisplayValues !== "" ? `,${pathDisplayValues}` : ""}>`.slice(0, 63) }); - } - const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); - if (this.branches[options.source] && this.branches[options.source][name]) throw new Error(`Condition \`${name}\` already present for node \`${source}\``); - this.branches[options.source] ??= {}; - this.branches[options.source][name] = new Branch(options); - return this; - } - /** - * @deprecated use `addEdge(START, key)` instead - */ - setEntryPoint(key) { - this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(START, key); - } - /** - * @deprecated use `addEdge(key, END)` instead - */ - setFinishPoint(key) { - this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(key, END); - } - compile({ checkpointer, interruptBefore, interruptAfter, name } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const compiled = new CompiledGraph({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - [START]: new EphemeralValue(), - [END]: new EphemeralValue() - }, - inputChannels: START, - outputChannels: END, - streamChannels: [], - streamMode: "values", - name - }); - for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); - for (const [start, end] of this.edges) compiled.attachEdge(start, end); - for (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch); - return compiled.validate(); - } - validate(interrupt) { - const allSources = new Set([...this.allEdges].map(([src, _]) => src)); - for (const [start] of Object.entries(this.branches)) allSources.add(start); - for (const source of allSources) if (source !== START && !(source in this.nodes)) throw new Error(`Found edge starting at unknown node \`${source}\``); - const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); - for (const [start, branches] of Object.entries(this.branches)) for (const branch of Object.values(branches)) if (branch.ends != null) for (const end of Object.values(branch.ends)) allTargets.add(end); - else { - allTargets.add(END); - for (const node of Object.keys(this.nodes)) if (node !== start) allTargets.add(node); - } - for (const node of Object.values(this.nodes)) for (const target of node.ends ?? []) allTargets.add(target); - for (const node of Object.keys(this.nodes)) if (!allTargets.has(node)) throw new UnreachableNodeError([ - `Node \`${node}\` is not reachable.`, - "", - "If you are returning Command objects from your node,", - "make sure you are passing names of potential destination nodes as an \"ends\" array", - "into \".addNode(..., { ends: [\"node1\", \"node2\"] })\"." - ].join("\n"), { lc_error_code: "UNREACHABLE_NODE" }); - for (const target of allTargets) if (target !== END && !(target in this.nodes)) throw new Error(`Found edge ending at unknown node \`${target}\``); - if (interrupt) { - for (const node of interrupt) if (!(node in this.nodes)) throw new Error(`Interrupt node \`${node}\` is not present`); - } - this.compiled = true; - } -}; -var CompiledGraph = class extends Pregel { - builder; - constructor({ builder,...rest }) { - super(rest); - this.builder = builder; - } - attachNode(key, node) { - this.channels[key] = new EphemeralValue(); - this.nodes[key] = new PregelNode({ - channels: [], - triggers: [], - metadata: node.metadata, - subgraphs: node.subgraphs, - ends: node.ends - }).pipe(node.runnable).pipe(new ChannelWrite([{ - channel: key, - value: PASSTHROUGH - }], [TAG_HIDDEN])); - this.streamChannels.push(key); - } - attachEdge(start, end) { - if (end === END) { - if (start === START) throw new Error("Cannot have an edge from START to END"); - this.nodes[start].writers.push(new ChannelWrite([{ - channel: END, - value: PASSTHROUGH - }], [TAG_HIDDEN])); - } else { - this.nodes[end].triggers.push(start); - this.nodes[end].channels.push(start); - } - } - attachBranch(start, name, branch) { - if (start === START && !this.nodes[START]) this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] }); - this.nodes[start].pipe(branch.run((dests) => { - const writes = dests.map((dest) => { - if (_isSend(dest)) return dest; - return { - channel: dest === END ? END : `branch:${start}:${name}:${dest}`, - value: PASSTHROUGH - }; - }); - return new ChannelWrite(writes, [TAG_HIDDEN]); - })); - const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); - for (const end of ends) if (end !== END) { - const channelName = `branch:${start}:${name}:${end}`; - this.channels[channelName] = new EphemeralValue(); - this.nodes[end].triggers.push(channelName); - this.nodes[end].channels.push(channelName); - } - } - /** - * Returns a drawable representation of the computation graph. - */ - async getGraphAsync(config) { - const xray = config?.xray; - const graph = new Graph(); - const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); - if (startNodes[start] === void 0) return; - if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); - } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== void 0 ? await subgraphs[key].getGraphAsync({ - ...config, - xray: newXrayValue - }) : node.getGraph(config); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - function _isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; - } - function _nodeDataStr(id, data) { - if (id !== void 0 && !langgraph_node_modules_uuid_wrapper_validate(id)) return id; - else if (_isRunnableInterface(data)) try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch (error) { - return data.getName(); - } - else return data.name ?? "UnknownSchema"; - } - if (s !== void 0) startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) return -1; - else if (b > a) return 1; - else return 0; - }); - for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), - [END]: END - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== void 0) ends = branch.ends; - else ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); - } - } - for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true); - return graph; - } - /** - * Returns a drawable representation of the computation graph. - * - * @deprecated Use getGraphAsync instead. The async method will be the default in the next minor core release. - */ - getGraph(config) { - const xray = config?.xray; - const graph = new Graph(); - const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); - } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== void 0 ? subgraphs[key].getGraph({ - ...config, - xray: newXrayValue - }) : node.getGraph(config); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - function _isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; - } - function _nodeDataStr(id, data) { - if (id !== void 0 && !langgraph_node_modules_uuid_wrapper_validate(id)) return id; - else if (_isRunnableInterface(data)) try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch (error) { - return data.getName(); - } - else return data.name ?? "UnknownSchema"; - } - if (s !== void 0) startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) return -1; - else if (b > a) return 1; - else return 0; - }); - for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), - [END]: END - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== void 0) ends = branch.ends; - else ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); - } - } - return graph; - } -}; -function isCompiledGraph(x) { - return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; -} -function _escapeMermaidKeywords(key) { - if (key === "subgraph") return `"${key}"`; - return key; -} - -//#endregion - -//# sourceMappingURL=graph.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js - - - -//#region src/channels/named_barrier_value.ts -const areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)); -/** -* A channel that waits until all named values are received before making the value available. -* -* This ensures that if node N and node M both write to channel C, the value of C will not be updated -* until N and M have completed updating. -*/ -var NamedBarrierValue = class NamedBarrierValue extends BaseChannel { - lc_graph_name = "NamedBarrierValue"; - names; - seen; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set(); - } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValue(this.names); - if (typeof checkpoint !== "undefined") empty.seen = new Set(checkpoint); - return empty; - } - update(values) { - let updated = false; - for (const nodeName of values) if (this.names.has(nodeName)) { - if (!this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } - } else throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; - } - get() { - if (!areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); - return void 0; - } - checkpoint() { - return [...this.seen]; - } - consume() { - if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set(); - return true; - } - return false; - } - isAvailable() { - return !!this.names && areSetsEqual(this.names, this.seen); - } -}; -/** -* A channel that waits until all named values are received before making the value ready to be made available. -* It is only made available after finish() is called. -* @internal -*/ -var NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish extends BaseChannel { - lc_graph_name = "NamedBarrierValueAfterFinish"; - names; - seen; - finished; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set(); - this.finished = false; - } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValueAfterFinish(this.names); - if (typeof checkpoint !== "undefined") { - const [seen, finished] = checkpoint; - empty.seen = new Set(seen); - empty.finished = finished; - } - return empty; - } - update(values) { - let updated = false; - for (const nodeName of values) if (this.names.has(nodeName) && !this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } else if (!this.names.has(nodeName)) throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; - } - get() { - if (!this.finished || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); - return void 0; - } - checkpoint() { - return [[...this.seen], this.finished]; - } - consume() { - if (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set(); - this.finished = false; - return true; - } - return false; - } - finish() { - if (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) { - this.finished = true; - return true; - } - return false; - } - isAvailable() { - return this.finished && !!this.names && areSetsEqual(this.names, this.seen); - } -}; - -//#endregion - -//# sourceMappingURL=named_barrier_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/zod/meta.js - - - - -//#region src/graph/zod/meta.ts -const META_EXTRAS_DESCRIPTION_PREFIX = "lg:"; -/** -* A registry for storing and managing metadata associated with schemas. -* This class provides methods to get, extend, remove, and check metadata for a given schema. -*/ -var SchemaMetaRegistry = class { - /** - * Internal map storing schema metadata. - * @internal - */ - _map = /* @__PURE__ */ new WeakMap(); - /** - * Cache for extended schfemas. - * @internal - */ - _extensionCache = /* @__PURE__ */ new Map(); - /** - * Retrieves the metadata associated with a given schema. - * @template TValue The value type of the schema. - * @template TUpdate The update type of the schema (defaults to TValue). - * @param schema The schema to retrieve metadata for. - * @returns The associated SchemaMeta, or undefined if not present. - */ - get(schema) { - return this._map.get(schema); - } - /** - * Extends or sets the metadata for a given schema. - * @template TValue The value type of the schema. - * @template TUpdate The update type of the schema (defaults to TValue). - * @param schema The schema to extend metadata for. - * @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata. - */ - extend(schema, predicate) { - const existingMeta = this.get(schema); - this._map.set(schema, predicate(existingMeta)); - } - /** - * Removes the metadata associated with a given schema. - * @param schema The schema to remove metadata for. - * @returns The SchemaMetaRegistry instance (for chaining). - */ - remove(schema) { - this._map.delete(schema); - return this; - } - /** - * Checks if metadata exists for a given schema. - * @param schema The schema to check. - * @returns True if metadata exists, false otherwise. - */ - has(schema) { - return this._map.has(schema); - } - /** - * Returns a mapping of channel instances for each property in the schema - * using the associated metadata in the registry. - * - * This is used to create the `channels` object that's passed to the `Graph` constructor. - * - * @template T The shape of the schema. - * @param schema The schema to extract channels from. - * @returns A mapping from property names to channel instances. - */ - getChannelsForSchema(schema) { - const channels = {}; - const shape = getInteropZodObjectShape(schema); - for (const [key, channelSchema] of Object.entries(shape)) { - const meta = this.get(channelSchema); - if (meta?.reducer) channels[key] = new BinaryOperatorAggregate(meta.reducer.fn, meta.default); - else channels[key] = new LastValue(); - } - return channels; - } - /** - * Returns a modified schema that introspectively looks at all keys of the provided - * object schema, and applies the augmentations based on meta provided with those keys - * in the registry and the selectors provided in the `effects` parameter. - * - * This assumes that the passed in schema is the "root" schema object for a graph where - * the keys of the schema are the channels of the graph. Because we need to represent - * the input of a graph in a couple of different ways, the `effects` parameter allows - * us to apply those augmentations based on pre determined conditions. - * - * @param schema The root schema object to extend. - * @param effects The effects that are being applied. - * @returns The extended schema. - */ - getExtendedChannelSchemas(schema, effects) { - if (Object.keys(effects).length === 0) return schema; - const cacheKey = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); - const cache = this._extensionCache.get(cacheKey) ?? /* @__PURE__ */ new WeakMap(); - if (cache.has(schema)) return cache.get(schema); - let modifiedSchema = schema; - if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { - const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema$1]) => { - const meta = this.get(schema$1); - let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema$1 : schema$1; - if (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) { - const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema$1); - const strExtras = JSON.stringify({ - ...meta.jsonSchemaExtra, - description - }); - outputSchema = outputSchema.describe(`${META_EXTRAS_DESCRIPTION_PREFIX}${strExtras}`); - } - return [key, outputSchema]; - }); - modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); - if (isZodSchemaV3(modifiedSchema)) modifiedSchema._def.unknownKeys = "strip"; - } - if (effects.asPartial) modifiedSchema = interopZodObjectPartial(modifiedSchema); - cache.set(schema, modifiedSchema); - this._extensionCache.set(cacheKey, cache); - return modifiedSchema; - } -}; -const schemaMetaRegistry = new SchemaMetaRegistry(); -function withLangGraph(schema, meta) { - if (meta.reducer && !meta.default) { - const defaultValueGetter = getInteropZodDefaultGetter(schema); - if (defaultValueGetter != null) meta.default = defaultValueGetter; - } - if (meta.reducer) { - const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta.reducer?.schema ?? schema }); - schemaMetaRegistry.extend(schemaWithReducer, () => meta); - return schemaWithReducer; - } else { - schemaMetaRegistry.extend(schema, () => meta); - return schema; - } -} - -//#endregion - -//# sourceMappingURL=meta.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/state.js - - - - - - - - - - - - - - - - -//#region src/graph/state.ts -const state_ROOT = "__root__"; -const PartialStateSchema = Symbol.for("langgraph.state.partial"); -/** -* A graph whose nodes communicate by reading and writing to a shared state. -* Each node takes a defined `State` as input and returns a `Partial`. -* -* Each state key can optionally be annotated with a reducer function that -* will be used to aggregate the values of that key received from multiple nodes. -* The signature of a reducer function is (left: Value, right: UpdateValue) => Value. -* -* See {@link Annotation} for more on defining state. -* -* After adding nodes and edges to your graph, you must call `.compile()` on it before -* you can use it. -* -* @example -* ```ts -* import { -* type BaseMessage, -* AIMessage, -* HumanMessage, -* } from "@langchain/core/messages"; -* import { StateGraph, Annotation } from "@langchain/langgraph"; -* -* // Define a state with a single key named "messages" that will -* // combine a returned BaseMessage or arrays of BaseMessages -* const StateAnnotation = Annotation.Root({ -* sentiment: Annotation, -* messages: Annotation({ -* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { -* if (Array.isArray(right)) { -* return left.concat(right); -* } -* return left.concat([right]); -* }, -* default: () => [], -* }), -* }); -* -* const graphBuilder = new StateGraph(StateAnnotation); -* -* // A node in the graph that returns an object with a "messages" key -* // will update the state by combining the existing value with the returned one. -* const myNode = (state: typeof StateAnnotation.State) => { -* return { -* messages: [new AIMessage("Some new response")], -* sentiment: "positive", -* }; -* }; -* -* const graph = graphBuilder -* .addNode("myNode", myNode) -* .addEdge("__start__", "myNode") -* .addEdge("myNode", "__end__") -* .compile(); -* -* await graph.invoke({ messages: [new HumanMessage("how are you?")] }); -* -* // { -* // messages: [HumanMessage("how are you?"), AIMessage("Some new response")], -* // sentiment: "positive", -* // } -* ``` -*/ -var StateGraph = class extends Graph$1 { - channels = {}; - waitingEdges = /* @__PURE__ */ new Set(); - /** @internal */ - _schemaDefinition; - /** @internal */ - _schemaRuntimeDefinition; - /** @internal */ - _inputDefinition; - /** @internal */ - _inputRuntimeDefinition; - /** @internal */ - _outputDefinition; - /** @internal */ - _outputRuntimeDefinition; - /** - * Map schemas to managed values - * @internal - */ - _schemaDefinitions = /* @__PURE__ */ new Map(); - /** @internal */ - _metaRegistry = schemaMetaRegistry; - /** @internal Used only for typing. */ - _configSchema; - /** @internal */ - _configRuntimeSchema; - /** @internal */ - _interrupt; - /** @internal */ - _writer; - constructor(fields, contextSchema) { - super(); - if (isZodStateGraphArgsWithStateSchema(fields)) { - const stateDef = this._metaRegistry.getChannelsForSchema(fields.state); - const inputDef = fields.input != null ? this._metaRegistry.getChannelsForSchema(fields.input) : stateDef; - const outputDef = fields.output != null ? this._metaRegistry.getChannelsForSchema(fields.output) : stateDef; - this._schemaDefinition = stateDef; - this._schemaRuntimeDefinition = fields.state; - this._inputDefinition = inputDef; - this._inputRuntimeDefinition = fields.input ?? PartialStateSchema; - this._outputDefinition = outputDef; - this._outputRuntimeDefinition = fields.output ?? fields.state; - } else if (isInteropZodObject(fields)) { - const stateDef = this._metaRegistry.getChannelsForSchema(fields); - this._schemaDefinition = stateDef; - this._schemaRuntimeDefinition = fields; - this._inputDefinition = stateDef; - this._inputRuntimeDefinition = PartialStateSchema; - this._outputDefinition = stateDef; - this._outputRuntimeDefinition = fields; - } else if (isStateGraphArgsWithInputOutputSchemas(fields)) { - this._schemaDefinition = fields.input.spec; - this._inputDefinition = fields.input.spec; - this._outputDefinition = fields.output.spec; - } else if (isStateGraphArgsWithStateSchema(fields)) { - this._schemaDefinition = fields.stateSchema.spec; - this._inputDefinition = fields.input?.spec ?? this._schemaDefinition; - this._outputDefinition = fields.output?.spec ?? this._schemaDefinition; - } else if (isStateDefinition(fields) || isAnnotationRoot(fields)) { - const spec = isAnnotationRoot(fields) ? fields.spec : fields; - this._schemaDefinition = spec; - } else if (isStateGraphArgs(fields)) { - const spec = _getChannels(fields.channels); - this._schemaDefinition = spec; - } else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema."); - this._inputDefinition ??= this._schemaDefinition; - this._outputDefinition ??= this._schemaDefinition; - this._addSchema(this._schemaDefinition); - this._addSchema(this._inputDefinition); - this._addSchema(this._outputDefinition); - function isOptions(options) { - return typeof options === "object" && options != null && !("spec" in options) && !isInteropZodObject(options); - } - if (isOptions(contextSchema)) { - if (isInteropZodObject(contextSchema.context)) this._configRuntimeSchema = contextSchema.context; - this._interrupt = contextSchema.interrupt; - this._writer = contextSchema.writer; - } else if (isInteropZodObject(contextSchema)) this._configRuntimeSchema = contextSchema; - } - get allEdges() { - return new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); - } - _addSchema(stateDefinition) { - if (this._schemaDefinitions.has(stateDefinition)) return; - this._schemaDefinitions.set(stateDefinition, stateDefinition); - for (const [key, val] of Object.entries(stateDefinition)) { - let channel; - if (typeof val === "function") channel = val(); - else channel = val; - if (this.channels[key] !== void 0) { - if (this.channels[key] !== channel) { - if (channel.lc_graph_name !== "LastValue") throw new Error(`Channel "${key}" already exists with a different type.`); - } - } else this.channels[key] = channel; - } - } - addNode(...args) { - function isMultipleNodes(args$1) { - return args$1.length >= 1 && typeof args$1[0] !== "string"; - } - const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - if (key in this.channels) throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); - for (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); - if (key === END || key === START) throw new Error(`Node \`${key}\` is reserved.`); - let inputSpec = this._schemaDefinition; - if (options?.input !== void 0) { - if (isInteropZodObject(options.input)) inputSpec = this._metaRegistry.getChannelsForSchema(options.input); - else if (options.input.spec !== void 0) inputSpec = options.input.spec; - } - if (inputSpec !== void 0) this._addSchema(inputSpec); - let runnable; - if (Runnable.isRunnable(action)) runnable = action; - else if (typeof action === "function") runnable = new RunnableCallable({ - func: action, - name: key, - trace: false - }); - else runnable = _coerceToRunnable(action); - let cachePolicy = options?.cachePolicy; - if (typeof cachePolicy === "boolean") cachePolicy = cachePolicy ? {} : void 0; - const nodeSpec = { - runnable, - retryPolicy: options?.retryPolicy, - cachePolicy, - metadata: options?.metadata, - input: inputSpec ?? this._schemaDefinition, - subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends, - defer: options?.defer - }; - this.nodes[key] = nodeSpec; - } - return this; - } - addEdge(startKey, endKey) { - if (typeof startKey === "string") return super.addEdge(startKey, endKey); - if (this.compiled) console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - for (const start of startKey) { - if (start === END) throw new Error("END cannot be a start node"); - if (!Object.keys(this.nodes).some((node) => node === start)) throw new Error(`Need to add a node named "${start}" first`); - } - if (endKey === END) throw new Error("END cannot be an end node"); - if (!Object.keys(this.nodes).some((node) => node === endKey)) throw new Error(`Need to add a node named "${endKey}" first`); - this.waitingEdges.add([startKey, endKey]); - return this; - } - addSequence(nodes) { - const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); - if (parsedNodes.length === 0) throw new Error("Sequence requires at least one node."); - let previousNode; - for (const [key, action, options] of parsedNodes) { - if (key in this.nodes) throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); - const validKey = key; - this.addNode(validKey, action, options); - if (previousNode != null) this.addEdge(previousNode, validKey); - previousNode = validKey; - } - return this; - } - compile({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); - const outputChannels = outputKeys.length === 1 && outputKeys[0] === state_ROOT ? state_ROOT : outputKeys; - const streamKeys = Object.keys(this.channels); - const streamChannels = streamKeys.length === 1 && streamKeys[0] === state_ROOT ? state_ROOT : streamKeys; - const userInterrupt = this._interrupt; - const compiled = new CompiledStateGraph({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - ...this.channels, - [START]: new EphemeralValue() - }, - inputChannels: START, - outputChannels, - streamChannels, - streamMode: "updates", - store, - cache, - name, - description, - userInterrupt - }); - compiled.attachNode(START); - for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); - compiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false }); - for (const [key] of Object.entries(this.nodes)) compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false }); - for (const [start, end] of this.edges) compiled.attachEdge(start, end); - for (const [starts, end] of this.waitingEdges) compiled.attachEdge(starts, end); - for (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch); - return compiled.validate(); - } -}; -function _getChannels(schema) { - const channels = {}; - for (const [name, val] of Object.entries(schema)) if (name === state_ROOT) channels[name] = getChannel(val); - else channels[name] = getChannel(val); - return channels; -} -/** -* Final result from building and compiling a {@link StateGraph}. -* Should not be instantiated directly, only using the StateGraph `.compile()` -* instance method. -*/ -var CompiledStateGraph = class extends CompiledGraph { - /** - * The description of the compiled graph. - * This is used by the supervisor agent to describe the handoff to the agent. - */ - description; - /** @internal */ - _metaRegistry = schemaMetaRegistry; - constructor({ description,...rest }) { - super(rest); - this.description = description; - } - attachNode(key, node) { - let outputKeys; - if (key === START) outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); - else outputKeys = Object.keys(this.builder.channels); - function _getRoot(input) { - if (isCommand(input)) { - if (input.graph === Command.PARENT) return null; - return input._updateAsTuples(); - } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) { - const updates = []; - for (const i of input) if (isCommand(i)) { - if (i.graph === Command.PARENT) continue; - updates.push(...i._updateAsTuples()); - } else updates.push([state_ROOT, i]); - return updates; - } else if (input != null) return [[state_ROOT, input]]; - return null; - } - const nodeKey = key; - function _getUpdates(input) { - if (!input) return null; - else if (isCommand(input)) { - if (input.graph === Command.PARENT) return null; - return input._updateAsTuples().filter(([k]) => outputKeys.includes(k)); - } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) { - const updates = []; - for (const item of input) if (isCommand(item)) { - if (item.graph === Command.PARENT) continue; - updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); - } else { - const itemUpdates = _getUpdates(item); - if (itemUpdates) updates.push(...itemUpdates ?? []); - } - return updates; - } else if (typeof input === "object" && !Array.isArray(input)) return Object.entries(input).filter(([k]) => outputKeys.includes(k)); - else { - const typeofInput = Array.isArray(input) ? "array" : typeof input; - throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); - } - } - const stateWriteEntries = [{ - value: PASSTHROUGH, - mapper: new RunnableCallable({ - func: outputKeys.length && outputKeys[0] === state_ROOT ? _getRoot : _getUpdates, - trace: false, - recurse: false - }) - }]; - if (key === START) this.nodes[key] = new PregelNode({ - tags: [TAG_HIDDEN], - triggers: [START], - channels: [START], - writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])] - }); - else { - const inputDefinition = node?.input ?? this.builder._schemaDefinition; - const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); - const isSingleInput = Object.keys(inputValues).length === 1 && state_ROOT in inputValues; - const branchChannel = `branch:to:${key}`; - this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish() : new EphemeralValue(false); - this.nodes[key] = new PregelNode({ - triggers: [branchChannel], - channels: isSingleInput ? Object.keys(inputValues) : inputValues, - writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])], - mapper: isSingleInput ? void 0 : (input) => { - return Object.fromEntries(Object.entries(input).filter(([k]) => k in inputValues)); - }, - bound: node?.runnable, - metadata: node?.metadata, - retryPolicy: node?.retryPolicy, - cachePolicy: node?.cachePolicy, - subgraphs: node?.subgraphs, - ends: node?.ends - }); - } - } - attachEdge(starts, end) { - if (end === END) return; - if (typeof starts === "string") this.nodes[starts].writers.push(new ChannelWrite([{ - channel: `branch:to:${end}`, - value: null - }], [TAG_HIDDEN])); - else if (Array.isArray(starts)) { - const channelName = `join:${starts.join("+")}:${end}`; - this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts)); - this.nodes[end].triggers.push(channelName); - for (const start of starts) this.nodes[start].writers.push(new ChannelWrite([{ - channel: channelName, - value: start - }], [TAG_HIDDEN])); - } - } - attachBranch(start, _, branch, options = { withReader: true }) { - const branchWriter = async (packets, config) => { - const filteredPackets = packets.filter((p) => p !== END); - if (!filteredPackets.length) return; - const writes = filteredPackets.map((p) => { - if (_isSend(p)) return p; - return { - channel: p === END ? p : `branch:to:${p}`, - value: start - }; - }); - await ChannelWrite.doWrite({ - ...config, - tags: (config.tags ?? []).concat([TAG_HIDDEN]) - }, writes); - }; - this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config) => ChannelRead.doRead(config, this.streamChannels ?? this.outputChannels, true) : void 0)); - } - async _validateInput(input) { - if (input == null) return input; - const schema = (() => { - const input$1 = this.builder._inputRuntimeDefinition; - const schema$1 = this.builder._schemaRuntimeDefinition; - const apply = (schema$2) => { - if (schema$2 == null) return void 0; - return this._metaRegistry.getExtendedChannelSchemas(schema$2, { withReducerSchema: true }); - }; - if (isInteropZodObject(input$1)) return apply(input$1); - if (input$1 === PartialStateSchema) return interopZodObjectPartial(apply(schema$1)); - return void 0; - })(); - if (isCommand(input)) { - const parsedInput = input; - if (input.update && schema != null) parsedInput.update = interopParse(schema, input.update); - return parsedInput; - } - if (schema != null) return interopParse(schema, input); - return input; - } - isInterrupted(input) { - return isInterrupted(input); - } - async _validateContext(config) { - const configSchema = this.builder._configRuntimeSchema; - if (isInteropZodObject(configSchema)) interopParse(configSchema, config); - return config; - } -}; -function isStateDefinition(obj) { - return typeof obj === "object" && obj !== null && !Array.isArray(obj) && Object.keys(obj).length > 0 && Object.values(obj).every((v) => typeof v === "function" || isBaseChannel(v)); -} -function isAnnotationRoot(obj) { - return typeof obj === "object" && obj !== null && "lc_graph_name" in obj && obj.lc_graph_name === "AnnotationRoot"; -} -function isStateGraphArgs(obj) { - return typeof obj === "object" && obj !== null && obj.channels !== void 0; -} -function isStateGraphArgsWithStateSchema(obj) { - return typeof obj === "object" && obj !== null && obj.stateSchema !== void 0; -} -function isStateGraphArgsWithInputOutputSchemas(obj) { - return typeof obj === "object" && obj !== null && obj.stateSchema === void 0 && obj.input !== void 0 && obj.output !== void 0; -} -function isZodStateGraphArgsWithStateSchema(value) { - if (typeof value !== "object" || value == null) return false; - if (!("state" in value) || !isInteropZodObject(value.state)) return false; - if ("input" in value && !isInteropZodObject(value.input)) return false; - if ("output" in value && !isInteropZodObject(value.output)) return false; - return true; -} -function _controlBranch(value) { - if (_isSend(value)) return [value]; - const commands = []; - if (isCommand(value)) commands.push(value); - else if (Array.isArray(value)) commands.push(...value.filter(isCommand)); - const destinations = []; - for (const command of commands) { - if (command.graph === Command.PARENT) throw new ParentCommand(command); - if (_isSend(command.goto)) destinations.push(command.goto); - else if (typeof command.goto === "string") destinations.push(command.goto); - else if (Array.isArray(command.goto)) destinations.push(...command.goto); - } - return destinations; -} -function _getControlBranch() { - const CONTROL_BRANCH_PATH = new RunnableCallable({ - func: _controlBranch, - tags: [TAG_HIDDEN], - trace: false, - recurse: false, - name: "" - }); - return new Branch({ path: CONTROL_BRANCH_PATH }); -} - -//#endregion - -//# sourceMappingURL=state.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/message.js - - - - - -//#region src/graph/message.ts -const REMOVE_ALL_MESSAGES = "__remove_all__"; -/** -* Prebuilt reducer that combines returned messages. -* Can handle standard messages and special modifiers like {@link RemoveMessage} -* instances. -*/ -function messagesStateReducer(left, right) { - const leftArray = Array.isArray(left) ? left : [left]; - const rightArray = Array.isArray(right) ? right : [right]; - const leftMessages = leftArray.map(utils_coerceMessageLikeToMessage); - const rightMessages = rightArray.map(utils_coerceMessageLikeToMessage); - for (const m of leftMessages) if (m.id === null || m.id === void 0) { - m.id = node_modules_uuid_wrapper_v4(); - m.lc_kwargs.id = m.id; - } - let removeAllIdx; - for (let i = 0; i < rightMessages.length; i += 1) { - const m = rightMessages[i]; - if (m.id === null || m.id === void 0) { - m.id = node_modules_uuid_wrapper_v4(); - m.lc_kwargs.id = m.id; - } - if (m.getType() === "remove" && m.id === REMOVE_ALL_MESSAGES) removeAllIdx = i; - } - if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1); - const merged = [...leftMessages]; - const mergedById = new Map(merged.map((m, i) => [m.id, i])); - const idsToRemove = /* @__PURE__ */ new Set(); - for (const m of rightMessages) { - const existingIdx = mergedById.get(m.id); - if (existingIdx !== void 0) if (m.getType() === "remove") idsToRemove.add(m.id); - else { - idsToRemove.delete(m.id); - merged[existingIdx] = m; - } - else { - if (m.getType() === "remove") throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); - mergedById.set(m.id, merged.length); - merged.push(m); - } - } - return merged.filter((m) => !idsToRemove.has(m.id)); -} -/** @ignore */ -var MessageGraph = class extends StateGraph { - constructor() { - super({ channels: { __root__: { - reducer: messagesStateReducer, - default: () => [] - } } }); - } -}; -/** -* Manually push a message to a message stream. -* -* This is useful when you need to push a manually created message before the node -* has finished executing. -* -* When a message is pushed, it will be automatically persisted to the state after the node has finished executing. -* To disable persisting, set `options.stateKey` to `null`. -* -* @param message The message to push. The message must have an ID set, otherwise an error will be thrown. -* @param options RunnableConfig / Runtime coming from node context. -*/ -function pushMessage(message, options) { - const { stateKey: userStateKey,...userConfig } = options ?? {}; - const config = ensureLangGraphConfig(userConfig); - let stateKey = userStateKey ?? "messages"; - if (userStateKey === null) stateKey = void 0; - const validMessage = coerceMessageLikeToMessage(message); - if (!validMessage.id) throw new Error("Message ID is required."); - const callbacks = (() => { - if (Array.isArray(config.callbacks)) return config.callbacks; - if (typeof config.callbacks !== "undefined") return config.callbacks.handlers; - return []; - })(); - const messagesHandler = callbacks.find((cb) => "name" in cb && cb.name === "StreamMessagesHandler"); - if (messagesHandler) { - const metadata = config.metadata ?? {}; - const namespace = (metadata.langgraph_checkpoint_ns ?? "").split("|"); - messagesHandler._emit([namespace, metadata], validMessage, void 0, false); - } - if (stateKey) config.configurable?.__pregel_send?.([[stateKey, validMessage]]); - return validMessage; -} - -//#endregion - -//# sourceMappingURL=message.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/func/index.js - - - - - - - - - - -//#region src/func/index.ts -/** -* Define a LangGraph task using the `task` function. -* -* Tasks can only be called from within an {@link entrypoint} or from within a StateGraph. -* A task can be called like a regular function with the following differences: -* -* - When a checkpointer is enabled, the function inputs and outputs must be serializable. -* - The wrapped function can only be called from within an entrypoint or StateGraph. -* - Calling the function produces a promise. This makes it easy to parallelize tasks. -* -* @typeParam ArgsT - The type of arguments the task function accepts -* @typeParam OutputT - The type of value the task function returns -* @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task -* @param func - The function that executes this task -* @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise -* -* @example basic example -* ```typescript -* const addOne = task("add", async (a: number) => a + 1); -* -* const workflow = entrypoint("example", async (numbers: number[]) => { -* const promises = numbers.map(n => addOne(n)); -* const results = await Promise.all(promises); -* return results; -* }); -* -* // Call the entrypoint -* await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] -* ``` -* -* @example using a retry policy -* ```typescript -* const addOne = task({ -* name: "add", -* retry: { maxAttempts: 3 } -* }, -* async (a: number) => a + 1 -* ); -* -* const workflow = entrypoint("example", async (numbers: number[]) => { -* const promises = numbers.map(n => addOne(n)); -* const results = await Promise.all(promises); -* return results; -* }); -* ``` -* @category Functional API -*/ -function task(optionsOrName, func) { - const options = typeof optionsOrName === "string" ? { - name: optionsOrName, - retry: void 0, - cachePolicy: void 0 - } : optionsOrName; - const { name, retry } = options; - if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write."); - const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : void 0); - let cache; - if (typeof cachePolicy === "boolean") cache = cachePolicy ? {} : void 0; - else cache = cachePolicy; - return (...args) => { - return call({ - func, - name, - retry, - cache - }, ...args); - }; -} -/** -* Define a LangGraph workflow using the `entrypoint` function. -* -* ### Function signature -* -* The wrapped function must accept at most **two parameters**. The first parameter -* is the input to the function. The second (optional) parameter is a -* {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to -* the function, you can pass them as an object. -* -* ### Helper functions -* -* #### Streaming -* To write data to the "custom" stream, use the {@link getWriter} function, or the -* {@link LangGraphRunnableConfig.writer} property. -* -* #### State management -* The {@link getPreviousState} function can be used to access the previous state -* that was returned from the last invocation of the entrypoint on the same thread id. -* -* If you wish to save state other than the return value, you can use the -* {@link entrypoint.final} function. -* -* @typeParam InputT - The type of input the entrypoint accepts -* @typeParam OutputT - The type of output the entrypoint produces -* @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint -* @param func - The function that executes this entrypoint -* @returns A {@link Pregel} instance that can be run to execute the workflow -* -* @example Using entrypoint and tasks -* ```typescript -* import { task, entrypoint } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* import { interrupt, Command } from "@langchain/langgraph"; -* -* const composeEssay = task("compose", async (topic: string) => { -* await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation -* return `An essay about ${topic}`; -* }); -* -* const reviewWorkflow = entrypoint({ -* name: "review", -* checkpointer: new MemorySaver() -* }, async (topic: string) => { -* const essay = await composeEssay(topic); -* const humanReview = await interrupt({ -* question: "Please provide a review", -* essay -* }); -* return { -* essay, -* review: humanReview -* }; -* }); -* -* // Example configuration for the workflow -* const config = { -* configurable: { -* thread_id: "some_thread" -* } -* }; -* -* // Topic for the essay -* const topic = "cats"; -* -* // Stream the workflow to generate the essay and await human review -* for await (const result of reviewWorkflow.stream(topic, config)) { -* console.log(result); -* } -* -* // Example human review provided after the interrupt -* const humanReview = "This essay is great."; -* -* // Resume the workflow with the provided human review -* for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) { -* console.log(result); -* } -* ``` -* -* @example Accessing the previous return value -* ```typescript -* import { entrypoint, getPreviousState } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* -* const accumulator = entrypoint({ -* name: "accumulator", -* checkpointer: new MemorySaver() -* }, async (input: string) => { -* const previous = getPreviousState(); -* return previous !== undefined ? `${previous } ${input}` : input; -* }); -* -* const config = { -* configurable: { -* thread_id: "some_thread" -* } -* }; -* await accumulator.invoke("hello", config); // returns "hello" -* await accumulator.invoke("world", config); // returns "hello world" -* ``` -* -* @example Using entrypoint.final to save a value -* ```typescript -* import { entrypoint, getPreviousState } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* -* const myWorkflow = entrypoint({ -* name: "accumulator", -* checkpointer: new MemorySaver() -* }, async (num: number) => { -* const previous = getPreviousState(); -* -* // This will return the previous value to the caller, saving -* // 2 * num to the checkpoint, which will be used in the next invocation -* // for the `previous` parameter. -* return entrypoint.final({ -* value: previous ?? 0, -* save: 2 * num -* }); -* }); -* -* const config = { -* configurable: { -* thread_id: "some_thread" -* } -* }; -* -* await myWorkflow.invoke(3, config); // 0 (previous was undefined) -* await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation) -* ``` -* @category Functional API -*/ -const entrypoint = function entrypoint$1(optionsOrName, func) { - const { name, checkpointer, store, cache } = typeof optionsOrName === "string" ? { - name: optionsOrName, - checkpointer: void 0, - store: void 0 - } : optionsOrName; - if (utils_isAsyncGeneratorFunction(func) || utils_isGeneratorFunction(func)) throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); - const streamMode = "updates"; - const bound = getRunnableForEntrypoint(name, func); - function isEntrypointFinal(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; - } - const pluckReturnValue = new RunnableCallable({ - name: "pluckReturnValue", - func: (value) => { - return isEntrypointFinal(value) ? value.value : value; - } - }); - const pluckSaveValue = new RunnableCallable({ - name: "pluckSaveValue", - func: (value) => { - return isEntrypointFinal(value) ? value.save : value; - } - }); - const entrypointNode = new PregelNode({ - bound, - triggers: [START], - channels: [START], - writers: [new ChannelWrite([{ - channel: END, - value: PASSTHROUGH, - mapper: pluckReturnValue - }, { - channel: PREVIOUS, - value: PASSTHROUGH, - mapper: pluckSaveValue - }], [TAG_HIDDEN])] - }); - return new Pregel({ - name, - checkpointer, - nodes: { [name]: entrypointNode }, - channels: { - [START]: new EphemeralValue(), - [END]: new LastValue(), - [PREVIOUS]: new LastValue() - }, - inputChannels: START, - outputChannels: END, - streamChannels: END, - streamMode, - store, - cache - }); -}; -entrypoint.final = function final({ value, save }) { - return { - value, - save, - __lg_type: "__pregel_final" - }; -}; -/** -* A helper utility function for use with the functional API that returns the previous -* state from the checkpoint from the last invocation of the current thread. -* -* This function allows workflows to access state that was saved in previous runs -* using {@link entrypoint.final}. -* -* @typeParam StateT - The type of the state that was previously saved -* @returns The previous saved state from the last invocation of the current thread -* -* @example -* ```typescript -* const previousState = getPreviousState<{ counter: number }>(); -* const newCount = (previousState?.counter ?? 0) + 1; -* ``` -* @category Functional API -*/ -function getPreviousState() { - const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); - return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE]; -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/messages_annotation.js - - - - - -//#region src/graph/messages_annotation.ts -/** -* Prebuilt state annotation that combines returned messages. -* Can handle standard messages and special modifiers like {@link RemoveMessage} -* instances. -* -* Specifically, importing and using the prebuilt MessagesAnnotation like this: -* -* @example -* ```ts -* import { MessagesAnnotation, StateGraph } from "@langchain/langgraph"; -* -* const graph = new StateGraph(MessagesAnnotation) -* .addNode(...) -* ... -* ``` -* -* Is equivalent to initializing your state manually like this: -* -* @example -* ```ts -* import { BaseMessage } from "@langchain/core/messages"; -* import { Annotation, StateGraph, messagesStateReducer } from "@langchain/langgraph"; -* -* export const StateAnnotation = Annotation.Root({ -* messages: Annotation({ -* reducer: messagesStateReducer, -* default: () => [], -* }), -* }); -* -* const graph = new StateGraph(StateAnnotation) -* .addNode(...) -* ... -* ``` -*/ -const MessagesAnnotation = Annotation.Root({ messages: Annotation({ - reducer: messagesStateReducer, - default: () => [] -}) }); -/** -* Prebuilt schema meta for Zod state definition. -* -* @example -* ```ts -* import { z } from "zod/v4-mini"; -* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; -* -* const AgentState = z.object({ -* messages: z.custom().register(registry, MessagesZodMeta), -* }); -* ``` -*/ -const MessagesZodMeta = { - reducer: { fn: messagesStateReducer }, - jsonSchemaExtra: { langgraph_type: "messages" }, - default: () => [] -}; -/** -* Prebuilt state object that uses Zod to combine returned messages. -* This utility is synonymous with the `MessagesAnnotation` annotation, -* but uses Zod as the way to express messages state. -* -* You can use import and use this prebuilt schema like this: -* -* @example -* ```ts -* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; -* -* const graph = new StateGraph(MessagesZodState) -* .addNode(...) -* ... -* ``` -* -* Which is equivalent to initializing the schema object manually like this: -* -* @example -* ```ts -* import { z } from "zod"; -* import type { BaseMessage, BaseMessageLike } from "@langchain/core/messages"; -* import { StateGraph, messagesStateReducer } from "@langchain/langgraph"; -* import "@langchain/langgraph/zod"; -* -* const AgentState = z.object({ -* messages: z -* .custom() -* .default(() => []) -* .langgraph.reducer( -* messagesStateReducer, -* z.custom() -* ), -* }); -* const graph = new StateGraph(AgentState) -* .addNode(...) -* ... -* ``` -*/ -const MessagesZodState = objectType({ messages: withLangGraph(custom(), MessagesZodMeta) }); - -//#endregion - -//# sourceMappingURL=messages_annotation.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/index.js - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/any_value.js - - - -//#region src/channels/any_value.ts -/** -* Stores the last value received, assumes that if multiple values are received, they are all equal. -* -* Note: Unlike 'LastValue' if multiple nodes write to this channel in a single step, the values -* will be continuously overwritten. -*/ -var AnyValue = class AnyValue extends BaseChannel { - lc_graph_name = "AnyValue"; - value = []; - constructor() { - super(); - } - fromCheckpoint(checkpoint) { - const empty = new AnyValue(); - if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) { - const updated = this.value.length > 0; - this.value = []; - return updated; - } - this.value = [values[values.length - 1]]; - return false; - } - get() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } -}; - -//#endregion - -//# sourceMappingURL=any_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js - - - - -//#region src/channels/dynamic_barrier_value.ts -function isWaitForNames(v) { - return v.__names !== void 0; -} -/** -* A channel that switches between two states -* -* - in the "priming" state it can't be read from. -* - if it receives a WaitForNames update, it switches to the "waiting" state. -* - in the "waiting" state it collects named values until all are received. -* - once all named values are received, it can be read once, and it switches -* back to the "priming" state. -*/ -var DynamicBarrierValue = class DynamicBarrierValue extends BaseChannel { - lc_graph_name = "DynamicBarrierValue"; - names; - seen; - constructor() { - super(); - this.names = void 0; - this.seen = /* @__PURE__ */ new Set(); - } - fromCheckpoint(checkpoint) { - const empty = new DynamicBarrierValue(); - if (typeof checkpoint !== "undefined") { - empty.names = new Set(checkpoint[0]); - empty.seen = new Set(checkpoint[1]); - } - return empty; - } - update(values) { - const waitForNames = values.filter(isWaitForNames); - if (waitForNames.length > 0) { - if (waitForNames.length > 1) throw new InvalidUpdateError("Received multiple WaitForNames updates in the same step."); - this.names = new Set(waitForNames[0].__names); - return true; - } else if (this.names !== void 0) { - let updated = false; - for (const value of values) { - if (isWaitForNames(value)) throw new Error("Assertion Error: Received unexpected WaitForNames instance."); - if (this.names.has(value) && !this.seen.has(value)) { - this.seen.add(value); - updated = true; - } - } - return updated; - } - return false; - } - consume() { - if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set(); - this.names = void 0; - return true; - } - return false; - } - get() { - if (!this.names || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); - return void 0; - } - checkpoint() { - return [this.names ? [...this.names] : void 0, [...this.seen]]; - } - isAvailable() { - return !!this.names && areSetsEqual(this.names, this.seen); - } -}; - -//#endregion - -//# sourceMappingURL=dynamic_barrier_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/index.js - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/web.js - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/writer.js - - -//#region src/writer.ts -function writer(chunk) { - const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (!config) throw new Error("Called interrupt() outside the context of a graph."); - const conf = config.configurable; - if (!conf) throw new Error("No configurable found in config"); - return conf.writer?.(chunk); -} - -//#endregion - -//# sourceMappingURL=writer.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/index.js - - - - - - - - - - - - - - - - -//#region src/index.ts -initializeAsyncLocalStorageSingleton(); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./src/tools/pr-analysis-tools.ts -/** - * PR Analysis Tools for LangChain Agent - * These tools are used by the agent to analyze different aspects of PR changes - */ - - -/** - * Parse git diff into structured file changes - */ -function parseDiff(diff) { - const files = []; - const lines = diff.split('\n'); - let currentFile = null; - let currentDiff = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - // New file detected - if (line.startsWith('diff --git')) { - // Save previous file - if (currentFile) { - files.push({ - ...currentFile, - diff: currentDiff.join('\n'), - }); - } - // Parse file path - const match = line.match(/^diff --git a\/(.+?) b\/(.+?)$/); - if (match) { - const filePath = match[2] !== '/dev/null' ? match[2] : match[1]; - currentFile = { - path: filePath, - additions: 0, - deletions: 0, - language: detectLanguage(filePath), - }; - currentDiff = [line]; - } - } - else if (line.startsWith('new file') && currentFile) { - currentFile.status = 'A'; - currentDiff.push(line); - } - else if (line.startsWith('deleted file') && currentFile) { - currentFile.status = 'D'; - currentDiff.push(line); - } - else if (line.startsWith('rename from') && currentFile) { - currentFile.status = 'R'; - const oldPath = line.replace('rename from ', '').trim(); - currentFile.oldPath = oldPath; - currentDiff.push(line); - } - else if (line.startsWith('+') && !line.startsWith('+++') && currentFile) { - currentFile.additions = (currentFile.additions || 0) + 1; - currentDiff.push(line); - } - else if (line.startsWith('-') && !line.startsWith('---') && currentFile) { - currentFile.deletions = (currentFile.deletions || 0) + 1; - currentDiff.push(line); - } - else if (currentFile) { - currentDiff.push(line); - } - } - // Save last file - if (currentFile) { - files.push({ - ...currentFile, - diff: currentDiff.join('\n'), - }); - } - return files; -} -/** - * Detect programming language from file extension - */ -function detectLanguage(filePath) { - const ext = filePath.split('.').pop()?.toLowerCase(); - const languageMap = { - ts: 'typescript', - tsx: 'typescript', - js: 'javascript', - jsx: 'javascript', - py: 'python', - java: 'java', - go: 'go', - rs: 'rust', - rb: 'ruby', - php: 'php', - cs: 'csharp', - cpp: 'cpp', - c: 'c', - swift: 'swift', - kt: 'kotlin', - yaml: 'yaml', - yml: 'yaml', - json: 'json', - md: 'markdown', - }; - return languageMap[ext || ''] || 'unknown'; -} -/** - * Create file analyzer tool - */ -function createFileAnalyzerTool() { - return new tools_DynamicStructuredTool({ - name: 'analyze_file', - description: 'Analyze a specific file from the diff to identify risks, complexity, and provide recommendations', - schema: objectType({ - filePath: stringType().describe('Path of the file to analyze'), - diffContent: stringType().describe('The diff content for this file'), - }), - func: async ({ filePath, diffContent }) => { - // Parse the diff to extract changes - const additions = (diffContent.match(/^\+[^+]/gm) || []).length; - const deletions = (diffContent.match(/^-[^-]/gm) || []).length; - const totalChanges = additions + deletions; - // Basic complexity scoring - let complexity = 1; - if (totalChanges > 100) - complexity = 4; - else if (totalChanges > 50) - complexity = 3; - else if (totalChanges > 20) - complexity = 2; - // Detect potential risks - const risks = []; - // Check for security-related patterns - if (/eval\(|exec\(|system\(/i.test(diffContent)) { - risks.push('Potentially dangerous function calls detected (eval, exec, system)'); - } - if (/password|secret|api[_-]?key|token/i.test(diffContent) && /['"]/i.test(diffContent)) { - risks.push('Possible hardcoded credentials or secrets'); - } - if (/TODO|FIXME|XXX|HACK/i.test(diffContent)) { - risks.push('Contains TODO/FIXME comments indicating incomplete work'); - } - if (totalChanges > 200) { - risks.push('Very large change set - difficult to review thoroughly'); - } - // Check for error handling - const hasTryCatch = /try\s*{|catch\s*\(/i.test(diffContent); - const hasThrow = /throw\s+/i.test(diffContent); - if (hasThrow && !hasTryCatch) { - risks.push('Throws errors without apparent error handling'); - } - return JSON.stringify({ - path: filePath, - additions, - deletions, - complexity, - risks, - language: detectLanguage(filePath), - }); - }, - }); -} -/** - * Create risk detector tool - */ -function createRiskDetectorTool() { - return new tools_DynamicStructuredTool({ - name: 'detect_risks', - description: 'Detect security, quality, and breaking change risks in the PR', - schema: objectType({ - diff: stringType().describe('The full diff to analyze for risks'), - context: stringType().optional().describe('Additional context about the changes'), - }), - func: async ({ diff, context }) => { - const risks = []; - // Security risks - if (/sql.*=.*\+|SQL.*=.*\+/i.test(diff)) { - risks.push({ - type: 'security', - severity: 'high', - description: 'Potential SQL injection - string concatenation in SQL queries', - }); - } - if (/innerHTML|dangerouslySetInnerHTML/i.test(diff)) { - risks.push({ - type: 'security', - severity: 'medium', - description: 'XSS risk - using innerHTML or dangerouslySetInnerHTML', - }); - } - // Breaking changes - if (/export\s+(interface|type|class|function)\s+\w+/i.test(diff) && /-.*export/i.test(diff)) { - risks.push({ - type: 'breaking', - severity: 'high', - description: 'Potential breaking change - modified or removed export', - }); - } - // Code quality - if ((diff.match(/console\.log/g) || []).length > 3) { - risks.push({ - type: 'quality', - severity: 'low', - description: 'Multiple console.log statements - consider using proper logging', - }); - } - // Performance - if (/for.*for|while.*while/i.test(diff) && /O\(n\^2\)/i.test(diff)) { - risks.push({ - type: 'performance', - severity: 'medium', - description: 'Nested loops detected - potential O(n²) complexity', - }); - } - return JSON.stringify({ - riskCount: risks.length, - risks, - context: context || 'No additional context provided', - }); - }, - }); -} -/** - * Create complexity scorer tool - */ -function createComplexityScorerTool() { - return new tools_DynamicStructuredTool({ - name: 'score_complexity', - description: 'Calculate overall complexity score for the PR (1-5 scale)', - schema: objectType({ - filesAnalyzed: arrayType(anyType()).describe('Array of analyzed files'), - totalChanges: numberType().describe('Total lines changed'), - }), - func: async ({ filesAnalyzed, totalChanges }) => { - let score = 1; - // Factor 1: Total changes - if (totalChanges > 500) - score = Math.max(score, 5); - else if (totalChanges > 300) - score = Math.max(score, 4); - else if (totalChanges > 150) - score = Math.max(score, 3); - else if (totalChanges > 50) - score = Math.max(score, 2); - // Factor 2: Number of files - const fileCount = filesAnalyzed.length; - if (fileCount > 20) - score = Math.max(score, 5); - else if (fileCount > 10) - score = Math.max(score, 4); - else if (fileCount > 5) - score = Math.max(score, 3); - // Factor 3: File complexity average - const avgFileComplexity = filesAnalyzed.reduce((sum, f) => sum + (f.complexity || 1), 0) / Math.max(fileCount, 1); - if (avgFileComplexity >= 4) - score = Math.max(score, 5); - else if (avgFileComplexity >= 3) - score = Math.max(score, 4); - return JSON.stringify({ - overallComplexity: Math.min(score, 5), - factors: { - totalChanges, - fileCount, - avgFileComplexity: avgFileComplexity.toFixed(1), - }, - recommendation: score >= 4 - ? 'High complexity - consider breaking into smaller PRs' - : score >= 3 - ? 'Moderate complexity - ensure thorough testing' - : 'Low complexity - straightforward changes', - }); - }, - }); -} -/** - * Create summary generator tool - */ -function createSummaryGeneratorTool() { - return new tools_DynamicStructuredTool({ - name: 'generate_summary', - description: 'Generate a concise summary of PR changes', - schema: objectType({ - files: arrayType(anyType()).describe('Array of changed files'), - title: stringType().optional().describe('PR title'), - }), - func: async ({ files, title }) => { - const filesByType = {}; - let totalAdditions = 0; - let totalDeletions = 0; - files.forEach((file) => { - const lang = file.language || 'other'; - filesByType[lang] = (filesByType[lang] || 0) + 1; - totalAdditions += file.additions || 0; - totalDeletions += file.deletions || 0; - }); - const mainLanguage = Object.entries(filesByType).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown'; - return JSON.stringify({ - title: title || 'Untitled PR', - fileCount: files.length, - totalAdditions, - totalDeletions, - netChange: totalAdditions - totalDeletions, - mainLanguage, - filesByType, - summary: `Changes ${files.length} file(s) with ${totalAdditions} additions and ${totalDeletions} deletions. Primary language: ${mainLanguage}.`, - }); - }, - }); -} -/** - * Create code suggestion tool for fixing issues based on reviewer comments - */ -function createCodeSuggestionTool() { - return new DynamicStructuredTool({ - name: 'suggest_code_fix', - description: 'Generate a code fix suggestion based on a reviewer comment and the associated code snippet', - schema: z.object({ - reviewerComment: z.string().describe('The reviewer\'s comment describing the issue'), - codeSnippet: z.string().describe('The original code snippet to be fixed'), - filePath: z.string().describe('Path of the file containing the code'), - prTitle: z.string().optional().describe('PR title for context'), - prContext: z.string().optional().describe('Additional PR context (repo, branch, etc.)'), - }), - func: async ({ reviewerComment, codeSnippet, filePath, prTitle, prContext }) => { - // Build the fix prompt - const prompt = `You are an expert software engineer and code-fixer. You will take a reviewer comment and the associated code snippet and produce the corrected code snippet only. - -Context: -${prContext || '(no additional context)'} -- PR Title: ${prTitle || '(unknown)'} -- File: ${filePath} - -Reviewer comment: -${reviewerComment.trim()} - -Original code snippet: -\`\`\` -${codeSnippet} -\`\`\` - -Task: -1) Apply the reviewer's requested changes to the provided code snippet. -2) Output rules (MUST follow exactly): - - Return only the corrected code snippet (no explanations, no markdown fences, no extra text). - - If only a few lines changed you may return only the updated lines, but prefer returning the full corrected snippet when structural/context changes are required. - - Preserve original code style and indentation. - - If no changes are needed, reply with exactly: NO CHANGE - - Do not include filenames, metadata, or commentary. - -Produce the corrected code now.`; - return JSON.stringify({ - filePath, - originalCode: codeSnippet, - reviewerComment, - prompt, - status: 'ready', - message: 'Code suggestion prompt prepared. The agent will use this to generate the fix.', - }); - }, - }); -} - -// EXTERNAL MODULE: external "fs" -var external_fs_ = __nccwpck_require__(9896); -// EXTERNAL MODULE: external "path" -var external_path_ = __nccwpck_require__(6928); -;// CONCATENATED MODULE: ./src/utils/arch-docs-parser.ts -/** - * Arch-Docs Parser - * Parses .arch-docs markdown files for RAG system - */ - - -/** - * Check if .arch-docs folder exists - */ -function archDocsExists(repoPath = process.cwd()) { - const archDocsPath = external_path_.join(repoPath, '.arch-docs'); - return external_fs_.existsSync(archDocsPath) && external_fs_.statSync(archDocsPath).isDirectory(); -} -/** - * Get all markdown files from .arch-docs folder - */ -function getArchDocsFiles(repoPath = process.cwd()) { - const archDocsPath = external_path_.join(repoPath, '.arch-docs'); - if (!archDocsExists(repoPath)) { - return []; - } - try { - const files = external_fs_.readdirSync(archDocsPath); - return files - .filter(file => file.endsWith('.md')) - .map(file => external_path_.join(archDocsPath, file)); - } - catch (error) { - console.warn('Error reading .arch-docs folder:', error); - return []; - } -} -/** - * Parse a markdown file into structured sections - */ -function parseMarkdownFile(filePath) { - const content = external_fs_.readFileSync(filePath, 'utf-8'); - const filename = external_path_.basename(filePath, '.md'); - const lines = content.split('\n'); - const sections = []; - let currentSection; - let title = filename.charAt(0).toUpperCase() + filename.slice(1).replace(/-/g, ' '); - for (let index = 0; index < lines.length; index++) { - const line = lines[index]; - const headingMatch = line.match(/^(#{1,6})\s+(.+)$/); - if (headingMatch) { - // Save previous section - if (currentSection) { - currentSection.lineEnd = index - 1; - sections.push(currentSection); - } - // Extract title from first heading - if (sections.length === 0 && headingMatch[1].length === 1) { - title = headingMatch[2]; - } - // Start new section - currentSection = { - heading: headingMatch[2], - level: headingMatch[1].length, - content: '', - lineStart: index, - lineEnd: index, - }; - } - else if (currentSection) { - // Add content to current section - currentSection.content += line + '\n'; - } - } - // Save last section - if (currentSection) { - currentSection.lineEnd = lines.length - 1; - sections.push(currentSection); - } - return { - filename, - title, - content, - sections, - }; -} -/** - * Parse all arch-docs files - */ -function parseAllArchDocs(repoPath = process.cwd()) { - const files = getArchDocsFiles(repoPath); - return files.map(file => parseMarkdownFile(file)); -} -/** - * Search arch-docs by keyword (simple text search) - */ -function searchArchDocs(docs, query, maxResults = 5) { - const results = []; - const queryLower = query.toLowerCase(); - const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2); - for (const doc of docs) { - for (const section of doc.sections) { - const sectionText = (section.heading + ' ' + section.content).toLowerCase(); - // Calculate relevance score - let relevance = 0; - // Exact phrase match - if (sectionText.includes(queryLower)) { - relevance += 10; - } - // Word matches - for (const word of queryWords) { - const matches = (sectionText.match(new RegExp(word, 'g')) || []).length; - relevance += matches * 2; - } - // Heading match bonus - if (section.heading.toLowerCase().includes(queryLower)) { - relevance += 5; - } - if (relevance > 0) { - results.push({ doc, section, relevance }); - } - } - } - // Sort by relevance and return top results - return results - .sort((a, b) => b.relevance - a.relevance) - .slice(0, maxResults); -} -/** - * Get specific arch-docs by filename - */ -function getArchDocByFilename(docs, filename) { - return docs.find(doc => doc.filename === filename); -} -/** - * Get arch-docs summary (index.md content if available) - */ -function getArchDocsSummary(docs) { - const indexDoc = getArchDocByFilename(docs, 'index'); - if (indexDoc) { - return indexDoc.content; - } - // Fallback: create summary from available docs - const fileList = docs.map(doc => `- ${doc.title} (${doc.filename}.md)`).join('\n'); - return `Available Architecture Documentation:\n\n${fileList}`; -} - -;// CONCATENATED MODULE: ./src/utils/arch-docs-rag.ts -/** - * Arch-Docs RAG System - * Retrieval Augmented Generation for architecture documentation - */ - -/** - * Build context from arch-docs based on PR analysis needs - */ -function buildArchDocsContext(docs, prContext) { - if (docs.length === 0) { - return { - available: false, - summary: '', - relevantDocs: [], - totalDocs: 0, - }; - } - // Extract keywords from PR context - const keywords = extractKeywords(prContext); - // Search for relevant sections - const relevantResults = new Map(); - // Search for each keyword and aggregate results - for (const keyword of keywords) { - const results = searchArchDocs(docs, keyword, 3); - for (const result of results) { - const key = `${result.doc.filename}:${result.section.heading}`; - const existing = relevantResults.get(key); - if (!existing || result.relevance > existing.relevance) { - relevantResults.set(key, result); - } - } - } - // Also always include key documents - const keyDocs = ['architecture', 'patterns', 'file-structure', 'security']; - for (const keyDoc of keyDocs) { - const doc = docs.find(d => d.filename === keyDoc); - if (doc && doc.sections.length > 0) { - const key = `${doc.filename}:${doc.sections[0].heading}`; - if (!relevantResults.has(key)) { - relevantResults.set(key, { - doc, - section: doc.sections[0], - relevance: 3, // Base relevance for key docs - }); - } - } - } - // Convert to array and sort by relevance - const sortedResults = Array.from(relevantResults.values()) - .sort((a, b) => b.relevance - a.relevance) - .slice(0, 10); // Top 10 most relevant sections - // Build context - const relevantDocs = sortedResults.map(result => ({ - filename: result.doc.filename, - title: result.doc.title, - section: result.section.heading, - content: result.section.content.trim(), - relevance: result.relevance, - })); - // Build summary - const summary = buildContextSummary(docs, relevantDocs); - return { - available: true, - summary, - relevantDocs, - totalDocs: docs.length, - }; -} -/** - * Extract keywords from PR context for semantic search - */ -function extractKeywords(prContext) { - const keywords = new Set(); - // From title - if (prContext.title) { - const titleWords = prContext.title - .toLowerCase() - .split(/\s+/) - .filter(w => w.length > 3 && !isCommonWord(w)); - titleWords.forEach(w => keywords.add(w)); - } - // From file paths - for (const file of prContext.files) { - const pathParts = file.path.split(/[\/\-_\.]/); - for (const part of pathParts) { - if (part.length > 3 && !isCommonWord(part.toLowerCase())) { - keywords.add(part.toLowerCase()); - } - } - // Extract from file extensions and directories - if (file.path.includes('test')) - keywords.add('testing'); - if (file.path.includes('api')) - keywords.add('api'); - if (file.path.includes('auth')) - keywords.add('authentication'); - if (file.path.includes('db') || file.path.includes('database')) - keywords.add('database'); - if (file.path.includes('security')) - keywords.add('security'); - if (file.path.includes('schema')) - keywords.add('schema'); - if (file.path.includes('config')) - keywords.add('configuration'); - if (file.path.includes('migration')) - keywords.add('migration'); - } - // From diff content (look for imports, function names, etc.) - if (prContext.diff) { - // Extract import statements - const importMatches = prContext.diff.matchAll(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g); - for (const match of importMatches) { - const importPath = match[1]; - const parts = importPath.split(/[\/\-_]/); - for (const part of parts) { - if (part.length > 3 && !isCommonWord(part)) { - keywords.add(part); - } - } - } - // Extract class and function names - const classMatches = prContext.diff.matchAll(/class\s+(\w+)/g); - for (const match of classMatches) { - keywords.add(match[1].toLowerCase()); - } - const functionMatches = prContext.diff.matchAll(/function\s+(\w+)/g); - for (const match of functionMatches) { - if (match[1].length > 3) { - keywords.add(match[1].toLowerCase()); - } - } - } - return Array.from(keywords).slice(0, 20); // Limit to top 20 keywords -} -/** - * Check if a word is too common to be useful - */ -function isCommonWord(word) { - const commonWords = new Set([ - 'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'been', - 'will', 'your', 'more', 'when', 'some', 'them', 'than', 'into', 'only', - 'other', 'then', 'also', 'make', 'made', 'like', 'time', 'very', 'just', - 'file', 'code', 'test', 'docs', 'info', 'data', 'type', 'name', 'index', - ]); - return commonWords.has(word); -} -/** - * Build a summary of the context - */ -function buildContextSummary(docs, relevantDocs) { - const docTitles = docs.map(d => d.title).join(', '); - const relevantCount = relevantDocs.length; - let summary = `Architecture Documentation Context:\n`; - summary += `- Total documents: ${docs.length}\n`; - summary += `- Available: ${docTitles}\n`; - summary += `- Relevant sections retrieved: ${relevantCount}\n\n`; - if (relevantCount > 0) { - summary += `Most relevant sections:\n`; - relevantDocs.slice(0, 5).forEach((doc, i) => { - summary += `${i + 1}. ${doc.title} - ${doc.section} (relevance: ${doc.relevance})\n`; - }); - } - return summary; -} -/** - * Format arch-docs context for inclusion in prompts - */ -function formatArchDocsForPrompt(context) { - if (!context.available || context.relevantDocs.length === 0) { - return ''; - } - let prompt = '\n## Repository Architecture Context\n\n'; - prompt += 'The following sections from the architecture documentation are relevant to this PR:\n\n'; - for (const doc of context.relevantDocs) { - prompt += `### ${doc.title} - ${doc.section}\n\n`; - prompt += doc.content + '\n\n'; - prompt += '---\n\n'; - } - return prompt; -} -/** - * Get specific context for risk analysis - */ -function getSecurityContext(docs) { - const securityDoc = docs.find(d => d.filename === 'security'); - if (securityDoc) { - return securityDoc.content; - } - return ''; -} -/** - * Get specific context for architecture understanding - */ -function getArchitectureContext(docs) { - const archDoc = docs.find(d => d.filename === 'architecture'); - if (archDoc) { - return archDoc.content; - } - return ''; -} -/** - * Get specific context for patterns - */ -function getPatternsContext(docs) { - const patternsDoc = docs.find(d => d.filename === 'patterns'); - if (patternsDoc) { - return patternsDoc.content; - } - return ''; -} - -;// CONCATENATED MODULE: ./src/agents/base-pr-agent-workflow.ts -/** - * Base PR Agent Workflow using LangGraph - * Follows architecture-doc-generator patterns with self-refinement - */ - - - - - -/** - * Agent workflow state - */ -const PRAgentState = Annotation.Root({ - // Input context - context: Annotation({ - reducer: (_, update) => update, - }), - // Current iteration - iteration: Annotation({ - reducer: (_, update) => update, - default: () => 0, - }), - // File analyses - fileAnalyses: Annotation({ - reducer: (_, update) => update, - default: () => new Map(), - }), - // Current analysis state - currentSummary: Annotation({ - reducer: (_, update) => update, - default: () => '', - }), - currentRisks: Annotation({ - reducer: (_, update) => update, - default: () => [], - }), - currentComplexity: Annotation({ - reducer: (_, update) => update, - default: () => 1, - }), - // Quality metrics - clarityScore: Annotation({ - reducer: (_, update) => update, - default: () => 0, - }), - missingInformation: Annotation({ - reducer: (_, update) => update, - default: () => [], - }), - // Recommendations - recommendations: Annotation({ - reducer: (_, update) => update, - default: () => [], - }), - // Insights and reasoning - insights: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - reasoning: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - // Arch-docs tracking - archDocsInfluencedStages: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - archDocsKeyInsights: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - // Token tracking - totalInputTokens: Annotation({ - reducer: (current, update) => current + update, - default: () => 0, - }), - totalOutputTokens: Annotation({ - reducer: (current, update) => current + update, - default: () => 0, - }), -}); -/** - * Base class for PR agents with self-refinement workflow - */ -class BasePRAgentWorkflow { - model; - workflow; - checkpointer = new MemorySaver(); - tools; - constructor(model) { - this.model = model; - // Initialize tools - this.tools = [ - createFileAnalyzerTool(), - createRiskDetectorTool(), - createComplexityScorerTool(), - createSummaryGeneratorTool(), - ]; - this.workflow = this.buildWorkflow(); - } - /** - * Build the PR analysis workflow - */ - buildWorkflow() { - const graph = new StateGraph(PRAgentState); - // Define nodes - graph.addNode('analyzeFiles', this.analyzeFilesNode.bind(this)); - graph.addNode('detectRisks', this.detectRisksNode.bind(this)); - graph.addNode('calculateComplexity', this.calculateComplexityNode.bind(this)); - graph.addNode('generateSummary', this.generateSummaryNode.bind(this)); - graph.addNode('evaluateQuality', this.evaluateQualityNode.bind(this)); - graph.addNode('refineAnalysis', this.refineAnalysisNode.bind(this)); - graph.addNode('finalize', this.finalizeNode.bind(this)); - // Set entry point - const entryPoint = 'analyzeFiles'; - graph.setEntryPoint(entryPoint); - // Build workflow graph - graph.addEdge(entryPoint, 'detectRisks'); - graph.addEdge('detectRisks', 'calculateComplexity'); - graph.addEdge('calculateComplexity', 'generateSummary'); - graph.addEdge('generateSummary', 'evaluateQuality'); - // Conditional: refine or finalize - graph.addConditionalEdges('evaluateQuality', this.shouldRefine.bind(this), { - refine: 'refineAnalysis', - finalize: 'finalize', - }); - // After refinement, evaluate again - graph.addEdge('refineAnalysis', 'evaluateQuality'); - // End after finalization - graph.addEdge('finalize', END); - return graph.compile({ checkpointer: this.checkpointer }); - } - /** - * Execute the agent workflow - */ - async execute(context, options) { - const startTime = Date.now(); - // Fast path: skip self-refinement - if (options?.skipSelfRefinement) { - return this.executeFastPath(context, startTime); - } - const config = { - maxIterations: 3, - clarityThreshold: 80, - skipSelfRefinement: false, - }; - const initialState = { - context, - iteration: 0, - fileAnalyses: new Map(), - currentSummary: '', - currentRisks: [], - currentComplexity: 1, - clarityScore: 0, - missingInformation: [], - recommendations: [], - insights: [], - reasoning: [], - totalInputTokens: 0, - totalOutputTokens: 0, - }; - const workflowConfig = { - configurable: { - thread_id: `pr-agent-${Date.now()}`, - maxIterations: config.maxIterations, - clarityThreshold: config.clarityThreshold, - }, - recursionLimit: 50, - }; - let finalState = initialState; - let totalInputTokens = 0; - let totalOutputTokens = 0; - // Execute workflow - stream returns state updates - try { - for await (const state of await this.workflow.stream(initialState, workflowConfig)) { - // Get the last node's state - const nodeNames = Object.keys(state); - if (nodeNames.length > 0) { - const lastNodeName = nodeNames[nodeNames.length - 1]; - finalState = state[lastNodeName] || finalState; - // Extract token counts if present - const stateAny = finalState; - if (stateAny.totalInputTokens !== undefined) { - totalInputTokens = stateAny.totalInputTokens; - } - if (stateAny.totalOutputTokens !== undefined) { - totalOutputTokens = stateAny.totalOutputTokens; - } - } - } - } - catch (error) { - console.error('Workflow execution error:', error); - throw error; - } - const executionTime = Date.now() - startTime; - // Build arch-docs impact summary with deduplication - const stateAny = finalState; - const archDocsImpact = context.archDocs?.available ? { - used: true, - docsAvailable: context.archDocs.totalDocs, - sectionsUsed: context.archDocs.relevantDocs.length, - influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])], - keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])], - } : undefined; - return { - summary: finalState.currentSummary, - fileAnalyses: finalState.fileAnalyses, - overallComplexity: finalState.currentComplexity, - overallRisks: finalState.currentRisks, - recommendations: finalState.recommendations, - insights: finalState.insights, - reasoning: finalState.reasoning, - provider: 'ai', - model: this.model.modelName || 'unknown', - totalTokensUsed: totalInputTokens + totalOutputTokens, - executionTime, - mode: context.mode, - archDocsImpact, - }; - } - /** - * Fast path execution - skip refinement loop but still use LLM for detailed analysis - */ - async executeFastPath(context, startTime) { - // Initialize state - const initialState = { - context, - iteration: 0, - fileAnalyses: new Map(), - currentSummary: '', - currentRisks: [], - currentComplexity: 1, - clarityScore: 0, - missingInformation: [], - recommendations: [], - insights: [], - reasoning: [], - totalInputTokens: 0, - totalOutputTokens: 0, - }; - // Execute workflow nodes sequentially (skip refinement loop) - let state = initialState; - try { - // 1. Analyze files - state = await this.analyzeFilesNode(state); - // 2. Detect risks - state = await this.detectRisksNode(state); - // 3. Calculate complexity - state = await this.calculateComplexityNode(state); - // 4. Generate summary - state = await this.generateSummaryNode(state); - // 5. Generate recommendations (skip quality evaluation) - state = await this.refineAnalysisNode(state); - // 6. Finalize - state = await this.finalizeNode(state); - const executionTime = Date.now() - startTime; - // Build arch-docs impact summary with deduplication - const stateAny = state; - const archDocsImpact = context.archDocs?.available ? { - used: true, - docsAvailable: context.archDocs.totalDocs, - sectionsUsed: context.archDocs.relevantDocs.length, - influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])], - keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])], - } : undefined; - return { - summary: state.currentSummary, - fileAnalyses: state.fileAnalyses, - overallComplexity: state.currentComplexity, - overallRisks: state.currentRisks, - recommendations: state.recommendations, - insights: state.insights, - reasoning: [...state.reasoning, 'Fast path: Self-refinement evaluation skipped for speed'], - provider: 'ai', - model: this.model.modelName || 'unknown', - totalTokensUsed: state.totalInputTokens + state.totalOutputTokens, - executionTime, - mode: context.mode, - archDocsImpact, - }; - } - catch (error) { - console.error('Fast path execution error:', error); - throw error; - } - } - // Workflow nodes - async analyzeFilesNode(state) { - const { context } = state; - const files = parseDiff(context.diff); - console.log(`🔍 Analyzing ${files.length} files...`); - // Show arch-docs status if available - if (context.archDocs?.available) { - console.log(`📚 Using architecture documentation (${context.archDocs.totalDocs} docs, ${context.archDocs.relevantDocs.length} relevant sections)`); - } - const fileAnalyses = new Map(); - // Build arch-docs context if available - let archDocsContext = ''; - if (context.archDocs?.available) { - archDocsContext = formatArchDocsForPrompt(context.archDocs); - } - // Analyze files in batches for detailed insights - const filesToAnalyze = files.slice(0, 15); // Limit to 15 files for detailed analysis - const importantFiles = filesToAnalyze.filter(f => f.additions + f.deletions > 20 || // Significant changes - f.path.includes('config') || - f.path.includes('schema') || - f.path.includes('migration') || - f.path.includes('test')).slice(0, 5); // Top 5 important files - // Get detailed analysis for important files - if (importantFiles.length > 0) { - try { - const fileDetailsPrompt = `Analyze these files from a pull request. For EACH file, provide a detailed analysis considering the repository's architecture standards. -${archDocsContext ? '\n' + archDocsContext : ''} - -Files to analyze: -${importantFiles.map(f => ` -File: ${f.path} -Status: ${f.status || 'modified'} -Changes: +${f.additions} -${f.deletions} -Diff preview: -\`\`\` -${f.diff.substring(0, 500)} -\`\`\` -`).join('\n---\n')} - -${archDocsContext ? `CRITICAL INSTRUCTIONS: -- For EACH file, reference the relevant architecture documentation sections above -- Explain how the changes align with or diverge from established patterns -- Identify specific guidelines that apply to each file -- Mention which parts of the architecture are affected -- Compare changes against documented standards - -` : ''} - -Respond with a JSON object mapping file paths to analysis objects: -{ - "path/to/file": { - "summary": "Description that references relevant arch-docs patterns/guidelines", - "risks": ["risk with arch-docs context", "risk2"], - "complexity": 1-5, - "recommendations": ["recommendation based on arch-docs standards"] - } -} - -${archDocsContext ? 'Each summary MUST reference the specific architecture documentation that applies to this file.' : ''}`; - const response = await this.model.invoke(fileDetailsPrompt); - const content = response.content; - // Track tokens - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Parse detailed file analyses - try { - const jsonMatch = content.match(/\{[\s\S]*\}/); - if (jsonMatch) { - const detailedAnalyses = JSON.parse(jsonMatch[0]); - // Apply detailed analysis to file analyses - for (const file of importantFiles) { - const detail = detailedAnalyses[file.path]; - if (detail) { - fileAnalyses.set(file.path, { - path: file.path, - summary: detail.summary || `${file.status || 'M'}: +${file.additions} -${file.deletions}`, - risks: Array.isArray(detail.risks) ? detail.risks : [], - complexity: detail.complexity || Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1), - changes: { - additions: file.additions, - deletions: file.deletions, - }, - recommendations: Array.isArray(detail.recommendations) ? detail.recommendations : [], - }); - } - } - } - } - catch (parseError) { - console.warn('Failed to parse file analysis JSON, using basic analysis'); - } - // Update state with token tracking - state = { - ...state, - totalInputTokens: (state.totalInputTokens || 0) + inputTokens, - totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, - }; - } - catch (error) { - console.warn('Error in detailed file analysis, falling back to basic:', error); - } - } - // Add basic analysis for remaining files - for (const file of filesToAnalyze) { - if (!fileAnalyses.has(file.path)) { - const analysis = { - path: file.path, - summary: `${file.status || 'M'}: +${file.additions} -${file.deletions}`, - risks: [], - complexity: Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1), - changes: { - additions: file.additions, - deletions: file.deletions, - }, - recommendations: [], - }; - fileAnalyses.set(file.path, analysis); - } - } - // Track arch-docs usage - const newInsights = [`Analyzed ${files.length} files (${importantFiles.length} in detail)`]; - const hasArchDocsContext = archDocsContext && archDocsContext.length > 0; - const archDocsStages = hasArchDocsContext ? ['file-analysis'] : []; - const archDocsInsights = []; - if (hasArchDocsContext && context.archDocs?.available) { - archDocsInsights.push(`Applied ${context.archDocs.relevantDocs.length} architecture documentation sections to analyze files in context of repository standards`); - } - return { - ...state, - fileAnalyses, - insights: newInsights, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - async detectRisksNode(state) { - const { context, fileAnalyses } = state; - console.log('⚠️ Detecting risks...'); - // Build context for risk analysis - const fileList = Array.from(fileAnalyses.entries()) - .slice(0, 15) - .map(([path, analysis]) => `${path} (+${analysis.changes.additions} -${analysis.changes.deletions})`) - .join('\n'); - // Get a sample of the diff for risk analysis (limit size) - const diffSample = context.diff.substring(0, 8000); // First 8KB for context - // Add security context from arch-docs if available - let securityContext = ''; - let allDocs = []; - let securityDoc = null; - let patternsDoc = null; - if (context.archDocs?.available) { - allDocs = parseAllArchDocs(); - const secDoc = getSecurityContext(allDocs); - if (secDoc) { - securityContext = `\n## Security Guidelines from Repository Documentation\n\n${secDoc.substring(0, 3000)}\n`; - securityDoc = allDocs.find(d => d.filename === 'security'); - } - // Also get patterns that might indicate risks - const patterns = getPatternsContext(allDocs); - if (patterns) { - securityContext += `\n## Repository Patterns and Best Practices\n\n${patterns.substring(0, 2000)}\n`; - patternsDoc = allDocs.find(d => d.filename === 'patterns'); - } - } - const riskPrompt = `You are a security and code quality expert analyzing a pull request for potential risks. -${securityContext} - -Analyze the following changes and identify SPECIFIC risks in these categories: -1. **Security Risks**: Exposed credentials, insecure patterns, authentication/authorization issues -2. **Breaking Changes**: API changes, database schema changes, removed functionality -3. **Performance Concerns**: Inefficient algorithms, memory leaks, N+1 queries -4. **Code Quality**: Complex logic, missing error handling, lack of tests -5. **Operational Risks**: Configuration changes, deployment concerns, dependency updates - -PR Title: ${context.title || 'No title provided'} - -Files changed: -${fileList} - -Diff sample: -\`\`\` -${diffSample} -\`\`\` - -${securityContext ? `CRITICAL INSTRUCTIONS: -- You MUST reference the repository documentation guidelines above when identifying each risk -- For EVERY risk you identify, find the relevant guideline from the documentation -- Explain HOW the code change violates or conflicts with the documented standards -- Quote the specific guideline that makes this a risk -- Be specific about why this matters based on the repository's own standards - -Example format for a risk with documentation: -{ - "description": "File exceeds maximum line count recommended for maintainability", - "archDocsSource": "code-quality.md", - "archDocsExcerpt": "Keep individual files under 500 lines to maintain testability and readability", - "reason": "This file contains 990 lines, nearly 2x the repository standard, which increases maintenance burden and makes comprehensive testing more difficult" -} -` : ''} - -Provide a JSON array of risk objects. Each risk MUST include: -- description: Clear, specific description of the risk -${securityContext ? `- archDocsSource: REQUIRED - Which documentation file from above this relates to (e.g., "security.md", "patterns.md", "code-quality.md") -- archDocsExcerpt: REQUIRED - Direct quote from the repository documentation that this violates -- reason: REQUIRED - Detailed explanation of why this is a risk based on the specific guideline quoted above -` : ''} - -Format: -${securityContext ? `[ - { - "description": "Specific risk description", - "archDocsSource": "documentation-file.md", - "archDocsExcerpt": "Exact quote from the documentation", - "reason": "Detailed explanation connecting the code change to the guideline violation" - } -] - -DO NOT return simple string arrays. Each risk MUST be an object with archDocsSource, archDocsExcerpt, and reason fields.` : '["risk 1", "risk 2", ...]'} - -Only include risks that are actually present. If no significant risks, return an empty array [].`; - try { - const response = await this.model.invoke(riskPrompt); - const content = response.content; - // Track tokens - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Parse JSON response - let risks = []; - let hasArchDocsEnhancement = false; - try { - // Extract JSON from markdown code blocks if present - const jsonMatch = content.match(/\[[\s\S]*\]/); - if (jsonMatch) { - const parsedRisks = JSON.parse(jsonMatch[0]); - // Check if risks have arch-docs references - if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'object' && 'archDocsSource' in parsedRisks[0]) { - // Transform to our RiskItem format - risks = parsedRisks.map((r) => ({ - description: r.description, - archDocsReference: r.archDocsSource ? { - source: r.archDocsSource, - excerpt: r.archDocsExcerpt || '', - reason: r.reason || '', - } : undefined, - })); - hasArchDocsEnhancement = true; - } - else if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'string') { - // Legacy format - just strings - risks = parsedRisks; - } - else { - risks = parsedRisks; - } - } - } - catch (parseError) { - console.warn('Failed to parse risk JSON, extracting manually'); - // Fallback: extract bullet points as strings - const lines = content.split('\n'); - risks = lines - .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•')) - .map(line => line.replace(/^[-•]\s*/, '').trim()) - .filter(line => line.length > 0); - } - // Add basic pattern-based checks with arch-docs enhancement - const patternRisks = []; - if (context.diff.includes('password') || context.diff.includes('secret') || context.diff.includes('api_key')) { - const riskDesc = 'Potential credentials or sensitive data in code changes'; - if (securityDoc) { - // Always enhance with arch-docs if available - patternRisks.push({ - description: riskDesc, - archDocsReference: { - source: 'security.md', - excerpt: 'Never commit credentials, API keys, or secrets to the repository. Use environment variables for all sensitive configuration.', - reason: 'Code changes contain keywords like "password", "secret", or "api_key" which may indicate hardcoded credentials. This violates the repository security policy requiring all secrets to be externalized via environment variables.', - }, - }); - } - else { - patternRisks.push(riskDesc); - } - } - if (fileAnalyses.size > 20) { - const qualityDoc = allDocs.find(d => d.filename === 'code-quality'); - if (qualityDoc && securityContext) { - patternRisks.push({ - description: `Large change set (${fileAnalyses.size} files) increases review complexity and error risk`, - archDocsReference: { - source: 'code-quality.md', - excerpt: 'Keep pull requests focused and under 15 files when possible for thorough review', - reason: `This PR modifies ${fileAnalyses.size} files, exceeding the recommended limit. Large PRs are harder to review thoroughly and increase the likelihood of missing critical issues.`, - }, - }); - } - else { - patternRisks.push(`Large change set (${fileAnalyses.size} files) - may be difficult to review thoroughly`); - } - } - if (context.diff.includes('DROP TABLE') || context.diff.includes('ALTER TABLE')) { - if (securityContext) { - patternRisks.push({ - description: 'Database schema changes detected - requires careful migration planning', - archDocsReference: { - source: 'patterns.md', - excerpt: 'All database schema changes must be backwards-compatible and include rollback procedures', - reason: 'The changes include database schema modifications (DROP TABLE or ALTER TABLE) which can cause data loss or application downtime if not properly planned and tested.', - }, - }); - } - else { - patternRisks.push('Database schema changes detected - requires careful migration planning'); - } - } - // Merge risks, avoiding duplicates (for string risks) - let allRisks; - if (hasArchDocsEnhancement) { - // Keep structured risks - allRisks = [...risks, ...patternRisks]; - } - else { - // Deduplicate string risks - allRisks = [...new Set([...risks, ...patternRisks])]; - } - // Track arch-docs usage in risk detection - const archDocsStages = securityContext ? ['risk-detection'] : []; - const archDocsInsights = []; - if (securityContext && context.archDocs?.available) { - const enhancedCount = allRisks.filter(r => typeof r === 'object' && r.archDocsReference).length; - if (enhancedCount > 0) { - archDocsInsights.push(`Linked ${enhancedCount} risks to specific repository security guidelines and best practices`); - } - } - return { - ...state, - currentRisks: allRisks, - insights: [`Identified ${allRisks.length} potential risks`], - totalInputTokens: (state.totalInputTokens || 0) + inputTokens, - totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - catch (error) { - console.error('Error in risk detection:', error); - // Fallback to basic pattern matching - const basicRisks = []; - if (context.diff.includes('password') || context.diff.includes('secret')) { - basicRisks.push('Potential credentials in diff'); - } - if (fileAnalyses.size > 15) { - basicRisks.push('Large change set - difficult to review'); - } - return { - ...state, - currentRisks: basicRisks, - insights: [`Identified ${basicRisks.length} potential risks (basic analysis)`], - }; - } - } - async calculateComplexityNode(state) { - const { fileAnalyses, context } = state; - console.log('📊 Calculating complexity...'); - const complexities = Array.from(fileAnalyses.values()).map(f => f.complexity); - const avgComplexity = complexities.length > 0 - ? complexities.reduce((a, b) => a + b, 0) / complexities.length - : 1; - // Track arch-docs influence on complexity - const archDocsStages = context.archDocs?.available ? ['complexity-calculation'] : []; - const archDocsInsights = []; - if (context.archDocs?.available) { - // Check if patterns documentation helped understand complexity - const allDocs = parseAllArchDocs(); - const patterns = getPatternsContext(allDocs); - if (patterns) { - archDocsInsights.push(`Evaluated complexity against repository design patterns and coding standards`); - } - } - return { - ...state, - currentComplexity: Math.round(avgComplexity), - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - async generateSummaryNode(state) { - const { context, fileAnalyses, currentRisks, currentComplexity } = state; - console.log('📝 Generating detailed summary...'); - const totalFiles = fileAnalyses.size; - const totalAdditions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.additions, 0); - const totalDeletions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.deletions, 0); - // Build file list with changes - const fileList = Array.from(fileAnalyses.entries()) - .slice(0, 20) - .map(([path, analysis]) => `- ${path}: +${analysis.changes.additions} -${analysis.changes.deletions} (complexity: ${analysis.complexity}/5)`) - .join('\n'); - // Add patterns context from arch-docs if available - let patternsContext = ''; - if (context.archDocs?.available) { - const allDocs = parseAllArchDocs(); - const patterns = getPatternsContext(allDocs); - if (patterns) { - patternsContext = `\n## Design Patterns from Repository Documentation\n\n${patterns.substring(0, 2000)}\n`; - } - } - // Create comprehensive prompt for LLM - const summaryPrompt = `You are analyzing a pull request. Provide a DETAILED and COMPREHENSIVE summary that covers: - -1. **Overall Purpose**: What is this PR trying to accomplish? What problem does it solve? -2. **Key Changes**: What are the main changes being made? Group related changes together. -3. **Impact Analysis**: What parts of the system are affected? What are the implications? -4. **Technical Details**: Mention important technical aspects (new dependencies, API changes, data model changes, etc.) -5. **Patterns Observed**: Any design patterns, refactoring, or architectural changes? -${patternsContext} - -PR Title: ${context.title || 'No title provided'} - -Statistics: -- Files changed: ${totalFiles} -- Lines added: ${totalAdditions} -- Lines deleted: ${totalDeletions} -- Overall complexity: ${currentComplexity}/5 -- Risks identified: ${currentRisks.length} - -Files changed: -${fileList} - -${currentRisks.length > 0 ? `\nRisks detected:\n${currentRisks.map(r => `- ${r}`).join('\n')}` : ''} - -${patternsContext ? 'Consider the design patterns and architecture from the repository documentation when analyzing the changes.\n' : ''} - -Provide a detailed, well-structured summary (3-5 paragraphs) that would help a reviewer understand the scope and purpose of this PR.`; - try { - const response = await this.model.invoke(summaryPrompt); - const detailedSummary = response.content; - // Track token usage - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Track arch-docs usage in summary - const archDocsStages = patternsContext ? ['summary-generation'] : []; - const archDocsInsights = []; - if (patternsContext && context.archDocs?.available) { - archDocsInsights.push(`Generated summary aligned with repository architecture and established patterns`); - } - return { - ...state, - currentSummary: detailedSummary, - totalInputTokens: inputTokens, - totalOutputTokens: outputTokens, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - catch (error) { - console.error('Error generating summary:', error); - // Fallback to basic summary - const fallbackSummary = `PR Analysis Summary: -- Files changed: ${totalFiles} -- Additions: ${totalAdditions} -- Deletions: ${totalDeletions} -- Overall complexity: ${currentComplexity}/5 -- Risks identified: ${currentRisks.length} - -${context.title ? `Title: ${context.title}` : ''}`; - return { - ...state, - currentSummary: fallbackSummary, - }; - } - } - async evaluateQualityNode(state) { - const { iteration } = state; - console.log(`🔍 Evaluating quality (iteration ${iteration + 1})...`); - // Simple quality check - const clarityScore = 85; // Placeholder - return { - ...state, - clarityScore, - iteration: iteration + 1, - }; - } - async refineAnalysisNode(state) { - const { currentSummary, currentRisks, fileAnalyses, context } = state; - console.log('🔄 Refining analysis...'); - // Build arch-docs context for refinement - let archDocsRefinementContext = ''; - if (context.archDocs?.available) { - const allDocs = parseAllArchDocs(); - // Get recommendations from arch-docs - const recommendationsDoc = allDocs.find(d => d.filename === 'recommendations'); - if (recommendationsDoc) { - archDocsRefinementContext += `\n## Repository Improvement Guidelines\n\n${recommendationsDoc.content.substring(0, 2000)}\n`; - } - // Get code quality guidelines - const qualityDoc = allDocs.find(d => d.filename === 'code-quality'); - if (qualityDoc) { - archDocsRefinementContext += `\n## Code Quality Standards\n\n${qualityDoc.content.substring(0, 2000)}\n`; - } - // Get KPI metrics - const kpiDoc = allDocs.find(d => d.filename === 'kpi'); - if (kpiDoc) { - archDocsRefinementContext += `\n## Repository Health KPIs\n\n${kpiDoc.content.substring(0, 1500)}\n`; - } - } - // Generate comprehensive recommendations - const refinementPrompt = `Based on this PR analysis, provide specific, actionable recommendations for the developer and reviewers. -${archDocsRefinementContext} - -PR Summary: -${currentSummary} - -Risks Identified: -${currentRisks.map(r => `- ${r}`).join('\n')} - -Files Changed: ${fileAnalyses.size} - -Consider: -1. Code organization and structure improvements -2. Testing recommendations -3. Documentation needs -4. Performance optimizations -5. Security enhancements -6. Review process suggestions -${archDocsRefinementContext ? '7. Alignment with repository standards and KPIs from arch-docs\n' : ''} - -${archDocsRefinementContext ? 'Use the repository guidelines and standards above to ensure recommendations align with established practices.\n' : ''} - -Provide a JSON array of 3-5 specific, actionable recommendations: -["recommendation 1", "recommendation 2", ...]`; - try { - const response = await this.model.invoke(refinementPrompt); - const content = response.content; - // Track tokens - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Parse recommendations - let recommendations = []; - try { - const jsonMatch = content.match(/\[[\s\S]*\]/); - if (jsonMatch) { - recommendations = JSON.parse(jsonMatch[0]); - } - } - catch (parseError) { - // Fallback: extract bullet points - const lines = content.split('\n'); - recommendations = lines - .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•') || /^\d+\./.test(line.trim())) - .map(line => line.replace(/^[-•]\s*/, '').replace(/^\d+\.\s*/, '').trim()) - .filter(line => line.length > 0) - .slice(0, 5); - } - // Add default recommendations if none found - if (recommendations.length === 0) { - recommendations = [ - 'Ensure comprehensive test coverage for new functionality', - 'Update relevant documentation', - 'Consider performance implications of changes', - ]; - } - // Track arch-docs usage in refinement - const archDocsStages = archDocsRefinementContext ? ['refinement'] : []; - const archDocsInsights = []; - if (archDocsRefinementContext && context.archDocs?.available) { - archDocsInsights.push(`Generated ${recommendations.length} recommendations based on repository quality standards and KPIs`); - } - return { - ...state, - recommendations, - totalInputTokens: (state.totalInputTokens || 0) + inputTokens, - totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - catch (error) { - console.error('Error refining analysis:', error); - return { - ...state, - recommendations: [ - 'Review changes carefully for potential side effects', - 'Ensure test coverage is adequate', - 'Update documentation as needed', - ], - }; - } - } - async finalizeNode(state) { - console.log('✨ Finalizing analysis...'); - return state; - } - shouldRefine(state) { - // Use defaults if config not accessible - const maxIterations = 3; - const clarityThreshold = 80; - if (state.iteration >= maxIterations) { - console.log(`⏹️ Stopping: Max iterations (${maxIterations}) reached`); - return 'finalize'; - } - if (state.clarityScore >= clarityThreshold) { - console.log(`✅ Stopping: Clarity threshold (${clarityThreshold}) achieved`); - return 'finalize'; - } - console.log(`🔄 Continuing: Iteration ${state.iteration}, clarity ${state.clarityScore}`); - return 'refine'; - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/output_parsers.js - - - -//#region src/output_parsers.ts -var AnthropicToolsOutputParser = class extends BaseLLMOutputParser { - static lc_name() { - return "AnthropicToolsOutputParser"; - } - lc_namespace = [ - "langchain", - "anthropic", - "output_parsers" - ]; - returnId = false; - /** The type of tool calls to return. */ - keyName; - /** Whether to return only the first tool call. */ - returnSingle = false; - zodSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - } - async _validateResult(result) { - let parsedResult = result; - if (typeof result === "string") try { - parsedResult = JSON.parse(result); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e.message)}`, result); - } - else parsedResult = result; - if (this.zodSchema === void 0) return parsedResult; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult); - if (zodParsedResult.success) return zodParsedResult.data; - else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2)); - } - async parseResult(generations) { - const tools = generations.flatMap((generation) => { - const { message } = generation; - if (!Array.isArray(message.content)) return []; - const tool$1 = extractToolCalls(message.content)[0]; - return tool$1; - }); - if (tools[0] === void 0) throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser."); - const [tool] = tools; - const validatedResult = await this._validateResult(tool.args); - return validatedResult; - } -}; -function extractToolCalls(content) { - const toolCalls = []; - for (const block of content) if (block.type === "tool_use") toolCalls.push({ - name: block.name, - args: block.input, - id: block.id, - type: "tool_call" - }); - return toolCalls; -} - -//#endregion - -//# sourceMappingURL=output_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/tools.js -//#region src/utils/tools.ts -function handleToolChoice(toolChoice) { - if (!toolChoice) return void 0; - else if (toolChoice === "any") return { type: "any" }; - else if (toolChoice === "auto") return { type: "auto" }; - else if (toolChoice === "none") return { type: "none" }; - else if (typeof toolChoice === "string") return { - type: "tool", - name: toolChoice - }; - else return toolChoice; -} - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/content.js - - -//#region src/utils/content.ts -function _isAnthropicThinkingBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "thinking"; -} -function _isAnthropicRedactedThinkingBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "redacted_thinking"; -} -function _isAnthropicSearchResultBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "search_result"; -} -function _isAnthropicImageBlockParam(block) { - if (typeof block !== "object" || block == null) return false; - if (!("type" in block) || block.type !== "image") return false; - if (!("source" in block) || typeof block.source !== "object" || block.source == null) return false; - if (!("type" in block.source)) return false; - if (block.source.type === "base64") { - if (!("media_type" in block.source)) return false; - if (typeof block.source.media_type !== "string") return false; - if (!("data" in block.source)) return false; - if (typeof block.source.data !== "string") return false; - return true; - } - if (block.source.type === "url") { - if (!("url" in block.source)) return false; - if (typeof block.source.url !== "string") return false; - return true; - } - return false; -} -const standardContentBlockConverter = { - providerName: "anthropic", - fromStandardTextBlock(block) { - return { - type: "text", - text: block.text, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - }, - fromStandardImageBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ - dataUrl: block.url, - asTypedArray: false - }); - if (data) return { - type: "image", - source: { - type: "base64", - data: data.data, - media_type: data.mime_type - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - else return { - type: "image", - source: { - type: "url", - url: block.url - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - } else if (block.source_type === "base64") return { - type: "image", - source: { - type: "base64", - data: block.data, - media_type: block.mime_type ?? "" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - else throw new Error(`Unsupported image source type: ${block.source_type}`); - }, - fromStandardFileBlock(block) { - const mime_type = (block.mime_type ?? "").split(";")[0]; - if (block.source_type === "url") { - if (mime_type === "application/pdf" || mime_type === "") return { - type: "document", - source: { - type: "url", - url: block.url - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`); - } else if (block.source_type === "text") if (mime_type === "text/plain" || mime_type === "") return { - type: "document", - source: { - type: "text", - data: block.text, - media_type: block.mime_type ?? "" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`); - else if (block.source_type === "base64") if (mime_type === "application/pdf" || mime_type === "") return { - type: "document", - source: { - type: "base64", - data: block.data, - media_type: "application/pdf" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else if ([ - "image/jpeg", - "image/png", - "image/gif", - "image/webp" - ].includes(mime_type)) return { - type: "document", - source: { - type: "content", - content: [{ - type: "image", - source: { - type: "base64", - data: block.data, - media_type: mime_type - } - }] - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`); - else throw new Error(`Unsupported file source type: ${block.source_type}`); - } -}; - -//#endregion - -//# sourceMappingURL=content.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/index.js -//#region src/utils/index.ts -const dist_utils_iife = (fn) => fn(); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/standard.js - - -//#region src/utils/standard.ts -function _isStandardAnnotation(annotation) { - return typeof annotation === "object" && annotation !== null && "type" in annotation && annotation.type === "citation"; -} -function _formatStandardCitations(annotations) { - function* iterateAnnotations() { - for (const annotation of annotations) if (_isStandardAnnotation(annotation)) { - if (annotation.source === "char") yield { - type: "char_location", - file_id: annotation.url ?? "", - start_char_index: annotation.startIndex ?? 0, - end_char_index: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "page") yield { - type: "page_location", - file_id: annotation.url ?? "", - start_page_number: annotation.startIndex ?? 0, - end_page_number: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "block") yield { - type: "content_block_location", - file_id: annotation.url ?? "", - start_block_index: annotation.startIndex ?? 0, - end_block_index: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "url") yield { - type: "web_search_result_location", - url: annotation.url ?? "", - title: annotation.title ?? null, - encrypted_index: String(annotation.startIndex ?? 0), - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "search") yield { - type: "search_result_location", - title: annotation.title ?? null, - start_block_index: annotation.startIndex ?? 0, - end_block_index: annotation.endIndex ?? 0, - search_result_index: 0, - source: annotation.source ?? "", - cited_text: annotation.citedText ?? "" - }; - } - } - return Array.from(iterateAnnotations()); -} -function _formatBase64Data(data) { - if (typeof data === "string") return data; - else return _encodeUint8Array(data); -} -function _encodeUint8Array(data) { - const output = []; - for (let i = 0, { length } = data; i < length; i++) output.push(String.fromCharCode(data[i])); - return btoa(output.join("")); -} -function _normalizeMimeType(mimeType) { - return (mimeType ?? "").split(";")[0].toLowerCase(); -} -function _extractMetadataValue(metadata, key) { - if (metadata !== void 0 && metadata !== null && typeof metadata === "object" && key in metadata) return metadata[key]; - return void 0; -} -function _applyDocumentMetadata(block, metadata) { - const cacheControl = _extractMetadataValue(metadata, "cache_control"); - if (cacheControl !== void 0) block.cache_control = cacheControl; - const citations = _extractMetadataValue(metadata, "citations"); - if (citations !== void 0) block.citations = citations; - const context = _extractMetadataValue(metadata, "context"); - if (context !== void 0) block.context = context; - const title = _extractMetadataValue(metadata, "title"); - if (title !== void 0) block.title = title; - return block; -} -function _applyImageMetadata(block, metadata) { - const cacheControl = _extractMetadataValue(metadata, "cache_control"); - if (cacheControl !== void 0) block.cache_control = cacheControl; - return block; -} -function _hasAllowedImageMimeType(mimeType) { - const ALLOWED_IMAGE_MIME_TYPES = new Set([ - "image/jpeg", - "image/png", - "image/gif", - "image/webp" - ]); - return ALLOWED_IMAGE_MIME_TYPES.has(mimeType); -} -function _formatStandardContent(message) { - const result = []; - const responseMetadata = message.response_metadata; - const isAnthropicMessage = "model_provider" in responseMetadata && responseMetadata?.model_provider === "anthropic"; - for (const block of message.contentBlocks) if (block.type === "text") if (block.annotations) result.push({ - type: "text", - text: block.text, - citations: _formatStandardCitations(block.annotations) - }); - else result.push({ - type: "text", - text: block.text - }); - else if (block.type === "tool_call") result.push({ - type: "tool_use", - id: block.id ?? "", - name: block.name, - input: block.args - }); - else if (block.type === "tool_call_chunk") { - const input = dist_utils_iife(() => { - if (typeof block.args !== "string") return block.args; - try { - return JSON.parse(block.args); - } catch { - return {}; - } - }); - result.push({ - type: "tool_use", - id: block.id ?? "", - name: block.name ?? "", - input - }); - } else if (block.type === "reasoning" && isAnthropicMessage) result.push({ - type: "thinking", - thinking: block.reasoning, - signature: String(block.signature) - }); - else if (block.type === "server_tool_call" && isAnthropicMessage) { - if (block.name === "web_search") result.push({ - type: "server_tool_use", - name: block.name, - id: block.id ?? "", - input: block.args - }); - else if (block.name === "code_execution") result.push({ - type: "server_tool_use", - name: block.name, - id: block.id ?? "", - input: block.args - }); - } else if (block.type === "server_tool_call_result" && isAnthropicMessage) { - if (block.name === "web_search" && Array.isArray(block.output.urls)) { - const content = block.output.urls.map((url) => ({ - type: "web_search_result", - title: "", - encrypted_content: "", - url - })); - result.push({ - type: "web_search_tool_result", - tool_use_id: block.toolCallId ?? "", - content - }); - } else if (block.name === "code_execution") result.push({ - type: "code_execution_tool_result", - tool_use_id: block.toolCallId ?? "", - content: block.output - }); - else if (block.name === "mcp_tool_result") result.push({ - type: "mcp_tool_result", - tool_use_id: block.toolCallId ?? "", - content: block.output - }); - } else if (block.type === "audio") throw new Error("Anthropic does not support audio content blocks."); - else if (block.type === "file") { - const metadata = block.metadata; - if (block.fileId) { - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "file", - file_id: block.fileId - } - }, metadata)); - continue; - } - if (block.url) { - const mimeType = _normalizeMimeType(block.mimeType); - if (mimeType === "application/pdf" || mimeType === "") { - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "url", - url: block.url - } - }, metadata)); - continue; - } - } - if (block.data) { - const mimeType = _normalizeMimeType(block.mimeType); - if (mimeType === "" || mimeType === "application/pdf") result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: "application/pdf" - } - }, metadata)); - else if (mimeType === "text/plain") result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "text", - data: _formatBase64Data(block.data), - media_type: "text/plain" - } - }, metadata)); - else if (_hasAllowedImageMimeType(mimeType)) result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "content", - content: [{ - type: "image", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: mimeType - } - }] - } - }, metadata)); - else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`); - continue; - } - throw new Error("File content block must include a fileId, url, or data property."); - } else if (block.type === "image") { - const metadata = block.metadata; - if (block.fileId) { - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "file", - file_id: block.fileId - } - }, metadata)); - continue; - } - if (block.url) { - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "url", - url: block.url - } - }, metadata)); - continue; - } - if (block.data) { - const mimeType = _normalizeMimeType(block.mimeType) || "image/png"; - if (_hasAllowedImageMimeType(mimeType)) result.push(_applyImageMetadata({ - type: "image", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: mimeType - } - }, metadata)); - continue; - } - throw new Error("Image content block must include a fileId, url, or data property."); - } else if (block.type === "video") {} else if (block.type === "text-plain") { - if (block.data) result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "text", - data: _formatBase64Data(block.data), - media_type: "text/plain" - } - }, block.metadata)); - } else if (block.type === "non_standard" && isAnthropicMessage) result.push(block.value); - return result; -} - -//#endregion - -//# sourceMappingURL=standard.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/message_inputs.js - - - - -//#region src/utils/message_inputs.ts -function _formatImage(imageUrl) { - const parsed = parseBase64DataUrl({ dataUrl: imageUrl }); - if (parsed) return { - type: "base64", - media_type: parsed.mime_type, - data: parsed.data - }; - let parsedUrl; - try { - parsedUrl = new URL(imageUrl); - } catch { - throw new Error([ - `Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`, - "Example: data:image/png;base64,/9j/4AAQSk...", - "Example: https://example.com/image.jpg" - ].join("\n\n")); - } - if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") return { - type: "url", - url: imageUrl - }; - throw new Error([ - `Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`, - "Example: data:image/png;base64,/9j/4AAQSk...", - "Example: https://example.com/image.jpg" - ].join("\n\n")); -} -function _ensureMessageContents(messages) { - const updatedMsgs = []; - for (const message of messages) if (message._getType() === "tool") if (typeof message.content === "string") { - const previousMessage = updatedMsgs[updatedMsgs.length - 1]; - if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") previousMessage.content.push({ - type: "tool_result", - content: message.content, - tool_use_id: message.tool_call_id - }); - else updatedMsgs.push(new HumanMessage({ content: [{ - type: "tool_result", - content: message.content, - tool_use_id: message.tool_call_id - }] })); - } else updatedMsgs.push(new HumanMessage({ content: [{ - type: "tool_result", - ...message.content != null ? { content: _formatContent(message) } : {}, - tool_use_id: message.tool_call_id - }] })); - else updatedMsgs.push(message); - return updatedMsgs; -} -function _convertLangChainToolCallToAnthropic(toolCall) { - if (toolCall.id === void 0) throw new Error(`Anthropic requires all tool calls to have an "id".`); - return { - type: "tool_use", - id: toolCall.id, - name: toolCall.name, - input: toolCall.args - }; -} -function* _formatContentBlocks(content) { - const toolTypes = [ - "bash_code_execution_tool_result", - "input_json_delta", - "server_tool_use", - "text_editor_code_execution_tool_result", - "tool_result", - "tool_use", - "web_search_result", - "web_search_tool_result" - ]; - const textTypes = ["text", "text_delta"]; - for (const contentPart of content) { - if (isDataContentBlock(contentPart)) yield convertToProviderContentBlock(contentPart, standardContentBlockConverter); - const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : void 0; - if (contentPart.type === "image_url") { - let source; - if (typeof contentPart.image_url === "string") source = _formatImage(contentPart.image_url); - else if (typeof contentPart.image_url === "object" && contentPart.image_url !== null && "url" in contentPart.image_url && typeof contentPart.image_url.url === "string") source = _formatImage(contentPart.image_url.url); - if (source) yield { - type: "image", - source, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (_isAnthropicImageBlockParam(contentPart)) return contentPart; - else if (contentPart.type === "document") yield { - ...contentPart, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - else if (_isAnthropicThinkingBlock(contentPart)) { - const block = { - type: "thinking", - thinking: contentPart.thinking, - signature: contentPart.signature, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - yield block; - } else if (_isAnthropicRedactedThinkingBlock(contentPart)) { - const block = { - type: "redacted_thinking", - data: contentPart.data, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - yield block; - } else if (_isAnthropicSearchResultBlock(contentPart)) { - const block = { - type: "search_result", - title: contentPart.title, - source: contentPart.source, - ..."cache_control" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {}, - ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}, - content: contentPart.content - }; - yield block; - } else if (textTypes.find((t) => t === contentPart.type) && "text" in contentPart) yield { - type: "text", - text: contentPart.text, - ...cacheControl ? { cache_control: cacheControl } : {}, - ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {} - }; - else if (toolTypes.find((t) => t === contentPart.type)) { - const contentPartCopy = { ...contentPart }; - if ("index" in contentPartCopy) delete contentPartCopy.index; - if (contentPartCopy.type === "input_json_delta") contentPartCopy.type = "tool_use"; - if ("input" in contentPartCopy) { - if (typeof contentPartCopy.input === "string") try { - contentPartCopy.input = JSON.parse(contentPartCopy.input); - } catch { - contentPartCopy.input = {}; - } - } - yield { - ...contentPartCopy, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (contentPart.type === "container_upload") yield { - ...contentPart, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } -} -function _formatContent(message) { - const { content } = message; - if (typeof content === "string") return content; - else return Array.from(_formatContentBlocks(content)); -} -/** -* Formats messages as a prompt for the model. -* Used in LangSmith, export is important here. -* @param messages The base messages to format as a prompt. -* @returns The formatted prompt. -*/ -function message_inputs_convertMessagesToAnthropicPayload(messages) { - const mergedMessages = _ensureMessageContents(messages); - let system; - if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") system = messages[0].content; - const conversationMessages = system !== void 0 ? mergedMessages.slice(1) : mergedMessages; - const formattedMessages = conversationMessages.map((message) => { - let role; - if (message._getType() === "human") role = "user"; - else if (message._getType() === "ai") role = "assistant"; - else if (message._getType() === "tool") role = "user"; - else if (message._getType() === "system") throw new Error("System messages are only permitted as the first passed message."); - else throw new Error(`Message type "${message.type}" is not supported.`); - if (isAIMessage(message) && message.response_metadata?.output_version === "v1") return { - role, - content: _formatStandardContent(message) - }; - if (isAIMessage(message) && !!message.tool_calls?.length) if (typeof message.content === "string") if (message.content === "") return { - role, - content: message.tool_calls.map(_convertLangChainToolCallToAnthropic) - }; - else return { - role, - content: [{ - type: "text", - text: message.content - }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)] - }; - else { - const { content } = message; - const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta" || contentPart.type === "server_tool_use") && contentPart.id === toolCall.id)); - if (hasMismatchedToolCalls) console.warn(`The "tool_calls" field on a message is only respected if content is a string.`); - return { - role, - content: _formatContent(message) - }; - } - else return { - role, - content: _formatContent(message) - }; - }); - return { - messages: mergeMessages(formattedMessages), - system - }; -} -function mergeMessages(messages) { - if (!messages || messages.length <= 1) return messages; - const result = []; - let currentMessage = messages[0]; - const normalizeContent = (content) => { - if (typeof content === "string") return [{ - type: "text", - text: content - }]; - return content; - }; - const isToolResultMessage = (msg) => { - if (msg.role !== "user") return false; - if (typeof msg.content === "string") return false; - return Array.isArray(msg.content) && msg.content.every((item) => item.type === "tool_result"); - }; - for (let i = 1; i < messages.length; i += 1) { - const nextMessage = messages[i]; - if (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) currentMessage = { - ...currentMessage, - content: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)] - }; - else { - result.push(currentMessage); - currentMessage = nextMessage; - } - } - result.push(currentMessage); - return result; -} - -//#endregion - -//# sourceMappingURL=message_inputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/message_outputs.js - - - -//#region src/utils/message_outputs.ts -function _makeMessageChunkFromAnthropicEvent(data, fields) { - const response_metadata = { model_provider: "anthropic" }; - if (data.type === "message_start") { - const { content, usage,...additionalKwargs } = data.message; - const filteredAdditionalKwargs = {}; - for (const [key, value] of Object.entries(additionalKwargs)) if (value !== void 0 && value !== null) filteredAdditionalKwargs[key] = value; - const { input_tokens, output_tokens,...rest } = usage ?? {}; - const usageMetadata = { - input_tokens, - output_tokens, - total_tokens: input_tokens + output_tokens, - input_token_details: { - cache_creation: rest.cache_creation_input_tokens, - cache_read: rest.cache_read_input_tokens - } - }; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [], - additional_kwargs: filteredAdditionalKwargs, - usage_metadata: fields.streamUsage ? usageMetadata : void 0, - response_metadata: { - ...response_metadata, - usage: { ...rest } - }, - id: data.message.id - }) }; - } else if (data.type === "message_delta") { - const usageMetadata = { - input_tokens: 0, - output_tokens: data.usage.output_tokens, - total_tokens: data.usage.output_tokens, - input_token_details: { - cache_creation: data.usage.cache_creation_input_tokens, - cache_read: data.usage.cache_read_input_tokens - } - }; - const responseMetadata = "context_management" in data.delta ? { context_management: data.delta.context_management } : void 0; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [], - response_metadata: responseMetadata, - additional_kwargs: { ...data.delta }, - usage_metadata: fields.streamUsage ? usageMetadata : void 0 - }) }; - } else if (data.type === "content_block_start" && [ - "tool_use", - "document", - "server_tool_use", - "web_search_tool_result" - ].includes(data.content_block.type)) { - const contentBlock = data.content_block; - let toolCallChunks; - if (contentBlock.type === "tool_use") toolCallChunks = [{ - id: contentBlock.id, - index: data.index, - name: contentBlock.name, - args: "" - }]; - else toolCallChunks = []; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block, - input: contentBlock.type === "server_tool_use" || contentBlock.type === "tool_use" ? "" : void 0 - }], - response_metadata, - additional_kwargs: {}, - tool_call_chunks: toolCallChunks - }) }; - } else if (data.type === "content_block_delta" && [ - "text_delta", - "citations_delta", - "thinking_delta", - "signature_delta" - ].includes(data.delta.type)) if (fields.coerceContentToString && "text" in data.delta) return { chunk: new AIMessageChunk({ content: data.delta.text }) }; - else { - const contentBlock = data.delta; - if ("citation" in contentBlock) { - contentBlock.citations = [contentBlock.citation]; - delete contentBlock.citation; - } - if (contentBlock.type === "thinking_delta" || contentBlock.type === "signature_delta") return { chunk: new AIMessageChunk({ - content: [{ - index: data.index, - ...contentBlock, - type: "thinking" - }], - response_metadata - }) }; - return { chunk: new AIMessageChunk({ - content: [{ - index: data.index, - ...contentBlock, - type: "text" - }], - response_metadata - }) }; - } - else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - input: data.delta.partial_json, - type: data.delta.type - }], - response_metadata, - additional_kwargs: {}, - tool_call_chunks: [{ - index: data.index, - args: data.delta.partial_json - }] - }) }; - else if (data.type === "content_block_start" && data.content_block.type === "text") { - const content = data.content_block?.text; - if (content !== void 0) return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? content : [{ - index: data.index, - ...data.content_block - }], - response_metadata, - additional_kwargs: {} - }) }; - } else if (data.type === "content_block_start" && data.content_block.type === "redacted_thinking") return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - else if (data.type === "content_block_start" && data.content_block.type === "thinking") { - const content = data.content_block.thinking; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? content : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - } - return null; -} -function anthropicResponseToChatMessages(messages, additionalKwargs) { - const response_metadata = { - ...additionalKwargs, - model_provider: "anthropic" - }; - const usage = additionalKwargs.usage; - const usageMetadata = usage != null ? { - input_tokens: usage.input_tokens ?? 0, - output_tokens: usage.output_tokens ?? 0, - total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0), - input_token_details: { - cache_creation: usage.cache_creation_input_tokens, - cache_read: usage.cache_read_input_tokens - } - } : void 0; - if (messages.length === 1 && messages[0].type === "text") return [{ - text: messages[0].text, - message: new AIMessage({ - content: messages[0].text, - additional_kwargs: additionalKwargs, - usage_metadata: usageMetadata, - response_metadata, - id: additionalKwargs.id - }) - }]; - else { - const toolCalls = extractToolCalls(messages); - const generations = [{ - text: "", - message: new AIMessage({ - content: messages, - additional_kwargs: additionalKwargs, - tool_calls: toolCalls, - usage_metadata: usageMetadata, - response_metadata, - id: additionalKwargs.id - }) - }]; - return generations; - } -} - -//#endregion - -//# sourceMappingURL=message_outputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/errors.js -//#region src/utils/errors.ts -function errors_addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`; - return error; -} -function wrapAnthropicClientError(e) { - let error; - if (e.status === 400 && e.message.includes("tool")) error = errors_addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); - else if (e.status === 401) error = errors_addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); - else if (e.status === 404) error = errors_addLangChainErrorFields(e, "MODEL_NOT_FOUND"); - else if (e.status === 429) error = errors_addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); - else error = e; - return error; -} - -//#endregion - -//# sourceMappingURL=errors.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/tslib.mjs -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - - -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * https://stackoverflow.com/a/2117523 - */ -let uuid4 = function () { - const { crypto } = globalThis; - if (crypto?.randomUUID) { - uuid4 = crypto.randomUUID.bind(crypto); - return crypto.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; - return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); -}; -//# sourceMappingURL=uuid.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/errors.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function isAbortError(err) { - return (typeof err === 'object' && - err !== null && - // Spec-compliant fetch implementations - (('name' in err && err.name === 'AbortError') || - // Expo fetch - ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); -} -const castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - if (Object.prototype.toString.call(err) === '[object Error]') { - // @ts-ignore - not all envs have native support for cause yet - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - // @ts-ignore - not all envs have native support for cause yet - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } - catch { } - try { - return new Error(JSON.stringify(err)); - } - catch { } - } - return new Error(err); -}; -//# sourceMappingURL=errors.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_AnthropicError extends Error { -} -class APIError extends error_AnthropicError { - constructor(status, error, message, headers) { - super(`${APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get('request-id'); - this.error = error; - } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError({ message, cause: castToError(errorResponse) }); - } - const error = errorResponse; - if (status === 400) { - return new BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new PermissionDeniedError(status, error, message, headers); - } - if (status === 404) { - return new NotFoundError(status, error, message, headers); - } - if (status === 409) { - return new ConflictError(status, error, message, headers); - } - if (status === 422) { - return new UnprocessableEntityError(status, error, message, headers); - } - if (status === 429) { - return new RateLimitError(status, error, message, headers); - } - if (status >= 500) { - return new InternalServerError(status, error, message, headers); - } - return new APIError(status, error, message, headers); - } -} -class APIUserAbortError extends APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); - } -} -class APIConnectionError extends APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; - } -} -class APIConnectionTimeoutError extends APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); - } -} -class BadRequestError extends APIError { -} -class AuthenticationError extends APIError { -} -class PermissionDeniedError extends APIError { -} -class NotFoundError extends APIError { -} -class ConflictError extends APIError { -} -class UnprocessableEntityError extends APIError { -} -class RateLimitError extends APIError { -} -class InternalServerError extends APIError { -} -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -// https://url.spec.whatwg.org/#url-scheme-string -const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const isAbsoluteURL = (url) => { - return startsWithSchemeRegexp.test(url); -}; -let values_isArray = (val) => ((values_isArray = Array.isArray), values_isArray(val)); -let isReadonlyArray = values_isArray; -/** Returns an object if the given value isn't an object, otherwise returns as-is */ -function maybeObj(x) { - if (typeof x !== 'object') { - return {}; - } - return x ?? {}; -} -// https://stackoverflow.com/a/34491287 -function isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); -} -const ensurePresent = (value) => { - if (value == null) { - throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); - } - return value; -}; -const validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_AnthropicError(`${name} must be an integer`); - } - if (n < 0) { - throw new error_AnthropicError(`${name} must be a positive integer`); - } - return n; -}; -const coerceInteger = (value) => { - if (typeof value === 'number') - return Math.round(value); - if (typeof value === 'string') - return parseInt(value, 10); - throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceFloat = (value) => { - if (typeof value === 'number') - return value; - if (typeof value === 'string') - return parseFloat(value); - throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const maybeCoerceInteger = (value) => { - if (value == null) { - return undefined; - } - return coerceInteger(value); -}; -const maybeCoerceFloat = (value) => { - if (value == null) { - return undefined; - } - return coerceFloat(value); -}; -const maybeCoerceBoolean = (value) => { - if (value == null) { - return undefined; - } - return coerceBoolean(value); -}; -const safeJSON = (text) => { - try { - return JSON.parse(text); - } - catch (err) { - return undefined; - } -}; -//# sourceMappingURL=values.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -//# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/version.mjs -const VERSION = '0.65.0'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined'); -}; -/** - * Note this does not detect 'browser'; for that, use getBrowserInfo(). - */ -function getDetectedPlatform() { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return 'deno'; - } - if (typeof EdgeRuntime !== 'undefined') { - return 'edge'; - } - if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { - return 'node'; - } - return 'unknown'; -} -const getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); - if (detectedPlatform === 'deno') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', - }; - } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': globalThis.process.version, - }; - } - // Check if Node.js - if (detectedPlatform === 'node') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'), - 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', - }; - } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; - } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; - } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } - } - return null; -} -const normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') - return 'x32'; - if (arch === 'x86_64' || arch === 'x64') - return 'x64'; - if (arch === 'arm') - return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') - return 'arm64'; - if (arch) - return `other:${arch}`; - return 'unknown'; -}; -const normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) - return 'iOS'; - if (platform === 'android') - return 'Android'; - if (platform === 'darwin') - return 'MacOS'; - if (platform === 'win32') - return 'Windows'; - if (platform === 'freebsd') - return 'FreeBSD'; - if (platform === 'openbsd') - return 'OpenBSD'; - if (platform === 'linux') - return 'Linux'; - if (platform) - return `Other:${platform}`; - return 'Unknown'; -}; -let _platformHeaders; -const getPlatformHeaders = () => { - return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); -}; -//# sourceMappingURL=detect-platform.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/shims.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function getDefaultFetch() { - if (typeof fetch !== 'undefined') { - return fetch; - } - throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); -} -function makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === 'undefined') { - // Note: All of the platforms / runtimes we officially support already define - // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); - } - return new ReadableStream(...args); -} -function ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ - start() { }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } - else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - }, - }); -} -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; -} -/** - * Cancels a ReadableStream we don't need to consume. - * See https://undici.nodejs.org/#/?id=garbage-collection - */ -async function CancelReadableStream(stream) { - if (stream === null || typeof stream !== 'object') - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} -//# sourceMappingURL=shims.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/request-options.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - 'content-type': 'application/json', - }, - body: JSON.stringify(body), - }; -}; -//# sourceMappingURL=request-options.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs -function concatBytes(buffers) { - let length = 0; - for (const buffer of buffers) { - length += buffer.length; - } - const output = new Uint8Array(length); - let index = 0; - for (const buffer of buffers) { - output.set(buffer, index); - index += buffer.length; - } - return output; -} -let encodeUTF8_; -function bytes_encodeUTF8(str) { - let encoder; - return (encodeUTF8_ ?? - ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); -} -let decodeUTF8_; -function decodeUTF8(bytes) { - let decoder; - return (decodeUTF8_ ?? - ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); -} -//# sourceMappingURL=bytes.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs -var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; - - -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class LineDecoder { - constructor() { - _LineDecoder_buffer.set(this, void 0); - _LineDecoder_carriageReturnIndex.set(this, void 0); - __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - decode(chunk) { - if (chunk == null) { - return []; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) - : chunk; - __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); - const lines = []; - let patternIndex; - while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { - // skip until we either get a corresponding `\n`, a new `\r` or nothing - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; - } - // we got double \r or \rtext\n - if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); - __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - continue; - } - const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); - lines.push(line); - __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - return lines; - } - flush() { - if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { - return []; - } - return this.decode('\n'); - } -} -_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap(); -// prettier-ignore -LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); -LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; -/** - * This function searches the buffer for the end patterns, (\r or \n) - * and returns an object with the index preceding the matched newline and the - * index after the newline char. `null` is returned if no new line is found. - * - * ```ts - * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } - * ``` - */ -function findNewlineIndex(buffer, startIndex) { - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = startIndex ?? 0; i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; - } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; -} -function findDoubleNewlineIndex(buffer) { - // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) - // and returns the index right after the first occurrence of any pattern, - // or -1 if none of the patterns are found. - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - // \n\n - return i + 2; - } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - // \r\r - return i + 2; - } - if (buffer[i] === carriage && - buffer[i + 1] === newline && - i + 3 < buffer.length && - buffer[i + 2] === carriage && - buffer[i + 3] === newline) { - // \r\n\r\n - return i + 4; - } - } - return -1; -} -//# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; - } - if (hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; - } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return undefined; -}; -function noop() { } -function makeLogFn(fnLevel, logger, logLevel) { - if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; - } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); - } -} -const noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop, -}; -let cachedLoggers = /* @__PURE__ */ new WeakMap(); -function loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return noopLogger; - } - const cachedLogger = cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: makeLogFn('error', logger, logLevel), - warn: makeLogFn('warn', logger, logLevel), - info: makeLogFn('info', logger, logLevel), - debug: makeLogFn('debug', logger, logLevel), - }; - cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -const formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'x-api-key' || - name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); - } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; - } - delete details.retryOfRequestLogID; - } - return details; -}; -//# sourceMappingURL=log.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/streaming.mjs -var _Stream_client; - - - - - - - - - - -class Stream { - constructor(iterator, controller, client) { - this.iterator = iterator; - _Stream_client.set(this, void 0); - this.controller = controller; - __classPrivateFieldSet(this, _Stream_client, client, "f"); - } - static fromSSEResponse(response, controller, client) { - let consumed = false; - const logger = client ? loggerFor(client) : console; - async function* iterator() { - if (consumed) { - throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of _iterSSEMessages(response, controller)) { - if (sse.event === 'completion') { - try { - yield JSON.parse(sse.data); - } - catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === 'message_start' || - sse.event === 'message_delta' || - sse.event === 'message_stop' || - sse.event === 'content_block_start' || - sse.event === 'content_block_delta' || - sse.event === 'content_block_stop') { - try { - yield JSON.parse(sse.data); - } - catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === 'ping') { - continue; - } - if (sse.event === 'error') { - throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers); - } - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new Stream(iterator, controller, client); - } - /** - * Generates a Stream from a newline-separated ReadableStream - * where each item is a JSON value. - */ - static fromReadableStream(readableStream, controller, client) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new LineDecoder(); - const iter = ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } - } - async function* iterator() { - if (consumed) { - throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new Stream(iterator, controller, client); - } - [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { - return this.iterator(); - } - /** - * Splits the stream into two streams which can be - * independently read from at different speeds. - */ - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue) => { - return { - next: () => { - if (queue.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue.shift(); - }, - }; - }; - return [ - new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), - new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), - ]; - } - /** - * Converts this stream to a newline-separated ReadableStream of - * JSON stringified values in the stream - * which can be turned back into a Stream with `Stream.fromReadableStream()`. - */ - toReadableStream() { - const self = this; - let iter; - return makeReadableStream({ - async start() { - iter = self[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = bytes_encodeUTF8(JSON.stringify(value) + '\n'); - ctrl.enqueue(bytes); - } - catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - }, - }); - } -} -async function* _iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_AnthropicError(`Attempted to iterate over a response with no body`); - } - const sseDecoder = new SSEDecoder(); - const lineDecoder = new LineDecoder(); - const iter = ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -/** - * Given an async iterable iterator, iterates over it and yields full - * SSE chunks, i.e. yields when a double new-line is encountered. - */ -async function* iterSSEChunks(iterator) { - let data = new Uint8Array(); - for await (const chunk of iterator) { - if (chunk == null) { - continue; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) - : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); - } - } - if (data.length > 0) { - yield data; - } -} -class SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } -} -function partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; - } - return [str, '', '']; -} -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/parse.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -async function defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (props.options.stream) { - loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller); - } - return Stream.fromSSEResponse(response, props.controller); - } - // fetch refuses to read the body when the status code is 204. - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get('content-type'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - return addRequestID(json, response); - } - const text = await response.text(); - return text; - })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime, - })); - return body; -} -function addRequestID(value, response) { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return value; - } - return Object.defineProperty(value, '_request_id', { - value: response.headers.get('request-id'), - enumerable: false, - }); -} -//# sourceMappingURL=parse.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/api-promise.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _APIPromise_client; - - -/** - * A subclass of `Promise` providing additional helper methods - * for interacting with the SDK. - */ -class APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client.set(this, void 0); - __classPrivateFieldSet(this, _APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data, the raw `Response` instance and the ID of the request, - * returned via the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response, request_id: response.headers.get('request-id') }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); - } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); - } -} -_APIPromise_client = new WeakMap(); -//# sourceMappingURL=api-promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _AbstractPage_client; - - - - - -class AbstractPage { - constructor(client, response, body, options) { - _AbstractPage_client.set(this, void 0); - __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new error_AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); - } - return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; - } - } - async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } - } - } -} -/** - * This subclass of Promise will resolve to an instantiated Page once the request completes. - * - * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ -class PagePromise extends APIPromise { - constructor(client, request, Page) { - super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; - } - } -} -class Page extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.first_id = body.first_id || null; - this.last_id = body.last_id || null; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - if (this.options.query?.['before_id']) { - // in reverse - const first_id = this.first_id; - if (!first_id) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - before_id: first_id, - }, - }; - } - const cursor = this.last_id; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - after_id: cursor, - }, - }; - } -} -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/uploads.mjs - -const checkFileSupport = () => { - if (typeof File === 'undefined') { - const { process } = globalThis; - const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; - throw new Error('`File` is not defined as a global, which is required for file uploads.' + - (isOldNode ? - " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." - : '')); - } -}; -/** - * Construct a `File` instance. This is used to ensure a helpful error is thrown - * for environments that don't define a global `File` yet. - */ -function makeFile(fileBits, fileName, options) { - checkFileSupport(); - return new File(fileBits, fileName ?? 'unknown_file', options); -} -function getName(value) { - return (((typeof value === 'object' && - value !== null && - (('name' in value && value.name && String(value.name)) || - ('url' in value && value.url && String(value.url)) || - ('filename' in value && value.filename && String(value.filename)) || - ('path' in value && value.path && String(value.path)))) || - '') - .split(/[\\/]/) - .pop() || undefined); -} -const uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const maybeMultipartFormRequestOptions = async (opts, fetch) => { - if (!hasUploadableValue(opts.body)) - return opts; - return { ...opts, body: await createForm(opts.body, fetch) }; -}; -const multipartFormRequestOptions = async (opts, fetch) => { - return { ...opts, body: await createForm(opts.body, fetch) }; -}; -const supportsFormDataMap = /* @__PURE__ */ new WeakMap(); -/** - * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending - * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". - * This function detects if the fetch function provided supports the global FormData object to avoid - * confusing error messages later on. - */ -function supportsFormData(fetchObject) { - const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; - const cached = supportsFormDataMap.get(fetch); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = ('Response' in fetch ? - fetch.Response - : (await fetch('data:,')).constructor); - const data = new FormData(); - if (data.toString() === (await new FetchResponse(data).text())) { - return false; - } - return true; - } - catch { - // avoid false negatives - return true; - } - })(); - supportsFormDataMap.set(fetch, promise); - return promise; -} -const createForm = async (body, fetch) => { - if (!(await supportsFormData(fetch))) { - throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); - } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; -}; -// We check for Blob not File because Bun.File doesn't inherit from File, -// but they both inherit from Blob and have a `name` property at runtime. -const isNamedBlob = (value) => value instanceof Blob && 'name' in value; -const isUploadable = (value) => typeof value === 'object' && - value !== null && - (value instanceof Response || uploads_isAsyncIterable(value) || isNamedBlob(value)); -const hasUploadableValue = (value) => { - if (isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (hasUploadableValue(value[k])) - return true; - } - } - return false; -}; -const addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (value instanceof Response) { - let options = {}; - const contentType = value.headers.get('Content-Type'); - if (contentType) { - options = { type: contentType }; - } - form.append(key, makeFile([await value.blob()], getName(value), options)); - } - else if (uploads_isAsyncIterable(value)) { - form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); - } - else if (isNamedBlob(value)) { - form.append(key, makeFile([value], getName(value), { type: value.type })); - } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); - } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); - } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/to-file.mjs - - -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - isBlobLike(value); -const isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function toFile(value, name, options) { - checkFileSupport(); - // If it's a promise, resolve it. - value = await value; - name || (name = getName(value)); - // If we've been given a `File` we don't need to do anything if the name / options - // have not been customised. - if (isFileLike(value)) { - if (value instanceof File && name == null && options == null) { - return value; - } - return makeFile([await value.arrayBuffer()], name ?? value.name, { - type: value.type, - lastModified: value.lastModified, - ...options, - }); - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile(await to_file_getBytes(blob), name, options); - } - const parts = await to_file_getBytes(value); - if (!options?.type) { - const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return makeFile(parts, name, options); -} -async function to_file_getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } - else if (uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(...(await to_file_getBytes(chunk))); // TODO, consider validating? - } - } - else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`); - } - return parts; -} -function propsForError(value) { - if (typeof value !== 'object' || value === null) - return ''; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; -} -//# sourceMappingURL=to-file.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/uploads.mjs - -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/resource.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class APIResource { - constructor(client) { - this._client = client; - } -} -//# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/headers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); -function* iterateHeaders(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; - } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } - else if (isReadonlyArray(headers)) { - iter = headers; - } - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (let row of iter) { - const name = row[0]; - if (typeof name !== 'string') - throw new TypeError('expected header name to be a string'); - const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - // Objects keys always overwrite older headers, they never append. - // Yield a null to clear the header before adding the new values. - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } - } -} -const buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = new Set(); - for (const headers of newHeaders) { - const seenHeaders = new Set(); - for (const [name, value] of iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } - else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } - } - } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; -const isEmptyHeaders = (headers) => { - for (const _ of iterateHeaders(headers)) - return false; - return true; -}; -//# sourceMappingURL=headers.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs - -/** - * Percent-encode everything that isn't safe to have in a path without encoding safe chars. - * - * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: - * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { - // If there are no params, no processing is needed. - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); - if (index !== params.length && - (value == null || - (typeof value === 'object' && - // handle values from other realms - value.toString === - Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) - ?.toString))) { - encoded = value + ''; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString - .call(value) - .slice(8, -1)} is not a valid path parameter`, - }); - } - return previousValue + currentValue + (index === params.length ? '' : encoded); - }, ''); - const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - // Find all invalid segments - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = ' '.repeat(segment.start - lastEnd); - const arrows = '^'.repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ''); - throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments - .map((e) => e.error) - .join('\n')}\n${path}\n${underline}`); - } - return path; -}; -/** - * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. - */ -const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); -//# sourceMappingURL=path.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Files extends APIResource { - /** - * List Files - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fileMetadata of client.beta.files.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/files', (Page), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }); - } - /** - * Delete File - * - * @example - * ```ts - * const deletedFile = await client.beta.files.delete( - * 'file_id', - * ); - * ``` - */ - delete(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path `/v1/files/${fileID}`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }); - } - /** - * Download File - * - * @example - * ```ts - * const response = await client.beta.files.download( - * 'file_id', - * ); - * - * const content = await response.blob(); - * console.log(content); - * ``` - */ - download(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/files/${fileID}/content`, { - ...options, - headers: buildHeaders([ - { - 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), - Accept: 'application/binary', - }, - options?.headers, - ]), - __binaryResponse: true, - }); - } - /** - * Get File Metadata - * - * @example - * ```ts - * const fileMetadata = - * await client.beta.files.retrieveMetadata('file_id'); - * ``` - */ - retrieveMetadata(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/files/${fileID}`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }); - } - /** - * Upload File - * - * @example - * ```ts - * const fileMetadata = await client.beta.files.upload({ - * file: fs.createReadStream('path/to/file'), - * }); - * ``` - */ - upload(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/files', multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }, this._client)); - } -} -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Models extends APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - * - * @example - * ```ts - * const betaModelInfo = await client.beta.models.retrieve( - * 'model_id', - * ); - * ``` - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}?beta=true`, { - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaModelInfo of client.beta.models.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/models?beta=true', (Page), { - query, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs - - - -class JSONLDecoder { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; - } - async *decoder() { - const lineDecoder = new LineDecoder(); - for await (const chunk of this.iterator) { - for (const line of lineDecoder.decode(chunk)) { - yield JSON.parse(line); - } - } - for (const line of lineDecoder.flush()) { - yield JSON.parse(line); - } - } - [Symbol.asyncIterator]() { - return this.decoder(); - } - static fromResponse(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_AnthropicError(`Attempted to iterate over a response with no body`); - } - return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); - } -} -//# sourceMappingURL=jsonl.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/error.mjs - -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class Batches extends APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-sonnet-4-5-20250929', - * }, - * }, - * ], - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/messages/batches?beta=true', { - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaMessageBatch of client.beta.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaDeletedMessageBatch = - * await client.beta.messages.batches.delete( - * 'message_batch_id', - * ); - * ``` - */ - delete(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatchIndividualResponse = - * await client.beta.messages.batches.results( - * 'message_batch_id', - * ); - * ``` - */ - async results(messageBatchID, params = {}, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - } - const { betas } = params ?? {}; - return this._client - .get(batch.results_url, { - ...options, - headers: buildHeaders([ - { - 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), - Accept: 'application/binary', - }, - options?.headers, - ]), - stream: true, - __binaryResponse: true, - }) - ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -} -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/streaming.mjs - -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs -const tokenize = (input) => { - let current = 0; - let tokens = []; - while (current < input.length) { - let char = input[current]; - if (char === '\\') { - current++; - continue; - } - if (char === '{') { - tokens.push({ - type: 'brace', - value: '{', - }); - current++; - continue; - } - if (char === '}') { - tokens.push({ - type: 'brace', - value: '}', - }); - current++; - continue; - } - if (char === '[') { - tokens.push({ - type: 'paren', - value: '[', - }); - current++; - continue; - } - if (char === ']') { - tokens.push({ - type: 'paren', - value: ']', - }); - current++; - continue; - } - if (char === ':') { - tokens.push({ - type: 'separator', - value: ':', - }); - current++; - continue; - } - if (char === ',') { - tokens.push({ - type: 'delimiter', - value: ',', - }); - current++; - continue; - } - if (char === '"') { - let value = ''; - let danglingQuote = false; - char = input[++current]; - while (char !== '"') { - if (current === input.length) { - danglingQuote = true; - break; - } - if (char === '\\') { - current++; - if (current === input.length) { - danglingQuote = true; - break; - } - value += char + input[current]; - char = input[++current]; - } - else { - value += char; - char = input[++current]; - } - } - char = input[++current]; - if (!danglingQuote) { - tokens.push({ - type: 'string', - value, - }); - } - continue; - } - let WHITESPACE = /\s/; - if (char && WHITESPACE.test(char)) { - current++; - continue; - } - let NUMBERS = /[0-9]/; - if ((char && NUMBERS.test(char)) || char === '-' || char === '.') { - let value = ''; - if (char === '-') { - value += char; - char = input[++current]; - } - while ((char && NUMBERS.test(char)) || char === '.') { - value += char; - char = input[++current]; - } - tokens.push({ - type: 'number', - value, - }); - continue; - } - let LETTERS = /[a-z]/i; - if (char && LETTERS.test(char)) { - let value = ''; - while (char && LETTERS.test(char)) { - if (current === input.length) { - break; - } - value += char; - char = input[++current]; - } - if (value == 'true' || value == 'false' || value === 'null') { - tokens.push({ - type: 'name', - value, - }); - } - else { - // unknown token, e.g. `nul` which isn't quite `null` - current++; - continue; - } - continue; - } - current++; - } - return tokens; -}, parser_strip = (tokens) => { - if (tokens.length === 0) { - return tokens; - } - let lastToken = tokens[tokens.length - 1]; - switch (lastToken.type) { - case 'separator': - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - break; - case 'number': - let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; - if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') { - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - } - case 'string': - let tokenBeforeTheLastToken = tokens[tokens.length - 2]; - if (tokenBeforeTheLastToken?.type === 'delimiter') { - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - } - else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') { - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - } - break; - case 'delimiter': - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - break; - } - return tokens; -}, unstrip = (tokens) => { - let tail = []; - tokens.map((token) => { - if (token.type === 'brace') { - if (token.value === '{') { - tail.push('}'); - } - else { - tail.splice(tail.lastIndexOf('}'), 1); - } - } - if (token.type === 'paren') { - if (token.value === '[') { - tail.push(']'); - } - else { - tail.splice(tail.lastIndexOf(']'), 1); - } - } - }); - if (tail.length > 0) { - tail.reverse().map((item) => { - if (item === '}') { - tokens.push({ - type: 'brace', - value: '}', - }); - } - else if (item === ']') { - tokens.push({ - type: 'paren', - value: ']', - }); - } - }); - } - return tokens; -}, generate = (tokens) => { - let output = ''; - tokens.map((token) => { - switch (token.type) { - case 'string': - output += '"' + token.value + '"'; - break; - default: - output += token.value; - break; - } - }); - return output; -}, partialParse = (input) => JSON.parse(generate(unstrip(parser_strip(tokenize(input))))); - -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs -var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage; - - - - - -const JSON_BUF_PROPERTY = '__json_buf'; -function tracksToolInput(content) { - return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use'; -} -class BetaMessageStream { - constructor() { - _BetaMessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _BetaMessageStream_currentMessageSnapshot.set(this, void 0); - this.controller = new AbortController(); - _BetaMessageStream_connectedPromise.set(this, void 0); - _BetaMessageStream_resolveConnectedPromise.set(this, () => { }); - _BetaMessageStream_rejectConnectedPromise.set(this, () => { }); - _BetaMessageStream_endPromise.set(this, void 0); - _BetaMessageStream_resolveEndPromise.set(this, () => { }); - _BetaMessageStream_rejectEndPromise.set(this, () => { }); - _BetaMessageStream_listeners.set(this, {}); - _BetaMessageStream_ended.set(this, false); - _BetaMessageStream_errored.set(this, false); - _BetaMessageStream_aborted.set(this, false); - _BetaMessageStream_catchingPromiseCreated.set(this, false); - _BetaMessageStream_response.set(this, void 0); - _BetaMessageStream_request_id.set(this, void 0); - _BetaMessageStream_handleError.set(this, (error) => { - __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); - if (isAbortError(error)) { - error = new APIUserAbortError(); - } - if (error instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_AnthropicError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const anthropicError = new error_AnthropicError(error.message); - // @ts-ignore - anthropicError.cause = error; - return this._emit('error', anthropicError); - } - return this._emit('error', new error_AnthropicError(String(error))); - }); - __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { }); - __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { }); - } - get response() { - return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); - } - /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. - * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. - */ - async withResponse() { - const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); - if (!response) { - throw new Error('Could not resolve a `Response` object'); - } - return { - data: this, - response, - request_id: response.headers.get('request-id'), - }; - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new BetaMessageStream(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options) { - const runner = new BetaMessageStream(); - for (const message of params.messages) { - runner._addMessageParam(message); - } - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit('message', message); - } - } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - _connected(response) { - if (this.ended) - return; - __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit('connect'); - } - get ended() { - return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); - } - get errored() { - return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); - } - get aborted() { - return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained - */ - on(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained - */ - once(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); - } - async done() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); - } - get currentMessage() { - return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); - } - _emit(event, ...args) { - // make sure we don't emit any MessageStreamEvents after end - if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) - return; - if (event === 'end') { - __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); - } - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.final...() - // - etc. - Promise.reject(error); - } - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } - } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit('finalMessage', __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); - } - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - this._connected(null); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - return this.receivedMessages.at(-1); - }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - const textBlocks = this.receivedMessages - .at(-1) - .content.filter((block) => block.type === 'text') - .map((block) => block.text); - if (textBlocks.length === 0) { - throw new error_AnthropicError('stream ended without producing a content block with type=text'); - } - return textBlocks.join(' '); - }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { - if (this.ended) - return; - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { - if (this.ended) - return; - const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); - this._emit('streamEvent', event, messageSnapshot); - switch (event.type) { - case 'content_block_delta': { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case 'text_delta': { - if (content.type === 'text') { - this._emit('text', event.delta.text, content.text || ''); - } - break; - } - case 'citations_delta': { - if (content.type === 'text') { - this._emit('citation', event.delta.citation, content.citations ?? []); - } - break; - } - case 'input_json_delta': { - if (tracksToolInput(content) && content.input) { - this._emit('inputJson', event.delta.partial_json, content.input); - } - break; - } - case 'thinking_delta': { - if (content.type === 'thinking') { - this._emit('thinking', event.delta.thinking, content.thinking); - } - break; - } - case 'signature_delta': { - if (content.type === 'thinking') { - this._emit('signature', content.signature); - } - break; - } - default: - checkNever(event.delta); - } - break; - } - case 'message_stop': { - this._addMessageParam(messageSnapshot); - this._addMessage(messageSnapshot, true); - break; - } - case 'content_block_stop': { - this._emit('contentBlock', messageSnapshot.content.at(-1)); - break; - } - case 'message_start': { - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; - } - case 'content_block_start': - case 'message_delta': - break; - } - }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { - if (this.ended) { - throw new error_AnthropicError(`stream has ended, this shouldn't happen`); - } - const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new error_AnthropicError(`request ended without sending any chunks`); - } - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - return snapshot; - }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { - let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (event.type === 'message_start') { - if (snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - } - return event.message; - } - if (!snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - } - switch (event.type) { - case 'message_stop': - return snapshot; - case 'message_delta': - snapshot.container = event.delta.container; - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - snapshot.context_management = event.context_management; - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; - } - return snapshot; - case 'content_block_start': - snapshot.content.push(event.content_block); - return snapshot; - case 'content_block_delta': { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case 'text_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || '') + event.delta.text, - }; - } - break; - } - case 'citations_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - citations: [...(snapshotContent.citations ?? []), event.delta.citation], - }; - } - break; - } - case 'input_json_delta': { - if (snapshotContent && tracksToolInput(snapshotContent)) { - // we need to keep track of the raw JSON string as well so that we can - // re-parse it for each delta, for now we just store it as an untyped - // non-enumerable property on the snapshot - let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; - jsonBuf += event.delta.partial_json; - const newContent = { ...snapshotContent }; - Object.defineProperty(newContent, JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true, - }); - if (jsonBuf) { - try { - newContent.input = partialParse(jsonBuf); - } - catch (err) { - const error = new error_AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); - __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); - } - } - snapshot.content[event.index] = newContent; - } - break; - } - case 'thinking_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking, - }; - } - break; - } - case 'signature_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature, - }; - } - break; - } - default: - checkNever(event.delta); - } - return snapshot; - } - case 'content_block_stop': - return snapshot; - } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('streamEvent', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - toReadableStream() { - const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } -} -// used to ensure exhaustive case matching without throwing a runtime error -function checkNever(x) { } -//# sourceMappingURL=BetaMessageStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/constants.mjs -// File containing shared constants -/** - * Model-specific timeout constraints for non-streaming requests - */ -const MODEL_NONSTREAMING_TOKENS = { - 'claude-opus-4-20250514': 8192, - 'claude-opus-4-0': 8192, - 'claude-4-opus-20250514': 8192, - 'anthropic.claude-opus-4-20250514-v1:0': 8192, - 'claude-opus-4@20250514': 8192, - 'claude-opus-4-1-20250805': 8192, - 'anthropic.claude-opus-4-1-20250805-v1:0': 8192, - 'claude-opus-4-1@20250805': 8192, -}; -//# sourceMappingURL=constants.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs -var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_generateToolResponse; - - - -/** - * Just Promise.withResolvers(), which is not available in all environments. - */ -function promiseWithResolvers() { - let resolve; - let reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve: resolve, reject: reject }; -} -/** - * A ToolRunner handles the automatic conversation loop between the assistant and tools. - * - * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects - * depending on the streaming configuration. - */ -class BetaToolRunner { - constructor(client, params, options) { - _BetaToolRunner_instances.add(this); - this.client = client; - /** Whether the async iterator has been consumed */ - _BetaToolRunner_consumed.set(this, false); - /** Whether parameters have been mutated since the last API call */ - _BetaToolRunner_mutated.set(this, false); - /** Current state containing the request parameters */ - _BetaToolRunner_state.set(this, void 0); - _BetaToolRunner_options.set(this, void 0); - /** Promise for the last message received from the assistant */ - _BetaToolRunner_message.set(this, void 0); - /** Cached tool response to avoid redundant executions */ - _BetaToolRunner_toolResponse.set(this, void 0); - /** Promise resolvers for waiting on completion */ - _BetaToolRunner_completion.set(this, void 0); - /** Number of iterations (API requests) made so far */ - _BetaToolRunner_iterationCount.set(this, 0); - __classPrivateFieldSet(this, _BetaToolRunner_state, { - params: { - // You can't clone the entire params since there are functions as handlers. - // You also don't really need to clone params.messages, but it probably will prevent a foot gun - // somewhere. - ...params, - messages: structuredClone(params.messages), - }, - }, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_options, { - ...options, - headers: buildHeaders([{ 'x-stainless-helper': 'BetaToolRunner' }, options?.headers]), - }, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - } - async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), Symbol.asyncIterator)]() { - var _a; - if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { - throw new error_AnthropicError('Cannot iterate over a consumed stream'); - } - __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - try { - while (true) { - let stream; - try { - if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && - __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { - break; - } - __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f"); - const { max_iterations, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - if (params.stream) { - stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); - __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f"); - yield stream; - } - else { - __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); - yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - } - if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); - } - const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); - if (toolMessage) { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); - } - if (!toolMessage && !__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - break; - } - } - finally { - if (stream) { - stream.abort(); - } - } - } - if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { - throw new error_AnthropicError('ToolRunner concluded without a message from the server'); - } - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); - } - catch (error) { - __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); - // Silence unhandled promise errors - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { }); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - throw error; - } - } - setMessagesParams(paramsOrMutator) { - if (typeof paramsOrMutator === 'function') { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); - } - else { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; - } - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - // Invalidate cached tool response since parameters changed - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - } - /** - * Get the tool response for the last message from the assistant. - * Avoids redundant tool executions by caching results. - * - * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed - * - * @example - * const toolResponse = await runner.generateToolResponse(); - * if (toolResponse) { - * console.log('Tool results:', toolResponse.content); - * } - */ - async generateToolResponse() { - const message = (await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")) ?? this.params.messages.at(-1); - if (!message) { - return null; - } - return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message); - } - /** - * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and - * will wait for an instance to start and go to completion. - * - * @returns A promise that resolves to the final BetaMessage when the iterator completes - * - * @example - * // Start consuming the iterator - * for await (const message of runner) { - * console.log('Message:', message.content); - * } - * - * // Meanwhile, wait for completion from another part of the code - * const finalMessage = await runner.done(); - * console.log('Final response:', finalMessage.content); - */ - done() { - return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; - } - /** - * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: - * * If the iterator has not been consumed, consume the entire iterator and return the final message from the - * assistant. - * * If the iterator has been consumed, waits for it to complete and returns the final message. - * - * @returns A promise that resolves to the final BetaMessage from the conversation - * @throws {AnthropicError} If no messages were processed during the conversation - * - * @example - * const finalMessage = await runner.runUntilDone(); - * console.log('Final response:', finalMessage.content); - */ - async runUntilDone() { - // If not yet consumed, start consuming and wait for completion - if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { - for await (const _ of this) { - // Iterator naturally populates this.#message - } - } - // If consumed but not completed, wait for completion - return this.done(); - } - /** - * Get the current parameters being used by the ToolRunner. - * - * @returns A readonly view of the current ToolRunnerParams - * - * @example - * const currentParams = runner.params; - * console.log('Current model:', currentParams.model); - * console.log('Message count:', currentParams.messages.length); - */ - get params() { - return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - } - /** - * Add one or more messages to the conversation history. - * - * @param messages - One or more BetaMessageParam objects to add to the conversation - * - * @example - * runner.pushMessages( - * { role: 'user', content: 'Also, what about the weather in NYC?' } - * ); - * - * @example - * // Adding multiple messages - * runner.pushMessages( - * { role: 'user', content: 'What about NYC?' }, - * { role: 'user', content: 'And Boston?' } - * ); - */ - pushMessages(...messages) { - this.setMessagesParams((params) => ({ - ...params, - messages: [...params.messages, ...messages], - })); - } - /** - * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() - * This allows using `await runner` instead of `await runner.runUntilDone()` - */ - then(onfulfilled, onrejected) { - return this.runUntilDone().then(onfulfilled, onrejected); - } -} -_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) { - if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) { - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); - } - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f"); - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); -}; -async function generateToolResponse(params, lastMessage = params.messages.at(-1)) { - // Only process if the last message is from the assistant and has tool use blocks - if (!lastMessage || - lastMessage.role !== 'assistant' || - !lastMessage.content || - typeof lastMessage.content === 'string') { - return null; - } - const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use'); - if (toolUseBlocks.length === 0) { - return null; - } - const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { - const tool = params.tools.find((t) => t.name === toolUse.name); - if (!tool || !('run' in tool)) { - return { - type: 'tool_result', - tool_use_id: toolUse.id, - content: `Error: Tool '${toolUse.name}' not found`, - is_error: true, - }; - } - try { - let input = toolUse.input; - if ('parse' in tool && tool.parse) { - input = tool.parse(input); - } - const result = await tool.run(input); - return { - type: 'tool_result', - tool_use_id: toolUse.id, - content: result, - }; - } - catch (error) { - return { - type: 'tool_result', - tool_use_id: toolUse.id, - content: `Error: ${error instanceof Error ? error.message : String(error)}`, - is_error: true, - }; - } - })); - return { - role: 'user', - content: toolResults, - }; -} -//# sourceMappingURL=BetaToolRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -const DEPRECATED_MODELS = { - 'claude-1.3': 'November 6th, 2024', - 'claude-1.3-100k': 'November 6th, 2024', - 'claude-instant-1.1': 'November 6th, 2024', - 'claude-instant-1.1-100k': 'November 6th, 2024', - 'claude-instant-1.2': 'November 6th, 2024', - 'claude-3-sonnet-20240229': 'July 21st, 2025', - 'claude-3-opus-20240229': 'January 5th, 2026', - 'claude-2.1': 'July 21st, 2025', - 'claude-2.0': 'July 21st, 2025', - 'claude-3-5-sonnet-20241022': 'October 22, 2025', - 'claude-3-5-sonnet-20240620': 'October 22, 2025', -}; -class Messages extends APIResource { - constructor() { - super(...arguments); - this.batches = new Batches(this._client); - } - create(params, options) { - const { betas, ...body } = params; - if (body.model in DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); - } - return this._client.post('/v1/messages?beta=true', { - body, - timeout: timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - stream: params.stream ?? false, - }); - } - /** - * Create a Message stream - */ - stream(body, options) { - return BetaMessageStream.createMessage(this, body, options); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](/en/docs/build-with-claude/token-counting) - * - * @example - * ```ts - * const betaMessageTokensCount = - * await client.beta.messages.countTokens({ - * messages: [{ content: 'string', role: 'user' }], - * model: 'claude-3-7-sonnet-latest', - * }); - * ``` - */ - countTokens(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/messages/count_tokens?beta=true', { - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, - options?.headers, - ]), - }); - } - toolRunner(body, options) { - return new BetaToolRunner(this._client, body, options); - } -} - -Messages.Batches = Batches; -Messages.BetaToolRunner = BetaToolRunner; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class Beta extends APIResource { - constructor() { - super(...arguments); - this.models = new Models(this._client); - this.messages = new Messages(this._client); - this.files = new Files(this._client); - } -} -Beta.Models = Models; -Beta.Messages = Messages; -Beta.Files = Files; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Completions extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/complete', { - body, - timeout: this._client._options.timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - stream: params.stream ?? false, - }); - } -} -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs -var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; - - - - - -const MessageStream_JSON_BUF_PROPERTY = '__json_buf'; -function MessageStream_tracksToolInput(content) { - return content.type === 'tool_use' || content.type === 'server_tool_use'; -} -class MessageStream { - constructor() { - _MessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _MessageStream_currentMessageSnapshot.set(this, void 0); - this.controller = new AbortController(); - _MessageStream_connectedPromise.set(this, void 0); - _MessageStream_resolveConnectedPromise.set(this, () => { }); - _MessageStream_rejectConnectedPromise.set(this, () => { }); - _MessageStream_endPromise.set(this, void 0); - _MessageStream_resolveEndPromise.set(this, () => { }); - _MessageStream_rejectEndPromise.set(this, () => { }); - _MessageStream_listeners.set(this, {}); - _MessageStream_ended.set(this, false); - _MessageStream_errored.set(this, false); - _MessageStream_aborted.set(this, false); - _MessageStream_catchingPromiseCreated.set(this, false); - _MessageStream_response.set(this, void 0); - _MessageStream_request_id.set(this, void 0); - _MessageStream_handleError.set(this, (error) => { - __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); - if (isAbortError(error)) { - error = new APIUserAbortError(); - } - if (error instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_AnthropicError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const anthropicError = new error_AnthropicError(error.message); - // @ts-ignore - anthropicError.cause = error; - return this._emit('error', anthropicError); - } - return this._emit('error', new error_AnthropicError(String(error))); - }); - __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { }); - __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { }); - } - get response() { - return __classPrivateFieldGet(this, _MessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); - } - /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. - * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. - */ - async withResponse() { - const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); - if (!response) { - throw new Error('Could not resolve a `Response` object'); - } - return { - data: this, - response, - request_id: response.headers.get('request-id'), - }; - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new MessageStream(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options) { - const runner = new MessageStream(); - for (const message of params.messages) { - runner._addMessageParam(message); - } - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit('message', message); - } - } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - _connected(response) { - if (this.ended) - return; - __classPrivateFieldSet(this, _MessageStream_response, response, "f"); - __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f"); - __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit('connect'); - } - get ended() { - return __classPrivateFieldGet(this, _MessageStream_ended, "f"); - } - get errored() { - return __classPrivateFieldGet(this, _MessageStream_errored, "f"); - } - get aborted() { - return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained - */ - on(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained - */ - once(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); - } - async done() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); - } - get currentMessage() { - return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); - } - _emit(event, ...args) { - // make sure we don't emit any MessageStreamEvents after end - if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) - return; - if (event === 'end') { - __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); - } - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.final...() - // - etc. - Promise.reject(error); - } - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } - } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit('finalMessage', __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); - } - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - this._connected(null); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - return this.receivedMessages.at(-1); - }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - const textBlocks = this.receivedMessages - .at(-1) - .content.filter((block) => block.type === 'text') - .map((block) => block.text); - if (textBlocks.length === 0) { - throw new error_AnthropicError('stream ended without producing a content block with type=text'); - } - return textBlocks.join(' '); - }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { - if (this.ended) - return; - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { - if (this.ended) - return; - const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); - this._emit('streamEvent', event, messageSnapshot); - switch (event.type) { - case 'content_block_delta': { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case 'text_delta': { - if (content.type === 'text') { - this._emit('text', event.delta.text, content.text || ''); - } - break; - } - case 'citations_delta': { - if (content.type === 'text') { - this._emit('citation', event.delta.citation, content.citations ?? []); - } - break; - } - case 'input_json_delta': { - if (MessageStream_tracksToolInput(content) && content.input) { - this._emit('inputJson', event.delta.partial_json, content.input); - } - break; - } - case 'thinking_delta': { - if (content.type === 'thinking') { - this._emit('thinking', event.delta.thinking, content.thinking); - } - break; - } - case 'signature_delta': { - if (content.type === 'thinking') { - this._emit('signature', content.signature); - } - break; - } - default: - MessageStream_checkNever(event.delta); - } - break; - } - case 'message_stop': { - this._addMessageParam(messageSnapshot); - this._addMessage(messageSnapshot, true); - break; - } - case 'content_block_stop': { - this._emit('contentBlock', messageSnapshot.content.at(-1)); - break; - } - case 'message_start': { - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; - } - case 'content_block_start': - case 'message_delta': - break; - } - }, _MessageStream_endRequest = function _MessageStream_endRequest() { - if (this.ended) { - throw new error_AnthropicError(`stream has ended, this shouldn't happen`); - } - const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new error_AnthropicError(`request ended without sending any chunks`); - } - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - return snapshot; - }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { - let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (event.type === 'message_start') { - if (snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - } - return event.message; - } - if (!snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - } - switch (event.type) { - case 'message_stop': - return snapshot; - case 'message_delta': - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - // Update other usage fields if they exist in the event - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; - } - return snapshot; - case 'content_block_start': - snapshot.content.push({ ...event.content_block }); - return snapshot; - case 'content_block_delta': { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case 'text_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || '') + event.delta.text, - }; - } - break; - } - case 'citations_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - citations: [...(snapshotContent.citations ?? []), event.delta.citation], - }; - } - break; - } - case 'input_json_delta': { - if (snapshotContent && MessageStream_tracksToolInput(snapshotContent)) { - // we need to keep track of the raw JSON string as well so that we can - // re-parse it for each delta, for now we just store it as an untyped - // non-enumerable property on the snapshot - let jsonBuf = snapshotContent[MessageStream_JSON_BUF_PROPERTY] || ''; - jsonBuf += event.delta.partial_json; - const newContent = { ...snapshotContent }; - Object.defineProperty(newContent, MessageStream_JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true, - }); - if (jsonBuf) { - newContent.input = partialParse(jsonBuf); - } - snapshot.content[event.index] = newContent; - } - break; - } - case 'thinking_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking, - }; - } - break; - } - case 'signature_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature, - }; - } - break; - } - default: - MessageStream_checkNever(event.delta); - } - return snapshot; - } - case 'content_block_stop': - return snapshot; - } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('streamEvent', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - toReadableStream() { - const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } -} -// used to ensure exhaustive case matching without throwing a runtime error -function MessageStream_checkNever(x) { } -//# sourceMappingURL=MessageStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class batches_Batches extends APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-sonnet-4-5-20250929', - * }, - * }, - * ], - * }); - * ``` - */ - create(body, options) { - return this._client.post('/v1/messages/batches', { body, ...options }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, options) { - return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const messageBatch of client.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/v1/messages/batches', (Page), { query, ...options }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const deletedMessageBatch = - * await client.messages.batches.delete('message_batch_id'); - * ``` - */ - delete(messageBatchID, options) { - return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, options) { - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatchIndividualResponse = - * await client.messages.batches.results('message_batch_id'); - * ``` - */ - async results(messageBatchID, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - } - return this._client - .get(batch.results_url, { - ...options, - headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - stream: true, - __binaryResponse: true, - }) - ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -} -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class messages_Messages extends APIResource { - constructor() { - super(...arguments); - this.batches = new batches_Batches(this._client); - } - create(body, options) { - if (body.model in messages_DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${messages_DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); - } - return this._client.post('/v1/messages', { - body, - timeout: timeout ?? 600000, - ...options, - stream: body.stream ?? false, - }); - } - /** - * Create a Message stream - */ - stream(body, options) { - return MessageStream.createMessage(this, body, options); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](/en/docs/build-with-claude/token-counting) - * - * @example - * ```ts - * const messageTokensCount = - * await client.messages.countTokens({ - * messages: [{ content: 'string', role: 'user' }], - * model: 'claude-3-7-sonnet-latest', - * }); - * ``` - */ - countTokens(body, options) { - return this._client.post('/v1/messages/count_tokens', { body, ...options }); - } -} -const messages_DEPRECATED_MODELS = { - 'claude-1.3': 'November 6th, 2024', - 'claude-1.3-100k': 'November 6th, 2024', - 'claude-instant-1.1': 'November 6th, 2024', - 'claude-instant-1.1-100k': 'November 6th, 2024', - 'claude-instant-1.2': 'November 6th, 2024', - 'claude-3-sonnet-20240229': 'July 21st, 2025', - 'claude-3-opus-20240229': 'January 5th, 2026', - 'claude-2.1': 'July 21st, 2025', - 'claude-2.0': 'July 21st, 2025', - 'claude-3-5-sonnet-20241022': 'October 22, 2025', - 'claude-3-5-sonnet-20240620': 'October 22, 2025', -}; -messages_Messages.Batches = batches_Batches; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class models_Models extends APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}`, { - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/models', (Page), { - query, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. - * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. - */ -const readEnv = (env) => { - if (typeof globalThis.process !== 'undefined') { - return globalThis.process.env?.[env]?.trim() ?? undefined; - } - if (typeof globalThis.Deno !== 'undefined') { - return globalThis.Deno.env?.get?.(env)?.trim(); - } - return undefined; -}; -//# sourceMappingURL=env.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/client.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden; - - - - - - - - - - - - - - - - - - - - - - - -const HUMAN_PROMPT = '\\n\\nHuman:'; -const AI_PROMPT = '\\n\\nAssistant:'; -/** - * Base class for Anthropic API clients. - */ -class BaseAnthropic { - /** - * API Client for interfacing with the Anthropic API. - * - * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] - * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] - * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { - _BaseAnthropic_instances.add(this); - _BaseAnthropic_encoder.set(this, void 0); - const options = { - apiKey, - authToken, - ...opts, - baseURL: baseURL || `https://api.anthropic.com`, - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { - throw new error_AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); - } - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */; - this.logger = options.logger ?? console; - const defaultLogLevel = 'warn'; - // Set default logLevel early so that we can log a warning in parseLogLevel. - this.logLevel = defaultLogLevel; - this.logLevel = - parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? - defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); - this._options = options; - this.apiKey = apiKey; - this.authToken = authToken; - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - authToken: this.authToken, - ...options, - }); - return client; - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - if (this.apiKey && values.get('x-api-key')) { - return; - } - if (nulls.has('x-api-key')) { - return; - } - if (this.authToken && values.get('authorization')) { - return; - } - if (nulls.has('authorization')) { - return; - } - throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); - } - async authHeaders(opts) { - return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); - } - async apiKeyAuth(opts) { - if (this.apiKey == null) { - return undefined; - } - return buildHeaders([{ 'X-Api-Key': this.apiKey }]); - } - async bearerAuth(opts) { - if (this.authToken == null) { - return undefined; - } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); - } - /** - * Basic re-implementation of `qs.stringify` for primitive types. - */ - stringifyQuery(query) { - return Object.entries(query) - .filter(([_, value]) => typeof value !== 'undefined') - .map(([key, value]) => { - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - } - if (value === null) { - return `${encodeURIComponent(key)}=`; - } - throw new error_AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); - }) - .join('&'); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); - } - buildURL(path, query, defaultBaseURL) { - const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; - const url = isAbsoluteURL(path) ? - new URL(path) - : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); - } - _calculateNonstreamingTimeout(maxTokens) { - const defaultTimeout = 10 * 60; - const expectedTimeout = (60 * 60 * maxTokens) / 128000; - if (expectedTimeout > defaultTimeout) { - throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' + - 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); - } - return defaultTimeout * 1000; - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => { - return { method, path, ...opts }; - })); - } - request(options, remainingRetries = null) { - return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); - } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining, - }); - await this.prepareRequest(req, { url, options }); - /** Not an API request ID, just for correlating local log entries. */ - const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); - const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers, - })); - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - // detect native connection timeout errors - // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" - // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" - // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = isAbortError(response) || - /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - if (isTimeout) { - throw new APIConnectionTimeoutError(); - } - throw new APIConnectionError({ cause: response }); - } - const specialHeaders = [...response.headers.entries()] - .filter(([name]) => name === 'request-id') - .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) - .join(''); - const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - // We don't need the body of this response. - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err) => castToError(err).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime, - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; - } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null, undefined); - return new PagePromise(this, request, Page); - } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - if (signal) - signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || - (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); - const fetchOptions = { - signal: controller.signal, - ...(isReadableBody ? { duplex: 'half' } : {}), - method: 'GET', - ...options, - }; - if (method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = method.toUpperCase(); - } - try { - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - return await this.fetch.call(undefined, url, fetchOptions); - } - finally { - clearTimeout(timeout); - } - } - async shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') - return true; - if (shouldRetryHeader === 'false') - return false; - // Retry on request timeouts. - if (response.status === 408) - return true; - // Retry on lock timeouts. - if (response.status === 409) - return true; - // Retry on rate limits. - if (response.status === 429) - return true; - // Retry internal errors. - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. - const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - const retryAfterHeader = responseHeaders?.get('retry-after'); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; - } - else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8.0; - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - // Apply some jitter, take up to at most 25 percent of the retry time. - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; - } - calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { - const maxTime = 60 * 60 * 1000; // 60 minutes - const defaultTime = 60 * 10 * 1000; // 10 minutes - const expectedTime = (maxTime * maxTokens) / 128000; - if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { - throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); - } - return defaultTime; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, defaultBaseURL } = options; - const url = this.buildURL(path, query, defaultBaseURL); - if ('timeout' in options) - validatePositiveInteger('timeout', options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...(options.signal && { signal: options.signal }), - ...(globalThis.ReadableStream && - body instanceof globalThis.ReadableStream && { duplex: 'half' }), - ...(body && { body }), - ...(this.fetchOptions ?? {}), - ...(options.fetchOptions ?? {}), - }; - return { req, url, timeout: options.timeout }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount, }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== 'get') { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...getPlatformHeaders(), - ...(this._options.dangerouslyAllowBrowser ? - { 'anthropic-dangerous-direct-browser-access': 'true' } - : undefined), - 'anthropic-version': '2023-06-01', - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers, - ]); - this.validateHeaders(headers); - return headers.values; - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: undefined, body: undefined }; - } - const headers = buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || - body instanceof ArrayBuffer || - body instanceof DataView || - (typeof body === 'string' && - // Preserve legacy string encoding behavior for now - headers.values.has('content-type')) || - // `Blob` is superset of `File` - (globalThis.Blob && body instanceof globalThis.Blob) || - // `FormData` -> `multipart/form-data` - body instanceof FormData || - // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || - // Send chunked stream (each chunk has own `length`) - (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { - return { bodyHeaders: undefined, body: body }; - } - else if (typeof body === 'object' && - (Symbol.asyncIterator in body || - (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; - } - else { - return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); - } - } -} -_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { - return this.baseURL !== 'https://api.anthropic.com'; -}; -BaseAnthropic.Anthropic = _a; -BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; -BaseAnthropic.AI_PROMPT = AI_PROMPT; -BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes -BaseAnthropic.AnthropicError = error_AnthropicError; -BaseAnthropic.APIError = APIError; -BaseAnthropic.APIConnectionError = APIConnectionError; -BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; -BaseAnthropic.APIUserAbortError = APIUserAbortError; -BaseAnthropic.NotFoundError = NotFoundError; -BaseAnthropic.ConflictError = ConflictError; -BaseAnthropic.RateLimitError = RateLimitError; -BaseAnthropic.BadRequestError = BadRequestError; -BaseAnthropic.AuthenticationError = AuthenticationError; -BaseAnthropic.InternalServerError = InternalServerError; -BaseAnthropic.PermissionDeniedError = PermissionDeniedError; -BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; -BaseAnthropic.toFile = toFile; -/** - * API Client for interfacing with the Anthropic API. - */ -class Anthropic extends BaseAnthropic { - constructor() { - super(...arguments); - this.completions = new Completions(this); - this.messages = new messages_Messages(this); - this.models = new models_Models(this); - this.beta = new Beta(this); - } -} -Anthropic.Completions = Completions; -Anthropic.Messages = messages_Messages; -Anthropic.Models = models_Models; -Anthropic.Beta = Beta; -//# sourceMappingURL=client.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/chat_models.js - - - - - - - - - - - - - - - - -//#region src/chat_models.ts -const MODEL_DEFAULT_MAX_OUTPUT_TOKENS = { - "claude-opus-4-1": 8192, - "claude-opus-4": 8192, - "claude-sonnet-4": 8192, - "claude-sonnet-3-7-sonnet": 8192, - "claude-3-5-sonnet": 4096, - "claude-3-5-haiku": 4096, - "claude-3-haiku": 2048 -}; -const FALLBACK_MAX_OUTPUT_TOKENS = 2048; -function defaultMaxOutputTokensForModel(model) { - if (!model) return FALLBACK_MAX_OUTPUT_TOKENS; - const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1]; - return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS; -} -function _toolsInParams(params) { - return !!(params.tools && params.tools.length > 0); -} -function _documentsInParams(params) { - for (const message of params.messages ?? []) { - if (typeof message.content === "string") continue; - for (const block of message.content ?? []) if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) return true; - } - return false; -} -function _thinkingInParams(params) { - return !!(params.thinking && params.thinking.type === "enabled"); -} -function isAnthropicTool(tool) { - return "input_schema" in tool; -} -function isBuiltinTool(tool) { - const builtInToolPrefixes = [ - "text_editor_", - "computer_", - "bash_", - "web_search_", - "web_fetch_", - "str_replace_editor_", - "str_replace_based_edit_tool_", - "code_execution_", - "memory_" - ]; - return typeof tool === "object" && tool !== null && "type" in tool && "name" in tool && typeof tool.type === "string" && builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix)); -} -function extractToken(chunk) { - if (typeof chunk.content === "string") return chunk.content; - else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); - else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") return chunk.content[0].text; - return void 0; -} -/** -* Anthropic chat model integration. -* -* Setup: -* Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`. -* -* ```bash -* npm install @langchain/anthropic -* export ANTHROPIC_API_KEY="your-api-key" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.bind`, call options should be passed via the first argument -* const llmWithArgsBound = llm.bindTools([...]).withConfig({ -* stop: ["\n"], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* tool_choice: "auto", -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { ChatAnthropic } from '@langchain/anthropic'; -* -* const llm = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* temperature: 0, -* maxTokens: undefined, -* maxRetries: 2, -* // apiKey: "...", -* // baseUrl: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", -* "content": "Here's the translation to French:\n\nJ'adore la programmation.", -* "response_metadata": { -* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", -* "model": "claude-sonnet-4-5-20250929", -* "stop_reason": "end_turn", -* "stop_sequence": null, -* "usage": { -* "input_tokens": 25, -* "output_tokens": 19 -* }, -* "type": "message", -* "role": "assistant" -* }, -* "usage_metadata": { -* "input_tokens": 25, -* "output_tokens": 19, -* "total_tokens": 44 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", -* "content": "", -* "additional_kwargs": { -* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", -* "type": "message", -* "role": "assistant", -* "model": "claude-sonnet-4-5-20250929" -* }, -* "usage_metadata": { -* "input_tokens": 25, -* "output_tokens": 1, -* "total_tokens": 26 -* } -* } -* AIMessageChunk { -* "content": "", -* } -* AIMessageChunk { -* "content": "Here", -* } -* AIMessageChunk { -* "content": "'s", -* } -* AIMessageChunk { -* "content": " the translation to", -* } -* AIMessageChunk { -* "content": " French:\n\nJ", -* } -* AIMessageChunk { -* "content": "'adore la programmation", -* } -* AIMessageChunk { -* "content": ".", -* } -* AIMessageChunk { -* "content": "", -* "additional_kwargs": { -* "stop_reason": "end_turn", -* "stop_sequence": null -* }, -* "usage_metadata": { -* "input_tokens": 0, -* "output_tokens": 19, -* "total_tokens": 19 -* } -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", -* "content": "Here's the translation to French:\n\nJ'adore la programmation.", -* "additional_kwargs": { -* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", -* "type": "message", -* "role": "assistant", -* "model": "claude-sonnet-4-5-20250929", -* "stop_reason": "end_turn", -* "stop_sequence": null -* }, -* "usage_metadata": { -* "input_tokens": 25, -* "output_tokens": 20, -* "total_tokens": 45 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* id: 'toolu_01WjW3Dann6BPJVtLhovdBD5', -* type: 'tool_call' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe', -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* id: 'toolu_0165qYWBA2VFyUst5RA18zew', -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* id: 'toolu_01PGNyP33vxr13tGqr7i3rDo', -* type: 'tool_call' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* import { z } from 'zod'; -* -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: "Why don't cats play poker in the jungle?", -* punchline: 'Too many cheetahs!', -* rating: 7 -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 25, output_tokens: 19, total_tokens: 44 } -* ``` -*
-* -*
-* -*
-* Stream Usage Metadata -* -* ```typescript -* const streamForMetadata = await llm.stream( -* input, -* { -* streamUsage: true -* } -* ); -* let fullForMetadata: AIMessageChunk | undefined; -* for await (const chunk of streamForMetadata) { -* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk); -* } -* console.log(fullForMetadata?.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 25, output_tokens: 20, total_tokens: 45 } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* id: 'msg_01STxeQxJmp4sCSpioD6vK3L', -* model: 'claude-sonnet-4-5-20250929', -* stop_reason: 'end_turn', -* stop_sequence: null, -* usage: { input_tokens: 25, output_tokens: 19 }, -* type: 'message', -* role: 'assistant' -* } -* ``` -*
-* -*
-*/ -var ChatAnthropicMessages = class extends BaseChatModel { - static lc_name() { - return "ChatAnthropic"; - } - get lc_secrets() { - return { - anthropicApiKey: "ANTHROPIC_API_KEY", - apiKey: "ANTHROPIC_API_KEY" - }; - } - get lc_aliases() { - return { modelName: "model" }; - } - lc_serializable = true; - anthropicApiKey; - apiKey; - apiUrl; - temperature; - topK; - topP; - maxTokens; - modelName = "claude-3-5-sonnet-latest"; - model = "claude-3-5-sonnet-latest"; - invocationKwargs; - stopSequences; - streaming = false; - clientOptions; - thinking = { type: "disabled" }; - contextManagement; - batchClient; - streamingClient; - streamUsage = true; - /** - * Optional method that returns an initialized underlying Anthropic client. - * Useful for accessing Anthropic models hosted on other cloud services - * such as Google Vertex. - */ - createClient; - constructor(fields) { - super(fields ?? {}); - this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY"); - if (!this.anthropicApiKey && !fields?.createClient) throw new Error("Anthropic API key not found"); - this.clientOptions = fields?.clientOptions ?? {}; - /** Keep anthropicApiKey for backwards compatibility */ - this.apiKey = this.anthropicApiKey; - this.apiUrl = fields?.anthropicApiUrl; - /** Keep modelName for backwards compatibility */ - this.modelName = fields?.model ?? fields?.modelName ?? this.model; - this.model = this.modelName; - this.invocationKwargs = fields?.invocationKwargs ?? {}; - this.topP = fields?.topP ?? this.topP; - this.temperature = fields?.temperature ?? this.temperature; - this.topK = fields?.topK ?? this.topK; - this.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model); - this.stopSequences = fields?.stopSequences ?? this.stopSequences; - this.streaming = fields?.streaming ?? false; - this.streamUsage = fields?.streamUsage ?? this.streamUsage; - this.thinking = fields?.thinking ?? this.thinking; - this.contextManagement = fields?.contextManagement ?? this.contextManagement; - this.createClient = fields?.createClient ?? ((options) => new Anthropic(options)); - } - getLsParams(options) { - const params = this.invocationParams(options); - return { - ls_provider: "anthropic", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: params.temperature ?? void 0, - ls_max_tokens: params.max_tokens ?? void 0, - ls_stop: options.stop - }; - } - /** - * Formats LangChain StructuredTools to AnthropicTools. - * - * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format - * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed. - */ - formatStructuredToolToAnthropic(tools) { - if (!tools || !tools.length) return void 0; - return tools.map((tool) => { - if (isBuiltinTool(tool)) return tool; - if (isAnthropicTool(tool)) return tool; - if (isOpenAITool(tool)) return { - name: tool.function.name, - description: tool.function.description, - input_schema: tool.function.parameters - }; - if (isLangChainTool(tool)) return { - name: tool.name, - description: tool.description, - input_schema: isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema - }; - throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`); - }); - } - bindTools(tools, kwargs) { - return this.withConfig({ - tools: this.formatStructuredToolToAnthropic(tools), - ...kwargs - }); - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - const tool_choice = handleToolChoice(options?.tool_choice); - if (this.thinking.type === "enabled") { - if (this.topP !== void 0 && this.topK !== -1) throw new Error("topK is not supported when thinking is enabled"); - if (this.temperature !== void 0 && this.temperature !== 1) throw new Error("temperature is not supported when thinking is enabled"); - return { - model: this.model, - stop_sequences: options?.stop ?? this.stopSequences, - stream: this.streaming, - max_tokens: this.maxTokens, - tools: this.formatStructuredToolToAnthropic(options?.tools), - tool_choice, - thinking: this.thinking, - context_management: this.contextManagement, - ...this.invocationKwargs, - container: options?.container - }; - } - return { - model: this.model, - temperature: this.temperature, - top_k: this.topK, - top_p: this.topP, - stop_sequences: options?.stop ?? this.stopSequences, - stream: this.streaming, - max_tokens: this.maxTokens, - tools: this.formatStructuredToolToAnthropic(options?.tools), - tool_choice, - thinking: this.thinking, - context_management: this.contextManagement, - ...this.invocationKwargs, - container: options?.container - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams() - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams() - }; - } - async *_streamResponseChunks(messages, options, runManager) { - const params = this.invocationParams(options); - const formattedMessages = message_inputs_convertMessagesToAnthropicPayload(messages); - const payload = { - ...params, - ...formattedMessages, - stream: true - }; - const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload); - const stream = await this.createStreamWithRetry(payload, { headers: options.headers }); - for await (const data of stream) { - if (options.signal?.aborted) { - stream.controller.abort(); - throw new Error("AbortError: User aborted the request."); - } - const shouldStreamUsage = this.streamUsage ?? options.streamUsage; - const result = _makeMessageChunkFromAnthropicEvent(data, { - streamUsage: shouldStreamUsage, - coerceContentToString - }); - if (!result) continue; - const { chunk } = result; - const token = extractToken(chunk); - const generationChunk = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: chunk.content, - additional_kwargs: chunk.additional_kwargs, - tool_call_chunks: chunk.tool_call_chunks, - usage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0, - response_metadata: chunk.response_metadata, - id: chunk.id - }), - text: token ?? "" - }); - yield generationChunk; - await runManager?.handleLLMNewToken(token ?? "", void 0, void 0, void 0, void 0, { chunk: generationChunk }); - } - } - /** @ignore */ - async _generateNonStreaming(messages, params, requestOptions) { - const response = await this.completionWithRetry({ - ...params, - stream: false, - ...message_inputs_convertMessagesToAnthropicPayload(messages) - }, requestOptions); - const { content,...additionalKwargs } = response; - const generations = anthropicResponseToChatMessages(content, additionalKwargs); - const { role: _role, type: _type,...rest } = additionalKwargs; - return { - generations, - llmOutput: rest - }; - } - /** @ignore */ - async _generate(messages, options, runManager) { - if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`); - const params = this.invocationParams(options); - if (params.stream) { - let finalChunk; - const stream = this._streamResponseChunks(messages, options, runManager); - for await (const chunk of stream) if (finalChunk === void 0) finalChunk = chunk; - else finalChunk = finalChunk.concat(chunk); - if (finalChunk === void 0) throw new Error("No chunks returned from Anthropic API."); - return { generations: [{ - text: finalChunk.text, - message: finalChunk.message - }] }; - } else return this._generateNonStreaming(messages, params, { - signal: options.signal, - headers: options.headers - }); - } - /** - * Creates a streaming request with retry. - * @param request The parameters for creating a completion. - * @param options - * @returns A streaming request. - */ - async createStreamWithRetry(request, options) { - if (!this.streamingClient) { - const options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0; - this.streamingClient = this.createClient({ - dangerouslyAllowBrowser: true, - ...this.clientOptions, - ...options_, - apiKey: this.apiKey, - maxRetries: 0 - }); - } - const makeCompletionRequest = async () => { - try { - return await this.streamingClient.messages.create({ - ...request, - ...this.invocationKwargs, - stream: true - }, options); - } catch (e) { - const error = wrapAnthropicClientError(e); - throw error; - } - }; - return this.caller.call(makeCompletionRequest); - } - /** @ignore */ - async completionWithRetry(request, options) { - if (!this.batchClient) { - const options$1 = this.apiUrl ? { baseURL: this.apiUrl } : void 0; - this.batchClient = this.createClient({ - dangerouslyAllowBrowser: true, - ...this.clientOptions, - ...options$1, - apiKey: this.apiKey, - maxRetries: 0 - }); - } - const makeCompletionRequest = async () => { - try { - return await this.batchClient.messages.create({ - ...request, - ...this.invocationKwargs - }, options); - } catch (e) { - const error = wrapAnthropicClientError(e); - throw error; - } - }; - return this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest); - } - _llmType() { - return "anthropic"; - } - withStructuredOutput(outputSchema, config) { - const schema = outputSchema; - const name = config?.name; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") throw new Error(`Anthropic only supports "functionCalling" as a method.`); - let functionName = name ?? "extract"; - let outputParser; - let tools; - if (isInteropZodSchema(schema)) { - const jsonSchema = toJsonSchema(schema); - tools = [{ - name: functionName, - description: jsonSchema.description ?? "A function available to call.", - input_schema: jsonSchema - }]; - outputParser = new AnthropicToolsOutputParser({ - returnSingle: true, - keyName: functionName, - zodSchema: schema - }); - } else { - let anthropicTools; - if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) { - anthropicTools = schema; - functionName = schema.name; - } else anthropicTools = { - name: functionName, - description: schema.description ?? "", - input_schema: schema - }; - tools = [anthropicTools]; - outputParser = new AnthropicToolsOutputParser({ - returnSingle: true, - keyName: functionName - }); - } - let llm; - if (this.thinking?.type === "enabled") { - const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called."; - console.warn(thinkingAdmonition); - llm = this.withConfig({ - outputVersion: "v0", - tools, - ls_structured_output_format: { - kwargs: { method: "functionCalling" }, - schema: toJsonSchema(schema) - } - }); - const raiseIfNoToolCalls = (message) => { - if (!message.tool_calls || message.tool_calls.length === 0) throw new Error(thinkingAdmonition); - return message; - }; - llm = llm.pipe(raiseIfNoToolCalls); - } else llm = this.withConfig({ - outputVersion: "v0", - tools, - tool_choice: { - type: "tool", - name: functionName - }, - ls_structured_output_format: { - kwargs: { method: "functionCalling" }, - schema: toJsonSchema(schema) - } - }); - if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatAnthropicStructuredOutput" }); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); - } -}; -var ChatAnthropic = class extends ChatAnthropicMessages {}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/prompts.js - - -//#region src/utils/prompts.ts -/** -* Convert a formatted LangChain prompt (e.g. pulled from the hub) into -* a format expected by Anthropic's JS SDK. -* -* Requires the "@langchain/anthropic" package to be installed in addition -* to the Anthropic SDK. -* -* @example -* ```ts -* import { convertPromptToAnthropic } from "langsmith/utils/hub/anthropic"; -* import { pull } from "langchain/hub"; -* -* import Anthropic from '@anthropic-ai/sdk'; -* -* const prompt = await pull("jacob/joke-generator"); -* const formattedPrompt = await prompt.invoke({ -* topic: "cats", -* }); -* -* const { system, messages } = convertPromptToAnthropic(formattedPrompt); -* -* const anthropicClient = new Anthropic({ -* apiKey: 'your_api_key', -* }); -* -* const anthropicResponse = await anthropicClient.messages.create({ -* model: "claude-sonnet-4-5-20250929", -* max_tokens: 1024, -* stream: false, -* system, -* messages, -* }); -* ``` -* @param formattedPrompt -* @returns A partial Anthropic payload. -*/ -function convertPromptToAnthropic(formattedPrompt) { - const messages = formattedPrompt.toChatMessages(); - const anthropicBody = _convertMessagesToAnthropicPayload(messages); - if (anthropicBody.messages === void 0) anthropicBody.messages = []; - return anthropicBody; -} - -//#endregion - -//# sourceMappingURL=prompts.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/index.js - - - - -;// CONCATENATED MODULE: ./src/providers/anthropic.provider.ts - -/** - * Anthropic Claude provider implementation - */ -class AnthropicProvider { - name = 'anthropic'; - apiKey; - constructor(apiKey) { - this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || ''; - } - isConfigured() { - return !!this.apiKey; - } - getDefaultModel() { - return 'claude-sonnet-4-5-20250929'; - } - getChatModel(config = {}) { - if (!this.isConfigured()) { - throw new Error('Anthropic API key is not configured'); - } - return new ChatAnthropic({ - apiKey: this.apiKey, - modelName: config.model || this.getDefaultModel(), - temperature: config.temperature ?? 0.2, - maxTokens: config.maxTokens ?? 4000, - }); - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/misc.js - - -//#region src/utils/misc.ts -const misc_iife = (fn) => fn(); -function isReasoningModel(model) { - if (!model) return false; - if (/^o\d/.test(model ?? "")) return true; - if (model.startsWith("gpt-5") && !model.startsWith("gpt-5-chat")) return true; - return false; -} -function extractGenericMessageCustomRole(message) { - if (message.role !== "system" && message.role !== "developer" && message.role !== "assistant" && message.role !== "user" && message.role !== "function" && message.role !== "tool") console.warn(`Unknown message role: ${message.role}`); - return message.role; -} -function messageToOpenAIRole(message) { - const type = message._getType(); - switch (type) { - case "system": return "system"; - case "ai": return "assistant"; - case "human": return "user"; - case "function": return "function"; - case "tool": return "tool"; - case "generic": - if (!ChatMessage.isInstance(message)) throw new Error("Invalid generic chat message"); - return extractGenericMessageCustomRole(message); - default: throw new Error(`Unknown message type: ${type}`); - } -} - -//#endregion - -//# sourceMappingURL=misc.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/azure.js - - -//#region src/utils/azure.ts -/** -* This function generates an endpoint URL for (Azure) OpenAI -* based on the configuration parameters provided. -* -* @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint. -* -* @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI. -* @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`. -* @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI. -* @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`. -* @property {string} config.baseURL - Some other custom base path URL. -* @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`. -* -* The function operates as follows: -* - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`). -* - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`). -* - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters. -* - If none of the above conditions are met, return any custom `baseURL`. -* - The function returns the generated URL as a string, or undefined if no custom paths are specified. -* -* @throws Will throw an error if the necessary parameters for generating the URL are missing. -* -* @returns {string | undefined} The generated (Azure) OpenAI endpoint URL. -*/ -function getEndpoint(config) { - const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, azureADTokenProvider, azureOpenAIEndpoint } = config; - if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; - if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIEndpoint && azureOpenAIApiDeploymentName) return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`; - if (azureOpenAIApiKey || azureADTokenProvider) { - if (!azureOpenAIApiInstanceName) throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); - if (!azureOpenAIApiDeploymentName) throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); - return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; - } - return baseURL; -} -function isHeaders(headers) { - return typeof Headers !== "undefined" && headers !== null && typeof headers === "object" && Object.prototype.toString.call(headers) === "[object Headers]"; -} -/** -* Normalizes various header formats into a consistent Record format. -* -* This function accepts headers in multiple formats and converts them to a -* Record for consistent handling. -* -* @param headers - The headers to normalize. Can be: -* - A Headers instance -* - An array of [key, value] pairs -* - A plain object with string keys -* - A NullableHeaders-like object with a 'values' property containing Headers -* - null or undefined -* @returns A normalized Record containing the header key-value pairs -* -* @example -* ```ts -* // With Headers instance -* const headers1 = new Headers([['content-type', 'application/json']]); -* const normalized1 = normalizeHeaders(headers1); -* -* // With plain object -* const headers2 = { 'content-type': 'application/json' }; -* const normalized2 = normalizeHeaders(headers2); -* -* // With array of pairs -* const headers3 = [['content-type', 'application/json']]; -* const normalized3 = normalizeHeaders(headers3); -* ``` -*/ -function normalizeHeaders(headers) { - const output = misc_iife(() => { - if (isHeaders(headers)) return headers; - else if (Array.isArray(headers)) return new Headers(headers); - else if (typeof headers === "object" && headers !== null && "values" in headers && isHeaders(headers.values)) return headers.values; - else if (typeof headers === "object" && headers !== null) { - const entries = Object.entries(headers).filter(([, v]) => typeof v === "string").map(([k, v]) => [k, v]); - return new Headers(entries); - } - return new Headers(); - }); - return Object.fromEntries(output.entries()); -} - -//#endregion - -//# sourceMappingURL=azure.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/tools.js - - - - -//#region src/utils/tools.ts -/** -* Formats a tool in either OpenAI format, or LangChain structured tool format -* into an OpenAI tool format. If the tool is already in OpenAI format, return without -* any changes. If it is in LangChain structured tool format, convert it to OpenAI tool format -* using OpenAI's `zodFunction` util, falling back to `convertToOpenAIFunction` if the parameters -* returned from the `zodFunction` util are not defined. -* -* @param {BindToolsInput} tool The tool to convert to an OpenAI tool. -* @param {Object} [fields] Additional fields to add to the OpenAI tool. -* @returns {ToolDefinition} The inputted tool in OpenAI tool format. -*/ -function _convertToOpenAITool(tool, fields) { - let toolDef; - if (isLangChainTool(tool)) toolDef = convertToOpenAITool(tool); - else toolDef = tool; - if (fields?.strict !== void 0) toolDef.function.strict = fields.strict; - return toolDef; -} -function isAnyOfProp(prop) { - return prop.anyOf !== void 0 && Array.isArray(prop.anyOf); -} -function formatFunctionDefinitions(functions) { - const lines = ["namespace functions {", ""]; - for (const f of functions) { - if (f.description) lines.push(`// ${f.description}`); - if (Object.keys(f.parameters.properties ?? {}).length > 0) { - lines.push(`type ${f.name} = (_: {`); - lines.push(formatObjectProperties(f.parameters, 0)); - lines.push("}) => any;"); - } else lines.push(`type ${f.name} = () => any;`); - lines.push(""); - } - lines.push("} // namespace functions"); - return lines.join("\n"); -} -function formatObjectProperties(obj, indent) { - const lines = []; - for (const [name, param] of Object.entries(obj.properties ?? {})) { - if (param.description && indent < 2) lines.push(`// ${param.description}`); - if (obj.required?.includes(name)) lines.push(`${name}: ${formatType(param, indent)},`); - else lines.push(`${name}?: ${formatType(param, indent)},`); - } - return lines.map((line) => " ".repeat(indent) + line).join("\n"); -} -function formatType(param, indent) { - if (isAnyOfProp(param)) return param.anyOf.map((v) => formatType(v, indent)).join(" | "); - switch (param.type) { - case "string": - if (param.enum) return param.enum.map((v) => `"${v}"`).join(" | "); - return "string"; - case "number": - if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); - return "number"; - case "integer": - if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); - return "number"; - case "boolean": return "boolean"; - case "null": return "null"; - case "object": return [ - "{", - formatObjectProperties(param, indent + 2), - "}" - ].join("\n"); - case "array": - if (param.items) return `${formatType(param.items, indent)}[]`; - return "any[]"; - default: return ""; - } -} -function formatToOpenAIToolChoice(toolChoice) { - if (!toolChoice) return void 0; - else if (toolChoice === "any" || toolChoice === "required") return "required"; - else if (toolChoice === "auto") return "auto"; - else if (toolChoice === "none") return "none"; - else if (typeof toolChoice === "string") return { - type: "function", - function: { name: toolChoice } - }; - else return toolChoice; -} -function isBuiltInTool(tool) { - return "type" in tool && tool.type !== "function"; -} -function isBuiltInToolChoice(tool_choice) { - return tool_choice != null && typeof tool_choice === "object" && "type" in tool_choice && tool_choice.type !== "function"; -} -function isCustomTool(tool) { - return typeof tool === "object" && tool !== null && "metadata" in tool && typeof tool.metadata === "object" && tool.metadata !== null && "customTool" in tool.metadata && typeof tool.metadata.customTool === "object" && tool.metadata.customTool !== null; -} -function isOpenAICustomTool(tool) { - return "type" in tool && tool.type === "custom" && "custom" in tool && typeof tool.custom === "object" && tool.custom !== null; -} -function parseCustomToolCall(rawToolCall) { - if (rawToolCall.type !== "custom_tool_call") return void 0; - return { - ...rawToolCall, - type: "tool_call", - call_id: rawToolCall.id, - id: rawToolCall.call_id, - name: rawToolCall.name, - isCustomTool: true, - args: { input: rawToolCall.input } - }; -} -function isCustomToolCall(toolCall) { - return toolCall.type === "tool_call" && "isCustomTool" in toolCall && toolCall.isCustomTool === true; -} -function convertCompletionsCustomTool(tool) { - const getFormat = () => { - if (!tool.custom.format) return void 0; - if (tool.custom.format.type === "grammar") return { - type: "grammar", - definition: tool.custom.format.grammar.definition, - syntax: tool.custom.format.grammar.syntax - }; - if (tool.custom.format.type === "text") return { type: "text" }; - return void 0; - }; - return { - type: "custom", - name: tool.custom.name, - description: tool.custom.description, - format: getFormat() - }; -} -function convertResponsesCustomTool(tool) { - const getFormat = () => { - if (!tool.format) return void 0; - if (tool.format.type === "grammar") return { - type: "grammar", - grammar: { - definition: tool.format.definition, - syntax: tool.format.syntax - } - }; - if (tool.format.type === "text") return { type: "text" }; - return void 0; - }; - return { - type: "custom", - custom: { - name: tool.name, - description: tool.description, - format: getFormat() - } - }; -} - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/errors.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function errors_isAbortError(err) { - return (typeof err === 'object' && - err !== null && - // Spec-compliant fetch implementations - (('name' in err && err.name === 'AbortError') || - // Expo fetch - ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); -} -const errors_castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - if (Object.prototype.toString.call(err) === '[object Error]') { - // @ts-ignore - not all envs have native support for cause yet - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - // @ts-ignore - not all envs have native support for cause yet - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } - catch { } - try { - return new Error(JSON.stringify(err)); - } - catch { } - } - return new Error(err); -}; -//# sourceMappingURL=errors.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_OpenAIError extends Error { -} -class error_APIError extends error_OpenAIError { - constructor(status, error, message, headers) { - super(`${error_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get('x-request-id'); - this.error = error; - const data = error; - this.code = data?.['code']; - this.param = data?.['param']; - this.type = data?.['type']; - } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new error_APIConnectionError({ message, cause: errors_castToError(errorResponse) }); - } - const error = errorResponse?.['error']; - if (status === 400) { - return new error_BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new error_AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new error_PermissionDeniedError(status, error, message, headers); - } - if (status === 404) { - return new error_NotFoundError(status, error, message, headers); - } - if (status === 409) { - return new error_ConflictError(status, error, message, headers); - } - if (status === 422) { - return new error_UnprocessableEntityError(status, error, message, headers); - } - if (status === 429) { - return new error_RateLimitError(status, error, message, headers); - } - if (status >= 500) { - return new error_InternalServerError(status, error, message, headers); - } - return new error_APIError(status, error, message, headers); - } -} -class error_APIUserAbortError extends error_APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); - } -} -class error_APIConnectionError extends error_APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; - } -} -class error_APIConnectionTimeoutError extends error_APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); - } -} -class error_BadRequestError extends error_APIError { -} -class error_AuthenticationError extends error_APIError { -} -class error_PermissionDeniedError extends error_APIError { -} -class error_NotFoundError extends error_APIError { -} -class error_ConflictError extends error_APIError { -} -class error_UnprocessableEntityError extends error_APIError { -} -class error_RateLimitError extends error_APIError { -} -class error_InternalServerError extends error_APIError { -} -class LengthFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the length limit was reached`); - } -} -class ContentFilterFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the request was rejected by the content filter`); - } -} -class InvalidWebhookSignatureError extends Error { - constructor(message) { - super(message); - } -} -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/error.mjs - -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs - -function isChatCompletionFunctionTool(tool) { - return tool !== undefined && 'function' in tool && tool.function !== undefined; -} -function makeParseableResponseFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function parser_makeParseableTextFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableResponseFormat(response_format) { - return response_format?.['$brand'] === 'auto-parseable-response-format'; -} -function parser_makeParseableTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function maybeParseChatCompletion(completion, params) { - if (!params || !hasAutoParseableInput(params)) { - return { - ...completion, - choices: completion.choices.map((choice) => { - assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); - return { - ...choice, - message: { - ...choice.message, - parsed: null, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls, - } - : undefined), - }, - }; - }), - }; - } - return parseChatCompletion(completion, params); -} -function parseChatCompletion(completion, params) { - const choices = completion.choices.map((choice) => { - if (choice.finish_reason === 'length') { - throw new LengthFinishReasonError(); - } - if (choice.finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); - return { - ...choice, - message: { - ...choice.message, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls?.map((toolCall) => parser_parseToolCall(params, toolCall)) ?? undefined, - } - : undefined), - parsed: choice.message.content && !choice.message.refusal ? - parseResponseFormat(params, choice.message.content) - : null, - }, - }; - }); - return { ...completion, choices }; -} -function parseResponseFormat(params, content) { - if (params.response_format?.type !== 'json_schema') { - return null; - } - if (params.response_format?.type === 'json_schema') { - if ('$parseRaw' in params.response_format) { - const response_format = params.response_format; - return response_format.$parseRaw(content); - } - return JSON.parse(content); - } - return null; -} -function parser_parseToolCall(params, toolCall) { - const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); // TS doesn't narrow based on isChatCompletionTool - return { - ...toolCall, - function: { - ...toolCall.function, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) - : null, - }, - }; -} -function shouldParseToolCall(params, toolCall) { - if (!params || !('tools' in params) || !params.tools) { - return false; - } - const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); - return (isChatCompletionFunctionTool(inputTool) && - (isAutoParsableTool(inputTool) || inputTool?.function.strict || false)); -} -function hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.response_format)) { - return true; - } - return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); -} -function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { - for (const toolCall of toolCalls || []) { - if (toolCall.type !== 'function') { - throw new error_OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); - } - } -} -function validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } - } -} -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Options.mjs -const Options_ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); -const zod_to_json_schema_Options_defaultOptions = { - name: undefined, - $refStrategy: 'root', - effectStrategy: 'input', - pipeStrategy: 'all', - dateStrategy: 'format:date-time', - mapStrategy: 'entries', - nullableStrategy: 'from-target', - removeAdditionalStrategy: 'passthrough', - definitionPath: 'definitions', - target: 'jsonSchema7', - strictUnions: false, - errorMessages: false, - markdownDescription: false, - patternStrategy: 'escape', - applyRegexFlags: false, - emailStrategy: 'format:email', - base64Strategy: 'contentEncoding:base64', - nameStrategy: 'ref', -}; -const Options_getDefaultOptions = (options) => { - // We need to add `definitions` here as we may mutate it - return (typeof options === 'string' ? - { - ...zod_to_json_schema_Options_defaultOptions, - basePath: ['#'], - definitions: {}, - name: options, - } - : { - ...zod_to_json_schema_Options_defaultOptions, - basePath: ['#'], - definitions: {}, - ...options, - }); -}; -//# sourceMappingURL=Options.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/util.mjs -const zodDef = (zodSchema) => { - return '_def' in zodSchema ? zodSchema._def : zodSchema; -}; -function util_isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -//# sourceMappingURL=util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs - - -const Refs_getRefs = (options) => { - const _options = Options_getDefaultOptions(options); - const currentPath = _options.name !== undefined ? - [..._options.basePath, _options.definitionPath, _options.name] - : _options.basePath; - return { - ..._options, - currentPath: currentPath, - propertyPath: undefined, - seenRefs: new Set(), - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - zodDef(def), - { - def: zodDef(def), - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: undefined, - }, - ])), - }; -}; -//# sourceMappingURL=Refs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs -function any_parseAnyDef() { - return {}; -} -//# sourceMappingURL=any.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs -function errorMessages_addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage, - }; - } -} -function errorMessages_setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - errorMessages_addErrorMessage(res, key, errorMessage, refs); -} -//# sourceMappingURL=errorMessages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs - - - -function array_parseArrayDef(def, refs) { - const res = { - type: 'array', - }; - if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { - res.items = parseDef_parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, 'items'], - }); - } - if (def.minLength) { - errorMessages_setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs); - } - if (def.maxLength) { - errorMessages_setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); - } - if (def.exactLength) { - errorMessages_setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); - errorMessages_setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); - } - return res; -} -//# sourceMappingURL=array.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs - -function bigint_parseBigintDef(def, refs) { - const res = { - type: 'integer', - format: 'int64', - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case 'min': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - break; - case 'max': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - break; - case 'multipleOf': - errorMessages_setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); - break; - } - } - return res; -} -//# sourceMappingURL=bigint.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs -function boolean_parseBooleanDef() { - return { - type: 'boolean', - }; -} -//# sourceMappingURL=boolean.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs - -function branded_parseBrandedDef(_def, refs) { - return parseDef_parseDef(_def.type._def, refs); -} -//# sourceMappingURL=branded.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs - -const catch_parseCatchDef = (def, refs) => { - return parseDef_parseDef(def.innerType._def, refs); -}; -//# sourceMappingURL=catch.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs - -function date_parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i) => date_parseDateDef(def, refs, item)), - }; - } - switch (strategy) { - case 'string': - case 'format:date-time': - return { - type: 'string', - format: 'date-time', - }; - case 'format:date': - return { - type: 'string', - format: 'date', - }; - case 'integer': - return date_integerDateParser(def, refs); - } -} -const date_integerDateParser = (def, refs) => { - const res = { - type: 'integer', - format: 'unix-time', - }; - if (refs.target === 'openApi3') { - return res; - } - for (const check of def.checks) { - switch (check.kind) { - case 'min': - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds - check.message, refs); - break; - case 'max': - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds - check.message, refs); - break; - } - } - return res; -}; -//# sourceMappingURL=date.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs - -function default_parseDefaultDef(_def, refs) { - return { - ...parseDef_parseDef(_def.innerType._def, refs), - default: _def.defaultValue(), - }; -} -//# sourceMappingURL=default.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs - -function effects_parseEffectsDef(_def, refs, forceResolution) { - return refs.effectStrategy === 'input' ? parseDef_parseDef(_def.schema._def, refs, forceResolution) : {}; -} -//# sourceMappingURL=effects.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs -function enum_parseEnumDef(def) { - return { - type: 'string', - enum: [...def.values], - }; -} -//# sourceMappingURL=enum.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs - -const intersection_isJsonSchema7AllOfType = (type) => { - if ('type' in type && type.type === 'string') - return false; - return 'allOf' in type; -}; -function intersection_parseIntersectionDef(def, refs) { - const allOf = [ - parseDef_parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', '0'], - }), - parseDef_parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', '1'], - }), - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined; - const mergedAllOf = []; - // If either of the schemas is an allOf, merge them into a single allOf - allOf.forEach((schema) => { - if (intersection_isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === undefined) { - // If one of the schemas has no unevaluatedProperties set, - // the merged schema should also have no unevaluatedProperties set - unevaluatedProperties = undefined; - } - } - else { - let nestedSchema = schema; - if ('additionalProperties' in schema && schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; - } - else { - // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties - unevaluatedProperties = undefined; - } - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length ? - { - allOf: mergedAllOf, - ...unevaluatedProperties, - } - : undefined; -} -//# sourceMappingURL=intersection.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs -function literal_parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== 'bigint' && - parsedType !== 'number' && - parsedType !== 'boolean' && - parsedType !== 'string') { - return { - type: Array.isArray(def.value) ? 'array' : 'object', - }; - } - if (refs.target === 'openApi3') { - return { - type: parsedType === 'bigint' ? 'integer' : parsedType, - enum: [def.value], - }; - } - return { - type: parsedType === 'bigint' ? 'integer' : parsedType, - const: def.value, - }; -} -//# sourceMappingURL=literal.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs - -let parsers_string_emojiRegex; -/** - * Generated from the regular expressions found here as of 2024-05-22: - * https://github.com/colinhacks/zod/blob/master/src/types.ts. - * - * Expressions with /i flag have been changed accordingly. - */ -const string_zodPatterns = { - /** - * `c` was changed to `[cC]` to replicate /i flag - */ - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - /** - * `a-z` was added to replicate /i flag - */ - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - /** - * Constructed a valid Unicode RegExp - * - * Lazily instantiate since this type of regex isn't supported - * in all envs (e.g. React Native). - * - * See: - * https://github.com/colinhacks/zod/issues/2433 - * Fix in Zod: - * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b - */ - emoji: () => { - if (parsers_string_emojiRegex === undefined) { - parsers_string_emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u'); - } - return parsers_string_emojiRegex; - }, - /** - * Unused - */ - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - /** - * Unused - */ - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - /** - * Unused - */ - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, -}; -function string_parseStringDef(def, refs) { - const res = { - type: 'string', - }; - function processPattern(value) { - return refs.patternStrategy === 'escape' ? string_escapeNonAlphaNumeric(value) : value; - } - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case 'min': - errorMessages_setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - break; - case 'max': - errorMessages_setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case 'email': - switch (refs.emailStrategy) { - case 'format:email': - string_addFormat(res, 'email', check.message, refs); - break; - case 'format:idn-email': - string_addFormat(res, 'idn-email', check.message, refs); - break; - case 'pattern:zod': - string_addPattern(res, string_zodPatterns.email, check.message, refs); - break; - } - break; - case 'url': - string_addFormat(res, 'uri', check.message, refs); - break; - case 'uuid': - string_addFormat(res, 'uuid', check.message, refs); - break; - case 'regex': - string_addPattern(res, check.regex, check.message, refs); - break; - case 'cuid': - string_addPattern(res, string_zodPatterns.cuid, check.message, refs); - break; - case 'cuid2': - string_addPattern(res, string_zodPatterns.cuid2, check.message, refs); - break; - case 'startsWith': - string_addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); - break; - case 'endsWith': - string_addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); - break; - case 'datetime': - string_addFormat(res, 'date-time', check.message, refs); - break; - case 'date': - string_addFormat(res, 'date', check.message, refs); - break; - case 'time': - string_addFormat(res, 'time', check.message, refs); - break; - case 'duration': - string_addFormat(res, 'duration', check.message, refs); - break; - case 'length': - errorMessages_setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - errorMessages_setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case 'includes': { - string_addPattern(res, RegExp(processPattern(check.value)), check.message, refs); - break; - } - case 'ip': { - if (check.version !== 'v6') { - string_addFormat(res, 'ipv4', check.message, refs); - } - if (check.version !== 'v4') { - string_addFormat(res, 'ipv6', check.message, refs); - } - break; - } - case 'emoji': - string_addPattern(res, string_zodPatterns.emoji, check.message, refs); - break; - case 'ulid': { - string_addPattern(res, string_zodPatterns.ulid, check.message, refs); - break; - } - case 'base64': { - switch (refs.base64Strategy) { - case 'format:binary': { - string_addFormat(res, 'binary', check.message, refs); - break; - } - case 'contentEncoding:base64': { - errorMessages_setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs); - break; - } - case 'pattern:zod': { - string_addPattern(res, string_zodPatterns.base64, check.message, refs); - break; - } - } - break; - } - case 'nanoid': { - string_addPattern(res, string_zodPatterns.nanoid, check.message, refs); - } - case 'toLowerCase': - case 'toUpperCase': - case 'trim': - break; - default: - ((_) => { })(check); - } - } - } - return res; -} -const string_escapeNonAlphaNumeric = (value) => Array.from(value) - .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) - .join(''); -const string_addFormat = (schema, value, message, refs) => { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) { - schema.anyOf = []; - } - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format }, - }), - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.anyOf.push({ - format: value, - ...(message && refs.errorMessages && { errorMessage: { format: message } }), - }); - } - else { - errorMessages_setResponseValueAndErrors(schema, 'format', value, message, refs); - } -}; -const string_addPattern = (schema, regex, message, refs) => { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) { - schema.allOf = []; - } - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern }, - }), - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.allOf.push({ - pattern: processRegExp(regex, refs), - ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), - }); - } - else { - errorMessages_setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs); - } -}; -// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true -const processRegExp = (regexOrFunction, refs) => { - const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction; - if (!refs.applyRegexFlags || !regex.flags) - return regex.source; - // Currently handled flags - const flags = { - i: regex.flags.includes('i'), // Case-insensitive - m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters - s: regex.flags.includes('s'), // `.` matches newlines - }; - // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ''; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } - else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } - else { - pattern += `${source[i]}${source[i].toUpperCase()}`; - } - continue; - } - } - else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i] === '^') { - pattern += `(^|(?<=[\r\n]))`; - continue; - } - else if (source[i] === '$') { - pattern += `($|(?=[\r\n]))`; - continue; - } - } - if (flags.s && source[i] === '.') { - pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; - continue; - } - pattern += source[i]; - if (source[i] === '\\') { - isEscaped = true; - } - else if (inCharGroup && source[i] === ']') { - inCharGroup = false; - } - else if (!inCharGroup && source[i] === '[') { - inCharGroup = true; - } - } - try { - const regexTest = new RegExp(pattern); - } - catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -}; -//# sourceMappingURL=string.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs - - - -function record_parseRecordDef(def, refs) { - if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - type: 'object', - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'properties', key], - }) ?? {}, - }), {}), - additionalProperties: false, - }; - } - const schema = { - type: 'object', - additionalProperties: parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalProperties'], - }) ?? {}, - }; - if (refs.target === 'openApi3') { - return schema; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const keyType = Object.entries(string_parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {}); - return { - ...schema, - propertyNames: keyType, - }; - } - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - ...schema, - propertyNames: { - enum: def.keyType._def.values, - }, - }; - } - return schema; -} -//# sourceMappingURL=record.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs - - -function map_parseMapDef(def, refs) { - if (refs.mapStrategy === 'record') { - return record_parseRecordDef(def, refs); - } - const keys = parseDef_parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', 'items', '0'], - }) || {}; - const values = parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', 'items', '1'], - }) || {}; - return { - type: 'array', - maxItems: 125, - items: { - type: 'array', - items: [keys, values], - minItems: 2, - maxItems: 2, - }, - }; -} -//# sourceMappingURL=map.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs -function nativeEnum_parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== 'number'; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? - parsedTypes[0] === 'string' ? - 'string' - : 'number' - : ['string', 'number'], - enum: actualValues, - }; -} -//# sourceMappingURL=nativeEnum.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs -function never_parseNeverDef() { - return { - not: {}, - }; -} -//# sourceMappingURL=never.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs -function null_parseNullDef(refs) { - return refs.target === 'openApi3' ? - { - enum: ['null'], - nullable: true, - } - : { - type: 'null', - }; -} -//# sourceMappingURL=null.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs - -const union_primitiveMappings = { - ZodString: 'string', - ZodNumber: 'number', - ZodBigInt: 'integer', - ZodBoolean: 'boolean', - ZodNull: 'null', -}; -function union_parseUnionDef(def, refs) { - if (refs.target === 'openApi3') - return union_asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. - if (options.every((x) => x._def.typeName in union_primitiveMappings && (!x._def.checks || !x._def.checks.length))) { - // all types in union are primitive and lack checks, so might as well squash into {type: [...]} - const types = options.reduce((types, x) => { - const type = union_primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 - return type && !types.includes(type) ? [...types, type] : types; - }, []); - return { - type: types.length > 1 ? types : types[0], - }; - } - else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) { - // all options literals - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case 'string': - case 'number': - case 'boolean': - return [...acc, type]; - case 'bigint': - return [...acc, 'integer']; - case 'object': - if (x._def.value === null) - return [...acc, 'null']; - case 'symbol': - case 'undefined': - case 'function': - default: - return acc; - } - }, []); - if (types.length === options.length) { - // all the literals are primitive, as far as null can be considered primitive - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []), - }; - } - } - else if (options.every((x) => x._def.typeName === 'ZodEnum')) { - return { - type: 'string', - enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []), - }; - } - return union_asAnyOf(def, refs); -} -const union_asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options) - .map((x, i) => parseDef_parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, 'anyOf', `${i}`], - })) - .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0))); - return anyOf.length ? { anyOf } : undefined; -}; -//# sourceMappingURL=union.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs - - -function nullable_parseNullableDef(def, refs) { - if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && - (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { - return { - type: union_primitiveMappings[def.innerType._def.typeName], - nullable: true, - }; - } - return { - type: [union_primitiveMappings[def.innerType._def.typeName], 'null'], - }; - } - if (refs.target === 'openApi3') { - const base = parseDef_parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath], - }); - if (base && '$ref' in base) - return { allOf: [base], nullable: true }; - return base && { ...base, nullable: true }; - } - const base = parseDef_parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, 'anyOf', '0'], - }); - return base && { anyOf: [base, { type: 'null' }] }; -} -//# sourceMappingURL=nullable.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs - -function number_parseNumberDef(def, refs) { - const res = { - type: 'number', - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case 'int': - res.type = 'integer'; - errorMessages_addErrorMessage(res, 'type', check.message, refs); - break; - case 'min': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - break; - case 'max': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - break; - case 'multipleOf': - errorMessages_setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); - break; - } - } - return res; -} -//# sourceMappingURL=number.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs - -function object_decideAdditionalProperties(def, refs) { - if (refs.removeAdditionalStrategy === 'strict') { - return def.catchall._def.typeName === 'ZodNever' ? - def.unknownKeys !== 'strict' - : parseDef_parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalProperties'], - }) ?? true; - } - else { - return def.catchall._def.typeName === 'ZodNever' ? - def.unknownKeys === 'passthrough' - : parseDef_parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalProperties'], - }) ?? true; - } -} -function object_parseObjectDef(def, refs) { - const result = { - type: 'object', - ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { - if (propDef === undefined || propDef._def === undefined) - return acc; - const propertyPath = [...refs.currentPath, 'properties', propName]; - const parsedDef = parseDef_parseDef(propDef._def, { - ...refs, - currentPath: propertyPath, - propertyPath, - }); - if (parsedDef === undefined) - return acc; - if (refs.openaiStrictMode && - propDef.isOptional() && - !propDef.isNullable() && - typeof propDef._def?.defaultValue === 'undefined') { - throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); - } - return { - properties: { - ...acc.properties, - [propName]: parsedDef, - }, - required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName], - }; - }, { properties: {}, required: [] }), - additionalProperties: object_decideAdditionalProperties(def, refs), - }; - if (!result.required.length) - delete result.required; - return result; -} -//# sourceMappingURL=object.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs - -const optional_parseOptionalDef = (def, refs) => { - if (refs.propertyPath && - refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) { - return parseDef_parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath }); - } - const innerSchema = parseDef_parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, 'anyOf', '1'], - }); - return innerSchema ? - { - anyOf: [ - { - not: {}, - }, - innerSchema, - ], - } - : {}; -}; -//# sourceMappingURL=optional.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs - -const pipeline_parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === 'input') { - return parseDef_parseDef(def.in._def, refs); - } - else if (refs.pipeStrategy === 'output') { - return parseDef_parseDef(def.out._def, refs); - } - const a = parseDef_parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', '0'], - }); - const b = parseDef_parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], - }); - return { - allOf: [a, b].filter((x) => x !== undefined), - }; -}; -//# sourceMappingURL=pipeline.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs - -function promise_parsePromiseDef(def, refs) { - return parseDef_parseDef(def.type._def, refs); -} -//# sourceMappingURL=promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs - - -function set_parseSetDef(def, refs) { - const items = parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'items'], - }); - const schema = { - type: 'array', - uniqueItems: true, - items, - }; - if (def.minSize) { - errorMessages_setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - errorMessages_setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} -//# sourceMappingURL=set.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs - -function tuple_parseTupleDef(def, refs) { - if (def.rest) { - return { - type: 'array', - minItems: def.items.length, - items: def.items - .map((x, i) => parseDef_parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - additionalItems: parseDef_parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalItems'], - }), - }; - } - else { - return { - type: 'array', - minItems: def.items.length, - maxItems: def.items.length, - items: def.items - .map((x, i) => parseDef_parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - }; - } -} -//# sourceMappingURL=tuple.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs -function undefined_parseUndefinedDef() { - return { - not: {}, - }; -} -//# sourceMappingURL=undefined.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs -function unknown_parseUnknownDef() { - return {}; -} -//# sourceMappingURL=unknown.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs - -const readonly_parseReadonlyDef = (def, refs) => { - return parseDef_parseDef(def.innerType._def, refs); -}; -//# sourceMappingURL=readonly.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -function parseDef_parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== Options_ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = parseDef_get$ref(seenItem, refs); - if (seenSchema !== undefined) { - if ('$ref' in seenSchema) { - refs.seenRefs.add(seenSchema.$ref); - } - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; - refs.seen.set(def, newItem); - const jsonSchema = parseDef_selectParser(def, def.typeName, refs, forceResolution); - if (jsonSchema) { - parseDef_addMeta(def, refs, jsonSchema); - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -const parseDef_get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case 'root': - return { $ref: item.path.join('/') }; - // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e. - // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever - // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract - // the schema to `#/definitions/` and reference that. - // - // e.g. if we need to reference a schema at - // `["#","definitions","contactPerson","properties","person1","properties","name"]` - // then we'll extract it out to `contactPerson_properties_person1_properties_name` - case 'extract-to-root': - const name = item.path.slice(refs.basePath.length + 1).join('_'); - // we don't need to extract the root schema in this case, as it's already - // been added to the definitions - if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') { - refs.definitions[name] = item.def; - } - return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') }; - case 'relative': - return { $ref: parseDef_getRelativePath(refs.currentPath, item.path) }; - case 'none': - case 'seen': { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`); - return {}; - } - return refs.$refStrategy === 'seen' ? {} : undefined; - } - } -}; -const parseDef_getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/'); -}; -const parseDef_selectParser = (def, typeName, refs, forceResolution) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: - return string_parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: - return number_parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: - return object_parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: - return bigint_parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: - return boolean_parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: - return date_parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: - return undefined_parseUndefinedDef(); - case ZodFirstPartyTypeKind.ZodNull: - return null_parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: - return array_parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return union_parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: - return intersection_parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: - return tuple_parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: - return record_parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: - return literal_parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return enum_parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return nativeEnum_parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return nullable_parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return optional_parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return map_parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return set_parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return parseDef_parseDef(def.getter()._def, refs); - case ZodFirstPartyTypeKind.ZodPromise: - return promise_parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return never_parseNeverDef(); - case ZodFirstPartyTypeKind.ZodEffects: - return effects_parseEffectsDef(def, refs, forceResolution); - case ZodFirstPartyTypeKind.ZodAny: - return any_parseAnyDef(); - case ZodFirstPartyTypeKind.ZodUnknown: - return unknown_parseUnknownDef(); - case ZodFirstPartyTypeKind.ZodDefault: - return default_parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return branded_parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return readonly_parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return catch_parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return pipeline_parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return undefined; - default: - return ((_) => undefined)(typeName); - } -}; -const parseDef_addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; -//# sourceMappingURL=parseDef.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs - - - -const zod_to_json_schema_zodToJsonSchema_zodToJsonSchema = (schema, options) => { - const refs = Refs_getRefs(options); - const name = typeof options === 'string' ? options - : options?.nameStrategy === 'title' ? undefined - : options?.name; - const main = parseDef_parseDef(schema._def, name === undefined ? refs : ({ - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }), false) ?? {}; - const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ? - options.name - : undefined; - if (title !== undefined) { - main.title = title; - } - const definitions = (() => { - if (util_isEmptyObj(refs.definitions)) { - return undefined; - } - const definitions = {}; - const processedDefinitions = new Set(); - // the call to `parseDef()` here might itself add more entries to `.definitions` - // so we need to continually evaluate definitions until we've resolved all of them - // - // we have a generous iteration limit here to avoid blowing up the stack if there - // are any bugs that would otherwise result in us iterating indefinitely - for (let i = 0; i < 500; i++) { - const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key)); - if (newDefinitions.length === 0) - break; - for (const [key, schema] of newDefinitions) { - definitions[key] = - parseDef_parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {}; - processedDefinitions.add(key); - } - } - return definitions; - })(); - const combined = name === undefined ? - definitions ? - { - ...main, - [refs.definitionPath]: definitions, - } - : main - : refs.nameStrategy === 'duplicate-ref' ? - { - ...main, - ...(definitions || refs.seenRefs.size ? - { - [refs.definitionPath]: { - ...definitions, - // only actually duplicate the schema definition if it was ever referenced - // otherwise the duplication is completely pointless - ...(refs.seenRefs.size ? { [name]: main } : undefined), - }, - } - : undefined), - } - : { - $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'), - [refs.definitionPath]: { - ...definitions, - [name]: main, - }, - }; - if (refs.target === 'jsonSchema7') { - combined.$schema = 'http://json-schema.org/draft-07/schema#'; - } - else if (refs.target === 'jsonSchema2019-09') { - combined.$schema = 'https://json-schema.org/draft/2019-09/schema#'; - } - return combined; -}; - -//# sourceMappingURL=zodToJsonSchema.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/index.mjs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* harmony default export */ const zod_to_json_schema = ((/* unused pure expression or super */ null && (zodToJsonSchema))); -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ResponsesParser.mjs - - -function maybeParseResponse(response, params) { - if (!params || !ResponsesParser_hasAutoParseableInput(params)) { - return { - ...response, - output_parsed: null, - output: response.output.map((item) => { - if (item.type === 'function_call') { - return { - ...item, - parsed_arguments: null, - }; - } - if (item.type === 'message') { - return { - ...item, - content: item.content.map((content) => ({ - ...content, - parsed: null, - })), - }; - } - else { - return item; - } - }), - }; - } - return parseResponse(response, params); -} -function parseResponse(response, params) { - const output = response.output.map((item) => { - if (item.type === 'function_call') { - return { - ...item, - parsed_arguments: ResponsesParser_parseToolCall(params, item), - }; - } - if (item.type === 'message') { - const content = item.content.map((content) => { - if (content.type === 'output_text') { - return { - ...content, - parsed: parseTextFormat(params, content.text), - }; - } - return content; - }); - return { - ...item, - content, - }; - } - return item; - }); - const parsed = Object.assign({}, response, { output }); - if (!Object.getOwnPropertyDescriptor(response, 'output_text')) { - addOutputText(parsed); - } - Object.defineProperty(parsed, 'output_parsed', { - enumerable: true, - get() { - for (const output of parsed.output) { - if (output.type !== 'message') { - continue; - } - for (const content of output.content) { - if (content.type === 'output_text' && content.parsed !== null) { - return content.parsed; - } - } - } - return null; - }, - }); - return parsed; -} -function parseTextFormat(params, content) { - if (params.text?.format?.type !== 'json_schema') { - return null; - } - if ('$parseRaw' in params.text?.format) { - const text_format = params.text?.format; - return text_format.$parseRaw(content); - } - return JSON.parse(content); -} -function ResponsesParser_hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.text?.format)) { - return true; - } - return false; -} -function ResponsesParser_makeParseableResponseTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function ResponsesParser_isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function getInputToolByName(input_tools, name) { - return input_tools.find((tool) => tool.type === 'function' && tool.name === name); -} -function ResponsesParser_parseToolCall(params, toolCall) { - const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); - return { - ...toolCall, - ...toolCall, - parsed_arguments: ResponsesParser_isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) - : inputTool?.strict ? JSON.parse(toolCall.arguments) - : null, - }; -} -function ResponsesParser_shouldParseToolCall(params, toolCall) { - if (!params) { - return false; - } - const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); - return ResponsesParser_isAutoParsableTool(inputTool) || inputTool?.strict || false; -} -function ResponsesParser_validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } - } -} -function addOutputText(rsp) { - const texts = []; - for (const output of rsp.output) { - if (output.type !== 'message') { - continue; - } - for (const content of output.content) { - if (content.type === 'output_text') { - texts.push(content.text); - } - } - } - rsp.output_text = texts.join(''); -} -//# sourceMappingURL=ResponsesParser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/transform.mjs -function toStrictJsonSchema(schema) { - if (schema.type !== 'object') { - throw new Error(`Root schema must have type: 'object' but got type: ${schema.type ? `'${schema.type}'` : 'undefined'}`); - } - const schemaCopy = structuredClone(schema); - return ensureStrictJsonSchema(schemaCopy, [], schemaCopy); -} -function isNullable(schema) { - if (typeof schema === 'boolean') { - return false; - } - if (schema.type === 'null') { - return true; - } - for (const oneOfVariant of schema.oneOf ?? []) { - if (isNullable(oneOfVariant)) { - return true; - } - } - for (const allOfVariant of schema.anyOf ?? []) { - if (isNullable(allOfVariant)) { - return true; - } - } - return false; -} -/** - * Mutates the given JSON schema to ensure it conforms to the `strict` standard - * that the API expects. - */ -function ensureStrictJsonSchema(jsonSchema, path, root) { - if (typeof jsonSchema === 'boolean') { - throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`); - } - if (!transform_isObject(jsonSchema)) { - throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join('/')}`); - } - // Handle $defs (non-standard but sometimes used) - const defs = jsonSchema.$defs; - if (transform_isObject(defs)) { - for (const [defName, defSchema] of Object.entries(defs)) { - ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root); - } - } - // Handle definitions (draft-04 style, deprecated in draft-07 but still used) - const definitions = jsonSchema.definitions; - if (transform_isObject(definitions)) { - for (const [definitionName, definitionSchema] of Object.entries(definitions)) { - ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root); - } - } - // Add additionalProperties: false to object types - const typ = jsonSchema.type; - if (typ === 'object' && !('additionalProperties' in jsonSchema)) { - jsonSchema.additionalProperties = false; - } - const required = jsonSchema.required ?? []; - // Handle object properties - const properties = jsonSchema.properties; - if (transform_isObject(properties)) { - for (const [key, value] of Object.entries(properties)) { - if (!isNullable(value) && !required.includes(key)) { - throw new Error(`Zod field at \`${[...path, 'properties', key].join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); - } - } - jsonSchema.required = Object.keys(properties); - jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ - key, - ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root), - ])); - } - // Handle arrays - const items = jsonSchema.items; - if (transform_isObject(items)) { - jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root); - } - // Handle unions (anyOf) - const anyOf = jsonSchema.anyOf; - if (Array.isArray(anyOf)) { - jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root)); - } - // Handle intersections (allOf) - const allOf = jsonSchema.allOf; - if (Array.isArray(allOf)) { - if (allOf.length === 1) { - const resolved = ensureStrictJsonSchema(allOf[0], [...path, 'allOf', '0'], root); - Object.assign(jsonSchema, resolved); - delete jsonSchema.allOf; - } - else { - jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root)); - } - } - // Strip `null` defaults as there's no meaningful distinction - if (jsonSchema.default === null) { - delete jsonSchema.default; - } - // Handle $ref with additional properties - const ref = jsonSchema.$ref; - if (ref && hasMoreThanNKeys(jsonSchema, 1)) { - if (typeof ref !== 'string') { - throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join('/')}`); - } - const resolved = resolveRef(root, ref); - if (typeof resolved === 'boolean') { - throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object schema but got boolean`); - } - if (!transform_isObject(resolved)) { - throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object but got ${JSON.stringify(resolved)}`); - } - // Properties from the json schema take priority over the ones on the `$ref` - Object.assign(jsonSchema, { ...resolved, ...jsonSchema }); - delete jsonSchema.$ref; - // Since the schema expanded from `$ref` might not have `additionalProperties: false` applied, - // we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid. - return ensureStrictJsonSchema(jsonSchema, path, root); - } - return jsonSchema; -} -function resolveRef(root, ref) { - if (!ref.startsWith('#/')) { - throw new Error(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`); - } - const pathParts = ref.slice(2).split('/'); - let resolved = root; - for (const key of pathParts) { - if (!transform_isObject(resolved)) { - throw new Error(`encountered non-object entry while resolving ${ref} - ${JSON.stringify(resolved)}`); - } - const value = resolved[key]; - if (value === undefined) { - throw new Error(`Key ${key} not found while resolving ${ref}`); - } - resolved = value; - } - return resolved; -} -function transform_isObject(obj) { - return typeof obj === 'object' && obj !== null && !Array.isArray(obj); -} -function hasMoreThanNKeys(obj, n) { - let i = 0; - for (const _ in obj) { - i++; - if (i > n) { - return true; - } - } - return false; -} -//# sourceMappingURL=transform.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/helpers/zod.mjs - - - - - -function zodV3ToJsonSchema(schema, options) { - return zod_to_json_schema_zodToJsonSchema_zodToJsonSchema(schema, { - openaiStrictMode: true, - name: options.name, - nameStrategy: 'duplicate-ref', - $refStrategy: 'extract-to-root', - nullableStrategy: 'property', - }); -} -function zodV4ToJsonSchema(schema) { - return toStrictJsonSchema(toJSONSchema(schema, { - target: 'draft-7', - })); -} -function isZodV4(zodObject) { - return '_zod' in zodObject; -} -/** - * Creates a chat completion `JSONSchema` response format object from - * the given Zod schema. - * - * If this is passed to the `.parse()`, `.stream()` or `.runTools()` - * chat completion methods then the response message will contain a - * `.parsed` property that is the result of parsing the content with - * the given Zod object. - * - * ```ts - * const completion = await client.chat.completions.parse({ - * model: 'gpt-4o-2024-08-06', - * messages: [ - * { role: 'system', content: 'You are a helpful math tutor.' }, - * { role: 'user', content: 'solve 8x + 31 = 2' }, - * ], - * response_format: zodResponseFormat( - * z.object({ - * steps: z.array(z.object({ - * explanation: z.string(), - * answer: z.string(), - * })), - * final_answer: z.string(), - * }), - * 'math_answer', - * ), - * }); - * const message = completion.choices[0]?.message; - * if (message?.parsed) { - * console.log(message.parsed); - * console.log(message.parsed.final_answer); - * } - * ``` - * - * This can be passed directly to the `.create()` method but will not - * result in any automatic parsing, you'll have to parse the response yourself. - */ -function zodResponseFormat(zodObject, name, props) { - return makeParseableResponseFormat({ - type: 'json_schema', - json_schema: { - ...props, - name, - strict: true, - schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }), - }, - }, (content) => zodObject.parse(JSON.parse(content))); -} -function zodTextFormat(zodObject, name, props) { - return makeParseableTextFormat({ - type: 'json_schema', - ...props, - name, - strict: true, - schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }), - }, (content) => zodObject.parse(JSON.parse(content))); -} -/** - * Creates a chat completion `function` tool that can be invoked - * automatically by the chat completion `.runTools()` method or automatically - * parsed by `.parse()` / `.stream()`. - */ -function zodFunction(options) { - // @ts-expect-error TODO - return makeParseableTool({ - type: 'function', - function: { - name: options.name, - parameters: isZodV4(options.parameters) ? - zodV4ToJsonSchema(options.parameters) - : zodV3ToJsonSchema(options.parameters, { name: options.name }), - strict: true, - ...(options.description ? { description: options.description } : undefined), - }, - }, { - callback: options.function, - parser: (args) => options.parameters.parse(JSON.parse(args)), - }); -} -function zodResponsesFunction(options) { - return makeParseableResponseTool({ - type: 'function', - name: options.name, - parameters: isZodV4(options.parameters) ? - zodV4ToJsonSchema(options.parameters) - : zodV3ToJsonSchema(options.parameters, { name: options.name }), - strict: true, - ...(options.description ? { description: options.description } : undefined), - }, { - callback: options.function, - parser: (args) => options.parameters.parse(JSON.parse(args)), - }); -} -//# sourceMappingURL=zod.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/output.js - - - - -//#region src/utils/output.ts -const SUPPORTED_METHODS = [ - "jsonSchema", - "functionCalling", - "jsonMode" -]; -/** -* Get the structured output method for a given model. By default, it uses -* `jsonSchema` if the model supports it, otherwise it uses `functionCalling`. -* -* @throws if the method is invalid, e.g. is not a string or invalid method is provided. -* @param model - The model name. -* @param config - The structured output method options. -* @returns The structured output method. -*/ -function getStructuredOutputMethod(model, method) { - /** - * If a method is provided, validate it. - */ - if (typeof method !== "undefined" && !SUPPORTED_METHODS.includes(method)) throw new Error(`Invalid method: ${method}. Supported methods are: ${SUPPORTED_METHODS.join(", ")}`); - const hasSupportForJsonSchema = !model.startsWith("gpt-3") && !model.startsWith("gpt-4-") && model !== "gpt-4"; - /** - * If the model supports JSON Schema, use it by default. - */ - if (hasSupportForJsonSchema && !method) return "jsonSchema"; - if (!hasSupportForJsonSchema && method === "jsonSchema") throw new Error(`JSON Schema is not supported for model "${model}". Please use a different method, e.g. "functionCalling" or "jsonMode".`); - /** - * If the model does not support JSON Schema, use function calling by default. - */ - return method ?? "functionCalling"; -} -function output_makeParseableResponseFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: "auto-parseable-response-format", - enumerable: false - }, - $parseRaw: { - value: parser, - enumerable: false - } - }); - return obj; -} -function interopZodResponseFormat(zodSchema, name, props) { - if (isZodSchemaV3(zodSchema)) return zodResponseFormat(zodSchema, name, props); - if (isZodSchemaV4(zodSchema)) return output_makeParseableResponseFormat({ - type: "json_schema", - json_schema: { - ...props, - name, - strict: true, - schema: toJSONSchema(zodSchema, { - cycles: "ref", - reused: "ref", - override(ctx) { - ctx.jsonSchema.title = name; - } - }) - } - }, (content) => parse_parse(zodSchema, JSON.parse(content))); - throw new Error("Unsupported schema response format"); -} -/** -* Handle multi modal response content. -* -* @param content The content of the message. -* @param messages The messages of the response. -* @returns The new content of the message. -*/ -function handleMultiModalOutput(content, messages) { - /** - * Handle OpenRouter image responses - * @see https://openrouter.ai/docs/features/multimodal/image-generation#api-usage - */ - if (messages && typeof messages === "object" && "images" in messages && Array.isArray(messages.images)) { - const images = messages.images.filter((image) => typeof image?.image_url?.url === "string").map((image) => ({ - type: "image", - url: image.image_url.url - })); - return [{ - type: "text", - text: content - }, ...images]; - } - return content; -} -function _convertOpenAIResponsesUsageToLangChainUsage(usage) { - const inputTokenDetails = { ...usage?.input_tokens_details?.cached_tokens != null && { cache_read: usage?.input_tokens_details?.cached_tokens } }; - const outputTokenDetails = { ...usage?.output_tokens_details?.reasoning_tokens != null && { reasoning: usage?.output_tokens_details?.reasoning_tokens } }; - return { - input_tokens: usage?.input_tokens ?? 0, - output_tokens: usage?.output_tokens ?? 0, - total_tokens: usage?.total_tokens ?? 0, - input_token_details: inputTokenDetails, - output_token_details: outputTokenDetails - }; -} - -//#endregion - -//# sourceMappingURL=output.js.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/tslib.mjs -function tslib_classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; -} -function tslib_classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - - -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/uuid.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * https://stackoverflow.com/a/2117523 - */ -let uuid_uuid4 = function () { - const { crypto } = globalThis; - if (crypto?.randomUUID) { - uuid_uuid4 = crypto.randomUUID.bind(crypto); - return crypto.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; - return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); -}; -//# sourceMappingURL=uuid.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/values.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -// https://url.spec.whatwg.org/#url-scheme-string -const values_startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const values_isAbsoluteURL = (url) => { - return values_startsWithSchemeRegexp.test(url); -}; -let utils_values_isArray = (val) => ((utils_values_isArray = Array.isArray), utils_values_isArray(val)); -let values_isReadonlyArray = utils_values_isArray; -/** Returns an object if the given value isn't an object, otherwise returns as-is */ -function values_maybeObj(x) { - if (typeof x !== 'object') { - return {}; - } - return x ?? {}; -} -// https://stackoverflow.com/a/34491287 -function values_isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function values_hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function values_isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); -} -const values_ensurePresent = (value) => { - if (value == null) { - throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); - } - return value; -}; -const values_validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_OpenAIError(`${name} must be an integer`); - } - if (n < 0) { - throw new error_OpenAIError(`${name} must be a positive integer`); - } - return n; -}; -const values_coerceInteger = (value) => { - if (typeof value === 'number') - return Math.round(value); - if (typeof value === 'string') - return parseInt(value, 10); - throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const values_coerceFloat = (value) => { - if (typeof value === 'number') - return value; - if (typeof value === 'string') - return parseFloat(value); - throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const values_coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const values_maybeCoerceInteger = (value) => { - if (value == null) { - return undefined; - } - return values_coerceInteger(value); -}; -const values_maybeCoerceFloat = (value) => { - if (value == null) { - return undefined; - } - return values_coerceFloat(value); -}; -const values_maybeCoerceBoolean = (value) => { - if (value == null) { - return undefined; - } - return values_coerceBoolean(value); -}; -const values_safeJSON = (text) => { - try { - return JSON.parse(text); - } - catch (err) { - return undefined; - } -}; -//# sourceMappingURL=values.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/sleep.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -//# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/version.mjs -const version_VERSION = '6.8.1'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/detect-platform.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const detect_platform_isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined'); -}; -/** - * Note this does not detect 'browser'; for that, use getBrowserInfo(). - */ -function detect_platform_getDetectedPlatform() { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return 'deno'; - } - if (typeof EdgeRuntime !== 'undefined') { - return 'edge'; - } - if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { - return 'node'; - } - return 'unknown'; -} -const detect_platform_getPlatformProperties = () => { - const detectedPlatform = detect_platform_getDetectedPlatform(); - if (detectedPlatform === 'deno') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': detect_platform_normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', - }; - } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': globalThis.process.version, - }; - } - // Check if Node.js - if (detectedPlatform === 'node') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform ?? 'unknown'), - 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch ?? 'unknown'), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', - }; - } - const browserInfo = detect_platform_getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; - } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function detect_platform_getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; - } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } - } - return null; -} -const detect_platform_normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') - return 'x32'; - if (arch === 'x86_64' || arch === 'x64') - return 'x64'; - if (arch === 'arm') - return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') - return 'arm64'; - if (arch) - return `other:${arch}`; - return 'unknown'; -}; -const detect_platform_normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) - return 'iOS'; - if (platform === 'android') - return 'Android'; - if (platform === 'darwin') - return 'MacOS'; - if (platform === 'win32') - return 'Windows'; - if (platform === 'freebsd') - return 'FreeBSD'; - if (platform === 'openbsd') - return 'OpenBSD'; - if (platform === 'linux') - return 'Linux'; - if (platform) - return `Other:${platform}`; - return 'Unknown'; -}; -let detect_platform_platformHeaders; -const detect_platform_getPlatformHeaders = () => { - return (detect_platform_platformHeaders ?? (detect_platform_platformHeaders = detect_platform_getPlatformProperties())); -}; -//# sourceMappingURL=detect-platform.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/shims.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function shims_getDefaultFetch() { - if (typeof fetch !== 'undefined') { - return fetch; - } - throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); -} -function shims_makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === 'undefined') { - // Note: All of the platforms / runtimes we officially support already define - // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); - } - return new ReadableStream(...args); -} -function shims_ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return shims_makeReadableStream({ - start() { }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } - else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - }, - }); -} -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function shims_ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; -} -/** - * Cancels a ReadableStream we don't need to consume. - * See https://undici.nodejs.org/#/?id=garbage-collection - */ -async function shims_CancelReadableStream(stream) { - if (stream === null || typeof stream !== 'object') - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} -//# sourceMappingURL=shims.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/request-options.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const request_options_FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - 'content-type': 'application/json', - }, - body: JSON.stringify(body), - }; -}; -//# sourceMappingURL=request-options.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs -const default_format = 'RFC3986'; -const default_formatter = (v) => String(v); -const formatters = { - RFC1738: (v) => String(v).replace(/%20/g, '+'), - RFC3986: default_formatter, -}; -const RFC1738 = 'RFC1738'; -const RFC3986 = 'RFC3986'; -//# sourceMappingURL=formats.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs - - -let has = (obj, key) => ((has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)), - has(obj, key)); -const hex_table = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } - return array; -})(); -function compact_queue(queue) { - while (queue.length > 1) { - const item = queue.pop(); - if (!item) - continue; - const obj = item.obj[item.prop]; - if (isArray(obj)) { - const compacted = []; - for (let j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } - } - // @ts-ignore - item.obj[item.prop] = compacted; - } - } -} -function array_to_object(source, options) { - const obj = options && options.plainObjects ? Object.create(null) : {}; - for (let i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } - return obj; -} -function utils_merge(target, source, options = {}) { - if (!source) { - return target; - } - if (typeof source !== 'object') { - if (isArray(target)) { - target.push(source); - } - else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { - target[source] = true; - } - } - else { - return [target, source]; - } - return target; - } - if (!target || typeof target !== 'object') { - return [target].concat(source); - } - let mergeTarget = target; - if (isArray(target) && !isArray(source)) { - // @ts-ignore - mergeTarget = array_to_object(target, options); - } - if (isArray(target) && isArray(source)) { - source.forEach(function (item, i) { - if (has(target, i)) { - const targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = utils_merge(targetItem, item, options); - } - else { - target.push(item); - } - } - else { - target[i] = item; - } - }); - return target; - } - return Object.keys(source).reduce(function (acc, key) { - const value = source[key]; - if (has(acc, key)) { - acc[key] = utils_merge(acc[key], value, options); - } - else { - acc[key] = value; - } - return acc; - }, mergeTarget); -} -function assign_single_source(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -} -function decode(str, _, charset) { - const strWithoutPlus = str.replace(/\+/g, ' '); - if (charset === 'iso-8859-1') { - // unescape never throws, no try...catch needed: - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - // utf-8 - try { - return decodeURIComponent(strWithoutPlus); - } - catch (e) { - return strWithoutPlus; - } -} -const limit = 1024; -const encode = (str, _defaultEncoder, charset, _kind, format) => { - // This code was originally written by Brian White for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === 'symbol') { - string = Symbol.prototype.toString.call(str); - } - else if (typeof str !== 'string') { - string = String(str); - } - if (charset === 'iso-8859-1') { - return escape(string).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 += limit) { - const segment = string.length >= limit ? string.slice(j, j + limit) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 0x2d || // - - c === 0x2e || // . - c === 0x5f || // _ - c === 0x7e || // ~ - (c >= 0x30 && c <= 0x39) || // 0-9 - (c >= 0x41 && c <= 0x5a) || // a-z - (c >= 0x61 && c <= 0x7a) || // A-Z - (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) - ) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 0x80) { - arr[arr.length] = hex_table[c]; - continue; - } - if (c < 0x800) { - arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - if (c < 0xd800 || c >= 0xe000) { - arr[arr.length] = - hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - i += 1; - c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); - arr[arr.length] = - hex_table[0xf0 | (c >> 18)] + - hex_table[0x80 | ((c >> 12) & 0x3f)] + - hex_table[0x80 | ((c >> 6) & 0x3f)] + - hex_table[0x80 | (c & 0x3f)]; - } - out += arr.join(''); - } - return out; -}; -function compact(value) { - const queue = [{ obj: { o: value }, prop: 'o' }]; - const refs = []; - for (let i = 0; i < queue.length; ++i) { - const item = queue[i]; - // @ts-ignore - const obj = item.obj[item.prop]; - const keys = Object.keys(obj); - for (let j = 0; j < keys.length; ++j) { - const key = keys[j]; - const val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } - } - } - compact_queue(queue); - return value; -} -function is_regexp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -} -function is_buffer(obj) { - if (!obj || typeof obj !== 'object') { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} -function combine(a, b) { - return [].concat(a, b); -} -function maybe_map(val, fn) { - if (utils_values_isArray(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; - } - return fn(val); -} -//# sourceMappingURL=utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs - - - -const array_prefix_generators = { - brackets(prefix) { - return String(prefix) + '[]'; - }, - comma: 'comma', - indices(prefix, key) { - return String(prefix) + '[' + key + ']'; - }, - repeat(prefix) { - return String(prefix); - }, -}; -const push_to_array = function (arr, value_or_array) { - Array.prototype.push.apply(arr, utils_values_isArray(value_or_array) ? value_or_array : [value_or_array]); -}; -let toISOString; -const defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: 'indices', - charset: 'utf-8', - charsetSentinel: false, - delimiter: '&', - encode: true, - encodeDotInKeys: false, - encoder: encode, - encodeValuesOnly: false, - format: default_format, - formatter: default_formatter, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false, -}; -function is_non_nullish_primitive(v) { - return (typeof v === 'string' || - typeof v === 'number' || - typeof v === 'boolean' || - typeof v === 'symbol' || - typeof v === 'bigint'); -} -const sentinel = {}; -function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { - // Where object last appeared in the ref tree - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== 'undefined') { - if (pos === step) { - throw new RangeError('Cyclic object value'); - } - else { - find_flag = true; // Break while - } - } - if (typeof tmp_sc.get(sentinel) === 'undefined') { - step = 0; - } - } - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } - else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } - else if (generateArrayPrefix === 'comma' && utils_values_isArray(obj)) { - obj = maybe_map(obj, function (value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? - // @ts-expect-error - encoder(prefix, defaults.encoder, charset, 'key', format) - : prefix; - } - obj = ''; - } - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix - // @ts-expect-error - : encoder(prefix, defaults.encoder, charset, 'key', format); - return [ - formatter?.(key_value) + - '=' + - // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), - ]; - } - return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === 'undefined') { - return values; - } - let obj_keys; - if (generateArrayPrefix === 'comma' && utils_values_isArray(obj)) { - // we need to join elements in - if (encodeValuesOnly && encoder) { - // @ts-expect-error values only - obj = maybe_map(obj, encoder); - } - obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; - } - else if (utils_values_isArray(filter)) { - obj_keys = filter; - } - else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); - const adjusted_prefix = commaRoundTrip && utils_values_isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; - if (allowEmptyArrays && utils_values_isArray(obj) && obj.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]; - if (skipNulls && value === null) { - continue; - } - // @ts-ignore - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; - const key_prefix = utils_values_isArray(obj) ? - typeof generateArrayPrefix === 'function' ? - generateArrayPrefix(adjusted_prefix, encoded_key) - : adjusted_prefix - : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); - sideChannel.set(object, step); - const valueSideChannel = new WeakMap(); - valueSideChannel.set(sentinel, sideChannel); - push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === 'comma' && encodeValuesOnly && utils_values_isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); - } - return values; -} -function normalize_stringify_options(opts = defaults) { - if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { - throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); - } - if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { - throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); - } - if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); - } - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); - } - let format = default_format; - if (typeof opts.format !== 'undefined') { - if (!has(formatters, opts.format)) { - throw new TypeError('Unknown format option provided.'); - } - format = opts.format; - } - const formatter = formatters[format]; - let filter = defaults.filter; - if (typeof opts.filter === 'function' || utils_values_isArray(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } - else if ('indices' in opts) { - arrayFormat = opts.indices ? 'indices' : 'repeat'; - } - else { - arrayFormat = defaults.arrayFormat; - } - if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { - throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); - } - const allowDots = typeof opts.allowDots === 'undefined' ? - !!opts.encodeDotInKeys === true ? - true - : defaults.allowDots - : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots: allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat: arrayFormat, - charset: charset, - charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter: filter, - format: format, - formatter: formatter, - serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === 'function' ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, - }; -} -function stringify_stringify(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - let obj_keys; - let filter; - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } - else if (utils_values_isArray(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== 'object' || obj === null) { - return ''; - } - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array(keys, inner_stringify(obj[key], key, - // @ts-expect-error - generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? '?' : ''; - if (options.charsetSentinel) { - if (options.charset === 'iso-8859-1') { - // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark - prefix += 'utf8=%26%2310003%3B&'; - } - else { - // encodeURIComponent('✓') - prefix += 'utf8=%E2%9C%93&'; - } - } - return joined.length > 0 ? prefix + joined : ''; -} -//# sourceMappingURL=stringify.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/index.mjs - -const formats = { - formatters: formatters, - RFC1738: RFC1738, - RFC3986: RFC3986, - default: default_format, -}; - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/bytes.mjs -function bytes_concatBytes(buffers) { - let length = 0; - for (const buffer of buffers) { - length += buffer.length; - } - const output = new Uint8Array(length); - let index = 0; - for (const buffer of buffers) { - output.set(buffer, index); - index += buffer.length; - } - return output; -} -let bytes_encodeUTF8_; -function utils_bytes_encodeUTF8(str) { - let encoder; - return (bytes_encodeUTF8_ ?? - ((encoder = new globalThis.TextEncoder()), (bytes_encodeUTF8_ = encoder.encode.bind(encoder))))(str); -} -let bytes_decodeUTF8_; -function bytes_decodeUTF8(bytes) { - let decoder; - return (bytes_decodeUTF8_ ?? - ((decoder = new globalThis.TextDecoder()), (bytes_decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); -} -//# sourceMappingURL=bytes.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/decoders/line.mjs -var line_LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; - - -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class line_LineDecoder { - constructor() { - line_LineDecoder_buffer.set(this, void 0); - line_LineDecoder_carriageReturnIndex.set(this, void 0); - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, new Uint8Array(), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); - } - decode(chunk) { - if (chunk == null) { - return []; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) - : chunk; - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, bytes_concatBytes([tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), binaryChunk]), "f"); - const lines = []; - let patternIndex; - while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") == null) { - // skip until we either get a corresponding `\n`, a new `\r` or nothing - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; - } - // we got double \r or \rtext\n - if (tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); - continue; - } - const endIndex = tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, endIndex)); - lines.push(line); - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); - } - return lines; - } - flush() { - if (!tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").length) { - return []; - } - return this.decode('\n'); - } -} -line_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); -// prettier-ignore -line_LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); -line_LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; -/** - * This function searches the buffer for the end patterns, (\r or \n) - * and returns an object with the index preceding the matched newline and the - * index after the newline char. `null` is returned if no new line is found. - * - * ```ts - * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } - * ``` - */ -function line_findNewlineIndex(buffer, startIndex) { - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = startIndex ?? 0; i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; - } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; -} -function line_findDoubleNewlineIndex(buffer) { - // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) - // and returns the index right after the first occurrence of any pattern, - // or -1 if none of the patterns are found. - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - // \n\n - return i + 2; - } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - // \r\r - return i + 2; - } - if (buffer[i] === carriage && - buffer[i + 1] === newline && - i + 3 < buffer.length && - buffer[i + 2] === carriage && - buffer[i + 3] === newline) { - // \r\n\r\n - return i + 4; - } - } - return -1; -} -//# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const log_levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const log_parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; - } - if (values_hasOwn(log_levelNumbers, maybeLevel)) { - return maybeLevel; - } - log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); - return undefined; -}; -function log_noop() { } -function log_makeLogFn(fnLevel, logger, logLevel) { - if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { - return log_noop; - } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); - } -} -const log_noopLogger = { - error: log_noop, - warn: log_noop, - info: log_noop, - debug: log_noop, -}; -let log_cachedLoggers = /* @__PURE__ */ new WeakMap(); -function log_loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return log_noopLogger; - } - const cachedLogger = log_cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: log_makeLogFn('error', logger, logLevel), - warn: log_makeLogFn('warn', logger, logLevel), - info: log_makeLogFn('info', logger, logLevel), - debug: log_makeLogFn('debug', logger, logLevel), - }; - log_cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -const log_formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); - } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; - } - delete details.retryOfRequestLogID; - } - return details; -}; -//# sourceMappingURL=log.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/streaming.mjs -var streaming_Stream_client; - - - - - - - - - -class streaming_Stream { - constructor(iterator, controller, client) { - this.iterator = iterator; - streaming_Stream_client.set(this, void 0); - this.controller = controller; - tslib_classPrivateFieldSet(this, streaming_Stream_client, client, "f"); - } - static fromSSEResponse(response, controller, client) { - let consumed = false; - const logger = client ? log_loggerFor(client) : console; - async function* iterator() { - if (consumed) { - throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of streaming_iterSSEMessages(response, controller)) { - if (done) - continue; - if (sse.data.startsWith('[DONE]')) { - done = true; - continue; - } - if (sse.event === null || !sse.event.startsWith('thread.')) { - let data; - try { - data = JSON.parse(sse.data); - } - catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - if (data && data.error) { - throw new error_APIError(undefined, data.error, undefined, response.headers); - } - yield data; - } - else { - let data; - try { - data = JSON.parse(sse.data); - } - catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } - // TODO: Is this where the error should be thrown? - if (sse.event == 'error') { - throw new error_APIError(undefined, data.error, data.message, undefined); - } - yield { event: sse.event, data: data }; - } - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (errors_isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new streaming_Stream(iterator, controller, client); - } - /** - * Generates a Stream from a newline-separated ReadableStream - * where each item is a JSON value. - */ - static fromReadableStream(readableStream, controller, client) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new line_LineDecoder(); - const iter = shims_ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } - } - async function* iterator() { - if (consumed) { - throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (errors_isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new streaming_Stream(iterator, controller, client); - } - [(streaming_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { - return this.iterator(); - } - /** - * Splits the stream into two streams which can be - * independently read from at different speeds. - */ - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue) => { - return { - next: () => { - if (queue.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue.shift(); - }, - }; - }; - return [ - new streaming_Stream(() => teeIterator(left), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), - new streaming_Stream(() => teeIterator(right), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), - ]; - } - /** - * Converts this stream to a newline-separated ReadableStream of - * JSON stringified values in the stream - * which can be turned back into a Stream with `Stream.fromReadableStream()`. - */ - toReadableStream() { - const self = this; - let iter; - return shims_makeReadableStream({ - async start() { - iter = self[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = utils_bytes_encodeUTF8(JSON.stringify(value) + '\n'); - ctrl.enqueue(bytes); - } - catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - }, - }); - } -} -async function* streaming_iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_OpenAIError(`Attempted to iterate over a response with no body`); - } - const sseDecoder = new streaming_SSEDecoder(); - const lineDecoder = new line_LineDecoder(); - const iter = shims_ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of streaming_iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -/** - * Given an async iterable iterator, iterates over it and yields full - * SSE chunks, i.e. yields when a double new-line is encountered. - */ -async function* streaming_iterSSEChunks(iterator) { - let data = new Uint8Array(); - for await (const chunk of iterator) { - if (chunk == null) { - continue; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) - : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = line_findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); - } - } - if (data.length > 0) { - yield data; - } -} -class streaming_SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = streaming_partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } -} -function streaming_partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; - } - return [str, '', '']; -} -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/parse.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -async function parse_defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (props.options.stream) { - log_loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller, client); - } - return streaming_Stream.fromSSEResponse(response, props.controller, client); - } - // fetch refuses to read the body when the status code is 204. - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get('content-type'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - return parse_addRequestID(json, response); - } - const text = await response.text(); - return text; - })(); - log_loggerFor(client).debug(`[${requestLogID}] response parsed`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime, - })); - return body; -} -function parse_addRequestID(value, response) { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return value; - } - return Object.defineProperty(value, '_request_id', { - value: response.headers.get('x-request-id'), - enumerable: false, - }); -} -//# sourceMappingURL=parse.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/api-promise.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var api_promise_APIPromise_client; - - -/** - * A subclass of `Promise` providing additional helper methods - * for interacting with the SDK. - */ -class api_promise_APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = parse_defaultParseResponse) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - api_promise_APIPromise_client.set(this, void 0); - tslib_classPrivateFieldSet(this, api_promise_APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), this.responsePromise, async (client, props) => parse_addRequestID(transform(await this.parseResponse(client, props), props), props.response)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data, the raw `Response` instance and the ID of the request, - * returned via the X-Request-ID header which is useful for debugging requests and reporting - * issues to OpenAI. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response, request_id: response.headers.get('x-request-id') }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), data)); - } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); - } -} -api_promise_APIPromise_client = new WeakMap(); -//# sourceMappingURL=api-promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var pagination_AbstractPage_client; - - - - - -class pagination_AbstractPage { - constructor(client, response, body, options) { - pagination_AbstractPage_client.set(this, void 0); - tslib_classPrivateFieldSet(this, pagination_AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new error_OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); - } - return await tslib_classPrivateFieldGet(this, pagination_AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; - } - } - async *[(pagination_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } - } - } -} -/** - * This subclass of Promise will resolve to an instantiated Page once the request completes. - * - * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ -class pagination_PagePromise extends api_promise_APIPromise { - constructor(client, request, Page) { - super(client, request, async (client, props) => new Page(client, props.response, await parse_defaultParseResponse(client, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; - } - } -} -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class pagination_Page extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.object = body.object; - } - getPaginatedItems() { - return this.data ?? []; - } - nextPageRequestOptions() { - return null; - } -} -class CursorPage extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - const data = this.getPaginatedItems(); - const id = data[data.length - 1]?.id; - if (!id) { - return null; - } - return { - ...this.options, - query: { - ...values_maybeObj(this.options.query), - after: id, - }, - }; - } -} -class ConversationCursorPage extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.last_id = body.last_id || ''; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - const cursor = this.last_id; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...values_maybeObj(this.options.query), - after: cursor, - }, - }; - } -} -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/uploads.mjs - -const uploads_checkFileSupport = () => { - if (typeof File === 'undefined') { - const { process } = globalThis; - const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; - throw new Error('`File` is not defined as a global, which is required for file uploads.' + - (isOldNode ? - " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." - : '')); - } -}; -/** - * Construct a `File` instance. This is used to ensure a helpful error is thrown - * for environments that don't define a global `File` yet. - */ -function uploads_makeFile(fileBits, fileName, options) { - uploads_checkFileSupport(); - return new File(fileBits, fileName ?? 'unknown_file', options); -} -function uploads_getName(value) { - return (((typeof value === 'object' && - value !== null && - (('name' in value && value.name && String(value.name)) || - ('url' in value && value.url && String(value.url)) || - ('filename' in value && value.filename && String(value.filename)) || - ('path' in value && value.path && String(value.path)))) || - '') - .split(/[\\/]/) - .pop() || undefined); -} -const internal_uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { - if (!uploads_hasUploadableValue(opts.body)) - return opts; - return { ...opts, body: await uploads_createForm(opts.body, fetch) }; -}; -const uploads_multipartFormRequestOptions = async (opts, fetch) => { - return { ...opts, body: await uploads_createForm(opts.body, fetch) }; -}; -const uploads_supportsFormDataMap = /* @__PURE__ */ new WeakMap(); -/** - * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending - * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". - * This function detects if the fetch function provided supports the global FormData object to avoid - * confusing error messages later on. - */ -function uploads_supportsFormData(fetchObject) { - const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; - const cached = uploads_supportsFormDataMap.get(fetch); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = ('Response' in fetch ? - fetch.Response - : (await fetch('data:,')).constructor); - const data = new FormData(); - if (data.toString() === (await new FetchResponse(data).text())) { - return false; - } - return true; - } - catch { - // avoid false negatives - return true; - } - })(); - uploads_supportsFormDataMap.set(fetch, promise); - return promise; -} -const uploads_createForm = async (body, fetch) => { - if (!(await uploads_supportsFormData(fetch))) { - throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); - } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => uploads_addFormValue(form, key, value))); - return form; -}; -// We check for Blob not File because Bun.File doesn't inherit from File, -// but they both inherit from Blob and have a `name` property at runtime. -const uploads_isNamedBlob = (value) => value instanceof Blob && 'name' in value; -const uploads_isUploadable = (value) => typeof value === 'object' && - value !== null && - (value instanceof Response || internal_uploads_isAsyncIterable(value) || uploads_isNamedBlob(value)); -const uploads_hasUploadableValue = (value) => { - if (uploads_isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(uploads_hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (uploads_hasUploadableValue(value[k])) - return true; - } - } - return false; -}; -const uploads_addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (value instanceof Response) { - form.append(key, uploads_makeFile([await value.blob()], uploads_getName(value))); - } - else if (internal_uploads_isAsyncIterable(value)) { - form.append(key, uploads_makeFile([await new Response(shims_ReadableStreamFrom(value)).blob()], uploads_getName(value))); - } - else if (uploads_isNamedBlob(value)) { - form.append(key, value, uploads_getName(value)); - } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); - } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => uploads_addFormValue(form, `${key}[${name}]`, prop))); - } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/to-file.mjs - - -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const to_file_isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const to_file_isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - to_file_isBlobLike(value); -const to_file_isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function to_file_toFile(value, name, options) { - uploads_checkFileSupport(); - // If it's a promise, resolve it. - value = await value; - // If we've been given a `File` we don't need to do anything - if (to_file_isFileLike(value)) { - if (value instanceof File) { - return value; - } - return uploads_makeFile([await value.arrayBuffer()], value.name); - } - if (to_file_isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return uploads_makeFile(await internal_to_file_getBytes(blob), name, options); - } - const parts = await internal_to_file_getBytes(value); - name || (name = uploads_getName(value)); - if (!options?.type) { - const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return uploads_makeFile(parts, name, options); -} -async function internal_to_file_getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (to_file_isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } - else if (internal_uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(...(await internal_to_file_getBytes(chunk))); // TODO, consider validating? - } - } - else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${to_file_propsForError(value)}`); - } - return parts; -} -function to_file_propsForError(value) { - if (typeof value !== 'object' || value === null) - return ''; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; -} -//# sourceMappingURL=to-file.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/uploads.mjs - -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/resource.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class resource_APIResource { - constructor(client) { - this._client = client; - } -} -//# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/path.mjs - -/** - * Percent-encode everything that isn't safe to have in a path without encoding safe chars. - * - * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: - * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ -function path_encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -const path_EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => function path(statics, ...params) { - // If there are no params, no processing is needed. - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); - if (index !== params.length && - (value == null || - (typeof value === 'object' && - // handle values from other realms - value.toString === - Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? path_EMPTY) ?? path_EMPTY) - ?.toString))) { - encoded = value + ''; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString - .call(value) - .slice(8, -1)} is not a valid path parameter`, - }); - } - return previousValue + currentValue + (index === params.length ? '' : encoded); - }, ''); - const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - // Find all invalid segments - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = ' '.repeat(segment.start - lastEnd); - const arrows = '^'.repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ''); - throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${invalidSegments - .map((e) => e.error) - .join('\n')}\n${path}\n${underline}`); - } - return path; -}; -/** - * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. - */ -const path_path = /* @__PURE__ */ path_createPathTagFunction(path_encodeURIPath); -//# sourceMappingURL=path.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class completions_messages_Messages extends resource_APIResource { - /** - * Get the messages in a stored chat completion. Only Chat Completions that have - * been created with the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( - * 'completion_id', - * )) { - * // ... - * } - * ``` - */ - list(completionID, query = {}, options) { - return this._client.getAPIList(path_path `/chat/completions/${completionID}/messages`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/chatCompletionUtils.mjs -const isAssistantMessage = (message) => { - return message?.role === 'assistant'; -}; -const chatCompletionUtils_isToolMessage = (message) => { - return message?.role === 'tool'; -}; -function isPresent(obj) { - return obj != null; -} -//# sourceMappingURL=chatCompletionUtils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/EventStream.mjs -var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; - - -class EventStream { - constructor() { - _EventStream_instances.add(this); - this.controller = new AbortController(); - _EventStream_connectedPromise.set(this, void 0); - _EventStream_resolveConnectedPromise.set(this, () => { }); - _EventStream_rejectConnectedPromise.set(this, () => { }); - _EventStream_endPromise.set(this, void 0); - _EventStream_resolveEndPromise.set(this, () => { }); - _EventStream_rejectEndPromise.set(this, () => { }); - _EventStream_listeners.set(this, {}); - _EventStream_ended.set(this, false); - _EventStream_errored.set(this, false); - _EventStream_aborted.set(this, false); - _EventStream_catchingPromiseCreated.set(this, false); - tslib_classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); - }), "f"); - tslib_classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - tslib_classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); - tslib_classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); - } - _run(executor) { - // Unfortunately if we call `executor()` immediately we get runtime errors about - // references to `this` before the `super()` constructor call returns. - setTimeout(() => { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, tslib_classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); - }, 0); - } - _connected() { - if (this.ended) - return; - tslib_classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); - this._emit('connect'); - } - get ended() { - return tslib_classPrivateFieldGet(this, _EventStream_ended, "f"); - } - get errored() { - return tslib_classPrivateFieldGet(this, _EventStream_errored, "f"); - } - get aborted() { - return tslib_classPrivateFieldGet(this, _EventStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this ChatCompletionStream, so that calls can be chained - */ - on(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this ChatCompletionStream, so that calls can be chained - */ - off(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this ChatCompletionStream, so that calls can be chained - */ - once(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); - } - async done() { - tslib_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - await tslib_classPrivateFieldGet(this, _EventStream_endPromise, "f"); - } - _emit(event, ...args) { - // make sure we don't emit any events after end - if (tslib_classPrivateFieldGet(this, _EventStream_ended, "f")) { - return; - } - if (event === 'end') { - tslib_classPrivateFieldSet(this, _EventStream_ended, true, "f"); - tslib_classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); - } - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; - if (listeners) { - tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - tslib_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.finalChatCompletion() - // - etc. - Promise.reject(error); - } - tslib_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } - } - _emitFinal() { } -} -_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { - tslib_classPrivateFieldSet(this, _EventStream_errored, true, "f"); - if (error instanceof Error && error.name === 'AbortError') { - error = new error_APIUserAbortError(); - } - if (error instanceof error_APIUserAbortError) { - tslib_classPrivateFieldSet(this, _EventStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_OpenAIError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const openAIError = new error_OpenAIError(error.message); - // @ts-ignore - openAIError.cause = error; - return this._emit('error', openAIError); - } - return this._emit('error', new error_OpenAIError(String(error))); -}; -//# sourceMappingURL=EventStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs -function isRunnableFunctionWithParse(fn) { - return typeof fn.parse === 'function'; -} -/** - * This is helper class for passing a `function` and `parse` where the `function` - * argument type matches the `parse` return type. - */ -class ParsingToolFunction { - constructor(input) { - this.type = 'function'; - this.function = input; - } -} -//# sourceMappingURL=RunnableFunction.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs -var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; - - - - - - -const DEFAULT_MAX_CHAT_COMPLETIONS = 10; -class AbstractChatCompletionRunner extends EventStream { - constructor() { - super(...arguments); - _AbstractChatCompletionRunner_instances.add(this); - this._chatCompletions = []; - this.messages = []; - } - _addChatCompletion(chatCompletion) { - this._chatCompletions.push(chatCompletion); - this._emit('chatCompletion', chatCompletion); - const message = chatCompletion.choices[0]?.message; - if (message) - this._addMessage(message); - return chatCompletion; - } - _addMessage(message, emit = true) { - if (!('content' in message)) - message.content = null; - this.messages.push(message); - if (emit) { - this._emit('message', message); - if (chatCompletionUtils_isToolMessage(message) && message.content) { - // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. - this._emit('functionToolCallResult', message.content); - } - else if (isAssistantMessage(message) && message.tool_calls) { - for (const tool_call of message.tool_calls) { - if (tool_call.type === 'function') { - this._emit('functionToolCall', tool_call.function); - } - } - } - } - } - /** - * @returns a promise that resolves with the final ChatCompletion, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletion. - */ - async finalChatCompletion() { - await this.done(); - const completion = this._chatCompletions[this._chatCompletions.length - 1]; - if (!completion) - throw new error_OpenAIError('stream ended without producing a ChatCompletion'); - return completion; - } - /** - * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalContent() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); - } - /** - * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, - * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalMessage() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the content of the final FunctionCall, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalFunctionToolCall() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); - } - async finalFunctionToolCallResult() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); - } - async totalUsage() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); - } - allChatCompletions() { - return [...this._chatCompletions]; - } - _emitFinal() { - const completion = this._chatCompletions[this._chatCompletions.length - 1]; - if (completion) - this._emit('finalChatCompletion', completion); - const finalMessage = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); - if (finalMessage) - this._emit('finalMessage', finalMessage); - const finalContent = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); - if (finalContent) - this._emit('finalContent', finalContent); - const finalFunctionCall = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); - if (finalFunctionCall) - this._emit('finalFunctionToolCall', finalFunctionCall); - const finalFunctionCallResult = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); - if (finalFunctionCallResult != null) - this._emit('finalFunctionToolCallResult', finalFunctionCallResult); - if (this._chatCompletions.some((c) => c.usage)) { - this._emit('totalUsage', tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); - } - } - async _createChatCompletion(client, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); - const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); - this._connected(); - return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); - } - async _runChatCompletion(client, params, options) { - for (const message of params.messages) { - this._addMessage(message, false); - } - return await this._createChatCompletion(client, params, options); - } - async _runTools(client, params, options) { - const role = 'tool'; - const { tool_choice = 'auto', stream, ...restParams } = params; - const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name; - const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; - // TODO(someday): clean this logic up - const inputTools = params.tools.map((tool) => { - if (isAutoParsableTool(tool)) { - if (!tool.$callback) { - throw new error_OpenAIError('Tool given to `.runTools()` that does not have an associated function'); - } - return { - type: 'function', - function: { - function: tool.$callback, - name: tool.function.name, - description: tool.function.description || '', - parameters: tool.function.parameters, - parse: tool.$parseRaw, - strict: true, - }, - }; - } - return tool; - }); - const functionsByName = {}; - for (const f of inputTools) { - if (f.type === 'function') { - functionsByName[f.function.name || f.function.function.name] = f.function; - } - } - const tools = 'tools' in params ? - inputTools.map((t) => t.type === 'function' ? - { - type: 'function', - function: { - name: t.function.name || t.function.function.name, - parameters: t.function.parameters, - description: t.function.description, - strict: t.function.strict, - }, - } - : t) - : undefined; - for (const message of params.messages) { - this._addMessage(message, false); - } - for (let i = 0; i < maxChatCompletions; ++i) { - const chatCompletion = await this._createChatCompletion(client, { - ...restParams, - tool_choice, - tools, - messages: [...this.messages], - }, options); - const message = chatCompletion.choices[0]?.message; - if (!message) { - throw new error_OpenAIError(`missing message in ChatCompletion response`); - } - if (!message.tool_calls?.length) { - return; - } - for (const tool_call of message.tool_calls) { - if (tool_call.type !== 'function') - continue; - const tool_call_id = tool_call.id; - const { name, arguments: args } = tool_call.function; - const fn = functionsByName[name]; - if (!fn) { - const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName) - .map((name) => JSON.stringify(name)) - .join(', ')}. Please try again`; - this._addMessage({ role, tool_call_id, content }); - continue; - } - else if (singleFunctionToCall && singleFunctionToCall !== name) { - const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; - this._addMessage({ role, tool_call_id, content }); - continue; - } - let parsed; - try { - parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; - } - catch (error) { - const content = error instanceof Error ? error.message : String(error); - this._addMessage({ role, tool_call_id, content }); - continue; - } - // @ts-expect-error it can't rule out `never` type. - const rawContent = await fn.function(parsed, this); - const content = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); - this._addMessage({ role, tool_call_id, content }); - if (singleFunctionToCall) { - return; - } - } - } - return; - } -} -_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; -}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { - let i = this.messages.length; - while (i-- > 0) { - const message = this.messages[i]; - if (isAssistantMessage(message)) { - // TODO: support audio here - const ret = { - ...message, - content: message.content ?? null, - refusal: message.refusal ?? null, - }; - return ret; - } - } - throw new error_OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); -}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() { - for (let i = this.messages.length - 1; i >= 0; i--) { - const message = this.messages[i]; - if (isAssistantMessage(message) && message?.tool_calls?.length) { - return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function; - } - } - return; -}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() { - for (let i = this.messages.length - 1; i >= 0; i--) { - const message = this.messages[i]; - if (chatCompletionUtils_isToolMessage(message) && - message.content != null && - typeof message.content === 'string' && - this.messages.some((x) => x.role === 'assistant' && - x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { - return message.content; - } - } - return; -}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { - const total = { - completion_tokens: 0, - prompt_tokens: 0, - total_tokens: 0, - }; - for (const { usage } of this._chatCompletions) { - if (usage) { - total.completion_tokens += usage.completion_tokens; - total.prompt_tokens += usage.prompt_tokens; - total.total_tokens += usage.total_tokens; - } - } - return total; -}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { - if (params.n != null && params.n > 1) { - throw new error_OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); - } -}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { - return (typeof rawContent === 'string' ? rawContent - : rawContent === undefined ? 'undefined' - : JSON.stringify(rawContent)); -}; -//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionRunner.mjs - - -class ChatCompletionRunner extends AbstractChatCompletionRunner { - static runTools(client, params, options) { - const runner = new ChatCompletionRunner(); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, - }; - runner._run(() => runner._runTools(client, params, opts)); - return runner; - } - _addMessage(message, emit = true) { - super._addMessage(message, emit); - if (isAssistantMessage(message) && message.content) { - this._emit('content', message.content); - } - } -} -//# sourceMappingURL=ChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs -const STR = 0b000000001; -const NUM = 0b000000010; -const ARR = 0b000000100; -const OBJ = 0b000001000; -const NULL = 0b000010000; -const BOOL = 0b000100000; -const NAN = 0b001000000; -const INFINITY = 0b010000000; -const MINUS_INFINITY = 0b100000000; -const INF = INFINITY | MINUS_INFINITY; -const SPECIAL = NULL | BOOL | INF | NAN; -const ATOM = STR | NUM | SPECIAL; -const COLLECTION = ARR | OBJ; -const ALL = ATOM | COLLECTION; -const Allow = { - STR, - NUM, - ARR, - OBJ, - NULL, - BOOL, - NAN, - INFINITY, - MINUS_INFINITY, - INF, - SPECIAL, - ATOM, - COLLECTION, - ALL, -}; -// The JSON string segment was unable to be parsed completely -class PartialJSON extends Error { -} -class MalformedJSON extends Error { -} -/** - * Parse incomplete JSON - * @param {string} jsonString Partial JSON to be parsed - * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details - * @returns The parsed JSON - * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) - * @throws {MalformedJSON} If the JSON is malformed - */ -function parseJSON(jsonString, allowPartial = Allow.ALL) { - if (typeof jsonString !== 'string') { - throw new TypeError(`expecting str, got ${typeof jsonString}`); - } - if (!jsonString.trim()) { - throw new Error(`${jsonString} is empty`); - } - return _parseJSON(jsonString.trim(), allowPartial); -} -const _parseJSON = (jsonString, allow) => { - const length = jsonString.length; - let index = 0; - const markPartialJSON = (msg) => { - throw new PartialJSON(`${msg} at position ${index}`); - }; - const throwMalformedError = (msg) => { - throw new MalformedJSON(`${msg} at position ${index}`); - }; - const parseAny = () => { - skipBlank(); - if (index >= length) - markPartialJSON('Unexpected end of input'); - if (jsonString[index] === '"') - return parseStr(); - if (jsonString[index] === '{') - return parseObj(); - if (jsonString[index] === '[') - return parseArr(); - if (jsonString.substring(index, index + 4) === 'null' || - (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { - index += 4; - return null; - } - if (jsonString.substring(index, index + 4) === 'true' || - (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { - index += 4; - return true; - } - if (jsonString.substring(index, index + 5) === 'false' || - (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { - index += 5; - return false; - } - if (jsonString.substring(index, index + 8) === 'Infinity' || - (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { - index += 8; - return Infinity; - } - if (jsonString.substring(index, index + 9) === '-Infinity' || - (Allow.MINUS_INFINITY & allow && - 1 < length - index && - length - index < 9 && - '-Infinity'.startsWith(jsonString.substring(index)))) { - index += 9; - return -Infinity; - } - if (jsonString.substring(index, index + 3) === 'NaN' || - (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { - index += 3; - return NaN; - } - return parseNum(); - }; - const parseStr = () => { - const start = index; - let escape = false; - index++; // skip initial quote - while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { - escape = jsonString[index] === '\\' ? !escape : false; - index++; - } - if (jsonString.charAt(index) == '"') { - try { - return JSON.parse(jsonString.substring(start, ++index - Number(escape))); - } - catch (e) { - throwMalformedError(String(e)); - } - } - else if (Allow.STR & allow) { - try { - return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); - } - catch (e) { - // SyntaxError: Invalid escape sequence - return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); - } - } - markPartialJSON('Unterminated string literal'); - }; - const parseObj = () => { - index++; // skip initial brace - skipBlank(); - const obj = {}; - try { - while (jsonString[index] !== '}') { - skipBlank(); - if (index >= length && Allow.OBJ & allow) - return obj; - const key = parseStr(); - skipBlank(); - index++; // skip colon - try { - const value = parseAny(); - Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); - } - catch (e) { - if (Allow.OBJ & allow) - return obj; - else - throw e; - } - skipBlank(); - if (jsonString[index] === ',') - index++; // skip comma - } - } - catch (e) { - if (Allow.OBJ & allow) - return obj; - else - markPartialJSON("Expected '}' at end of object"); - } - index++; // skip final brace - return obj; - }; - const parseArr = () => { - index++; // skip initial bracket - const arr = []; - try { - while (jsonString[index] !== ']') { - arr.push(parseAny()); - skipBlank(); - if (jsonString[index] === ',') { - index++; // skip comma - } - } - } - catch (e) { - if (Allow.ARR & allow) { - return arr; - } - markPartialJSON("Expected ']' at end of array"); - } - index++; // skip final bracket - return arr; - }; - const parseNum = () => { - if (index === 0) { - if (jsonString === '-' && Allow.NUM & allow) - markPartialJSON("Not sure what '-' is"); - try { - return JSON.parse(jsonString); - } - catch (e) { - if (Allow.NUM & allow) { - try { - if ('.' === jsonString[jsonString.length - 1]) - return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); - return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); - } - catch (e) { } - } - throwMalformedError(String(e)); - } - } - const start = index; - if (jsonString[index] === '-') - index++; - while (jsonString[index] && !',]}'.includes(jsonString[index])) - index++; - if (index == length && !(Allow.NUM & allow)) - markPartialJSON('Unterminated number literal'); - try { - return JSON.parse(jsonString.substring(start, index)); - } - catch (e) { - if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) - markPartialJSON("Not sure what '-' is"); - try { - return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); - } - catch (e) { - throwMalformedError(String(e)); - } - } - }; - const skipBlank = () => { - while (index < length && ' \n\r\t'.includes(jsonString[index])) { - index++; - } - }; - return parseAny(); -}; -// using this function with malformed JSON is undefined behavior -const parser_partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); - -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs - -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs -var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; - - - - - - -class ChatCompletionStream extends AbstractChatCompletionRunner { - constructor(params) { - super(); - _ChatCompletionStream_instances.add(this); - _ChatCompletionStream_params.set(this, void 0); - _ChatCompletionStream_choiceEventStates.set(this, void 0); - _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); - tslib_classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); - tslib_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); - } - get currentChatCompletionSnapshot() { - return tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new ChatCompletionStream(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createChatCompletion(client, params, options) { - const runner = new ChatCompletionStream(params); - runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - async _createChatCompletion(client, params, options) { - super._createChatCompletion; - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); - const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const chunk of stream) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); - this._connected(); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - let chatId; - for await (const chunk of stream) { - if (chatId && chatId !== chunk.id) { - // A new request has been made. - this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); - chatId = chunk.id; - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { - let state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; - if (state) { - return state; - } - state = { - content_done: false, - refusal_done: false, - logprobs_content_done: false, - logprobs_refusal_done: false, - done_tool_calls: new Set(), - current_tool_call_index: null, - }; - tslib_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; - return state; - }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { - if (this.ended) - return; - const completion = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); - this._emit('chunk', chunk, completion); - for (const choice of chunk.choices) { - const choiceSnapshot = completion.choices[choice.index]; - if (choice.delta.content != null && - choiceSnapshot.message?.role === 'assistant' && - choiceSnapshot.message?.content) { - this._emit('content', choice.delta.content, choiceSnapshot.message.content); - this._emit('content.delta', { - delta: choice.delta.content, - snapshot: choiceSnapshot.message.content, - parsed: choiceSnapshot.message.parsed, - }); - } - if (choice.delta.refusal != null && - choiceSnapshot.message?.role === 'assistant' && - choiceSnapshot.message?.refusal) { - this._emit('refusal.delta', { - delta: choice.delta.refusal, - snapshot: choiceSnapshot.message.refusal, - }); - } - if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { - this._emit('logprobs.content.delta', { - content: choice.logprobs?.content, - snapshot: choiceSnapshot.logprobs?.content ?? [], - }); - } - if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { - this._emit('logprobs.refusal.delta', { - refusal: choice.logprobs?.refusal, - snapshot: choiceSnapshot.logprobs?.refusal ?? [], - }); - } - const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (choiceSnapshot.finish_reason) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); - if (state.current_tool_call_index != null) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); - } - } - for (const toolCall of choice.delta.tool_calls ?? []) { - if (state.current_tool_call_index !== toolCall.index) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); - // new tool call started, the previous one is done - if (state.current_tool_call_index != null) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); - } - } - state.current_tool_call_index = toolCall.index; - } - for (const toolCallDelta of choice.delta.tool_calls ?? []) { - const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; - if (!toolCallSnapshot?.type) { - continue; - } - if (toolCallSnapshot?.type === 'function') { - this._emit('tool_calls.function.arguments.delta', { - name: toolCallSnapshot.function?.name, - index: toolCallDelta.index, - arguments: toolCallSnapshot.function.arguments, - parsed_arguments: toolCallSnapshot.function.parsed_arguments, - arguments_delta: toolCallDelta.function?.arguments ?? '', - }); - } - else { - ChatCompletionStream_assertNever(toolCallSnapshot?.type); - } - } - } - }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { - const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (state.done_tool_calls.has(toolCallIndex)) { - // we've already fired the done event - return; - } - const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; - if (!toolCallSnapshot) { - throw new Error('no tool call snapshot'); - } - if (!toolCallSnapshot.type) { - throw new Error('tool call snapshot missing `type`'); - } - if (toolCallSnapshot.type === 'function') { - const inputTool = tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); // TS doesn't narrow based on isChatCompletionTool - this._emit('tool_calls.function.arguments.done', { - name: toolCallSnapshot.function.name, - index: toolCallIndex, - arguments: toolCallSnapshot.function.arguments, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) - : null, - }); - } - else { - ChatCompletionStream_assertNever(toolCallSnapshot.type); - } - }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { - const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (choiceSnapshot.message.content && !state.content_done) { - state.content_done = true; - const responseFormat = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); - this._emit('content.done', { - content: choiceSnapshot.message.content, - parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, - }); - } - if (choiceSnapshot.message.refusal && !state.refusal_done) { - state.refusal_done = true; - this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); - } - if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { - state.logprobs_content_done = true; - this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); - } - if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { - state.logprobs_refusal_done = true; - this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); - } - }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - const snapshot = tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - if (!snapshot) { - throw new error_OpenAIError(`request ended without sending any chunks`); - } - tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - tslib_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); - return finalizeChatCompletion(snapshot, tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); - }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { - const responseFormat = tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; - if (isAutoParsableResponseFormat(responseFormat)) { - return responseFormat; - } - return null; - }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { - var _a, _b, _c, _d; - let snapshot = tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - const { choices, ...rest } = chunk; - if (!snapshot) { - snapshot = tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { - ...rest, - choices: [], - }, "f"); - } - else { - Object.assign(snapshot, rest); - } - for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { - let choice = snapshot.choices[index]; - if (!choice) { - choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; - } - if (logprobs) { - if (!choice.logprobs) { - choice.logprobs = Object.assign({}, logprobs); - } - else { - const { content, refusal, ...rest } = logprobs; - assertIsEmpty(rest); - Object.assign(choice.logprobs, rest); - if (content) { - (_a = choice.logprobs).content ?? (_a.content = []); - choice.logprobs.content.push(...content); - } - if (refusal) { - (_b = choice.logprobs).refusal ?? (_b.refusal = []); - choice.logprobs.refusal.push(...refusal); - } - } - } - if (finish_reason) { - choice.finish_reason = finish_reason; - if (tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { - if (finish_reason === 'length') { - throw new LengthFinishReasonError(); - } - if (finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - } - } - Object.assign(choice, other); - if (!delta) - continue; // Shouldn't happen; just in case. - const { content, refusal, function_call, role, tool_calls, ...rest } = delta; - assertIsEmpty(rest); - Object.assign(choice.message, rest); - if (refusal) { - choice.message.refusal = (choice.message.refusal || '') + refusal; - } - if (role) - choice.message.role = role; - if (function_call) { - if (!choice.message.function_call) { - choice.message.function_call = function_call; - } - else { - if (function_call.name) - choice.message.function_call.name = function_call.name; - if (function_call.arguments) { - (_c = choice.message.function_call).arguments ?? (_c.arguments = ''); - choice.message.function_call.arguments += function_call.arguments; - } - } - } - if (content) { - choice.message.content = (choice.message.content || '') + content; - if (!choice.message.refusal && tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { - choice.message.parsed = parser_partialParse(choice.message.content); - } - } - if (tool_calls) { - if (!choice.message.tool_calls) - choice.message.tool_calls = []; - for (const { index, id, type, function: fn, ...rest } of tool_calls) { - const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {})); - Object.assign(tool_call, rest); - if (id) - tool_call.id = id; - if (type) - tool_call.type = type; - if (fn) - tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' }); - if (fn?.name) - tool_call.function.name = fn.name; - if (fn?.arguments) { - tool_call.function.arguments += fn.arguments; - if (shouldParseToolCall(tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { - tool_call.function.parsed_arguments = parser_partialParse(tool_call.function.arguments); - } - } - } - } - } - return snapshot; - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('chunk', (chunk) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(chunk); - } - else { - pushQueue.push(chunk); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - toReadableStream() { - const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } -} -function finalizeChatCompletion(snapshot, params) { - const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; - const completion = { - ...rest, - id, - choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { - if (!finish_reason) { - throw new error_OpenAIError(`missing finish_reason for choice ${index}`); - } - const { content = null, function_call, tool_calls, ...messageRest } = message; - const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. - if (!role) { - throw new error_OpenAIError(`missing role for choice ${index}`); - } - if (function_call) { - const { arguments: args, name } = function_call; - if (args == null) { - throw new error_OpenAIError(`missing function_call.arguments for choice ${index}`); - } - if (!name) { - throw new error_OpenAIError(`missing function_call.name for choice ${index}`); - } - return { - ...choiceRest, - message: { - content, - function_call: { arguments: args, name }, - role, - refusal: message.refusal ?? null, - }, - finish_reason, - index, - logprobs, - }; - } - if (tool_calls) { - return { - ...choiceRest, - index, - finish_reason, - logprobs, - message: { - ...messageRest, - role, - content, - refusal: message.refusal ?? null, - tool_calls: tool_calls.map((tool_call, i) => { - const { function: fn, type, id, ...toolRest } = tool_call; - const { arguments: args, name, ...fnRest } = fn || {}; - if (id == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); - } - if (type == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); - } - if (name == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); - } - if (args == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); - } - return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; - }), - }, - }; - } - return { - ...choiceRest, - message: { ...messageRest, content, role, refusal: message.refusal ?? null }, - finish_reason, - index, - logprobs, - }; - }), - created, - model, - object: 'chat.completion', - ...(system_fingerprint ? { system_fingerprint } : {}), - }; - return maybeParseChatCompletion(completion, params); -} -function str(x) { - return JSON.stringify(x); -} -/** - * Ensures the given argument is an empty object, useful for - * asserting that all known properties on an object have been - * destructured. - */ -function assertIsEmpty(obj) { - return; -} -function ChatCompletionStream_assertNever(_x) { } -//# sourceMappingURL=ChatCompletionStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStreamingRunner.mjs - -class ChatCompletionStreamingRunner extends ChatCompletionStream { - static fromReadableStream(stream) { - const runner = new ChatCompletionStreamingRunner(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static runTools(client, params, options) { - const runner = new ChatCompletionStreamingRunner( - // @ts-expect-error TODO these types are incompatible - params); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, - }; - runner._run(() => runner._runTools(client, params, opts)); - return runner; - } -} -//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class completions_Completions extends resource_APIResource { - constructor() { - super(...arguments); - this.messages = new completions_messages_Messages(this._client); - } - create(body, options) { - return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); - } - /** - * Get a stored chat completion. Only Chat Completions that have been created with - * the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * const chatCompletion = - * await client.chat.completions.retrieve('completion_id'); - * ``` - */ - retrieve(completionID, options) { - return this._client.get(path_path `/chat/completions/${completionID}`, options); - } - /** - * Modify a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be modified. Currently, the only - * supported modification is to update the `metadata` field. - * - * @example - * ```ts - * const chatCompletion = await client.chat.completions.update( - * 'completion_id', - * { metadata: { foo: 'string' } }, - * ); - * ``` - */ - update(completionID, body, options) { - return this._client.post(path_path `/chat/completions/${completionID}`, { body, ...options }); - } - /** - * List stored Chat Completions. Only Chat Completions that have been stored with - * the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const chatCompletion of client.chat.completions.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/chat/completions', (CursorPage), { query, ...options }); - } - /** - * Delete a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be deleted. - * - * @example - * ```ts - * const chatCompletionDeleted = - * await client.chat.completions.delete('completion_id'); - * ``` - */ - delete(completionID, options) { - return this._client.delete(path_path `/chat/completions/${completionID}`, options); - } - parse(body, options) { - validateInputTools(body.tools); - return this._client.chat.completions - .create(body, { - ...options, - headers: { - ...options?.headers, - 'X-Stainless-Helper-Method': 'chat.completions.parse', - }, - }) - ._thenUnwrap((completion) => parseChatCompletion(completion, body)); - } - runTools(body, options) { - if (body.stream) { - return ChatCompletionStreamingRunner.runTools(this._client, body, options); - } - return ChatCompletionRunner.runTools(this._client, body, options); - } - /** - * Creates a chat completion stream - */ - stream(body, options) { - return ChatCompletionStream.createChatCompletion(this._client, body, options); - } -} - - - - -completions_Completions.Messages = completions_messages_Messages; -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Chat extends resource_APIResource { - constructor() { - super(...arguments); - this.completions = new completions_Completions(this._client); - } -} -Chat.Completions = completions_Completions; -//# sourceMappingURL=chat.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/headers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const headers_brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders'); -function* headers_iterateHeaders(headers) { - if (!headers) - return; - if (headers_brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; - } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } - else if (values_isReadonlyArray(headers)) { - iter = headers; - } - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (let row of iter) { - const name = row[0]; - if (typeof name !== 'string') - throw new TypeError('expected header name to be a string'); - const values = values_isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - // Objects keys always overwrite older headers, they never append. - // Yield a null to clear the header before adding the new values. - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } - } -} -const headers_buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = new Set(); - for (const headers of newHeaders) { - const seenHeaders = new Set(); - for (const [name, value] of headers_iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } - else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } - } - } - return { [headers_brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; -const headers_isEmptyHeaders = (headers) => { - for (const _ of headers_iterateHeaders(headers)) - return false; - return true; -}; -//# sourceMappingURL=headers.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Speech extends resource_APIResource { - /** - * Generates audio from the input text. - * - * @example - * ```ts - * const speech = await client.audio.speech.create({ - * input: 'input', - * model: 'string', - * voice: 'ash', - * }); - * - * const content = await speech.blob(); - * console.log(content); - * ``` - */ - create(body, options) { - return this._client.post('/audio/speech', { - body, - ...options, - headers: headers_buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]), - __binaryResponse: true, - }); - } -} -//# sourceMappingURL=speech.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Transcriptions extends resource_APIResource { - create(body, options) { - return this._client.post('/audio/transcriptions', uploads_multipartFormRequestOptions({ - body, - ...options, - stream: body.stream ?? false, - __metadata: { model: body.model }, - }, this._client)); - } -} -//# sourceMappingURL=transcriptions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Translations extends resource_APIResource { - create(body, options) { - return this._client.post('/audio/translations', uploads_multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client)); - } -} -//# sourceMappingURL=translations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class Audio extends resource_APIResource { - constructor() { - super(...arguments); - this.transcriptions = new Transcriptions(this._client); - this.translations = new Translations(this._client); - this.speech = new Speech(this._client); - } -} -Audio.Transcriptions = Transcriptions; -Audio.Translations = Translations; -Audio.Speech = Speech; -//# sourceMappingURL=audio.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class resources_batches_Batches extends resource_APIResource { - /** - * Creates and executes a batch from an uploaded file of requests - */ - create(body, options) { - return this._client.post('/batches', { body, ...options }); - } - /** - * Retrieves a batch. - */ - retrieve(batchID, options) { - return this._client.get(path_path `/batches/${batchID}`, options); - } - /** - * List your organization's batches. - */ - list(query = {}, options) { - return this._client.getAPIList('/batches', (CursorPage), { query, ...options }); - } - /** - * Cancels an in-progress batch. The batch will be in status `cancelling` for up to - * 10 minutes, before changing to `cancelled`, where it will have partial results - * (if any) available in the output file. - */ - cancel(batchID, options) { - return this._client.post(path_path `/batches/${batchID}/cancel`, options); - } -} -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/assistants.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Assistants extends resource_APIResource { - /** - * Create an assistant with a model and instructions. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.create({ - * model: 'gpt-4o', - * }); - * ``` - */ - create(body, options) { - return this._client.post('/assistants', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves an assistant. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.retrieve( - * 'assistant_id', - * ); - * ``` - */ - retrieve(assistantID, options) { - return this._client.get(path_path `/assistants/${assistantID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies an assistant. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.update( - * 'assistant_id', - * ); - * ``` - */ - update(assistantID, body, options) { - return this._client.post(path_path `/assistants/${assistantID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of assistants. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const assistant of client.beta.assistants.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/assistants', (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete an assistant. - * - * @example - * ```ts - * const assistantDeleted = - * await client.beta.assistants.delete('assistant_id'); - * ``` - */ - delete(assistantID, options) { - return this._client.delete(path_path `/assistants/${assistantID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=assistants.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/sessions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Sessions extends resource_APIResource { - /** - * Create an ephemeral API token for use in client-side applications with the - * Realtime API. Can be configured with the same session parameters as the - * `session.update` client event. - * - * It responds with a session object, plus a `client_secret` key which contains a - * usable ephemeral API token that can be used to authenticate browser clients for - * the Realtime API. - * - * @example - * ```ts - * const session = - * await client.beta.realtime.sessions.create(); - * ``` - */ - create(body, options) { - return this._client.post('/realtime/sessions', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/transcription-sessions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class TranscriptionSessions extends resource_APIResource { - /** - * Create an ephemeral API token for use in client-side applications with the - * Realtime API specifically for realtime transcriptions. Can be configured with - * the same session parameters as the `transcription_session.update` client event. - * - * It responds with a session object, plus a `client_secret` key which contains a - * usable ephemeral API token that can be used to authenticate browser clients for - * the Realtime API. - * - * @example - * ```ts - * const transcriptionSession = - * await client.beta.realtime.transcriptionSessions.create(); - * ``` - */ - create(body, options) { - return this._client.post('/realtime/transcription_sessions', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=transcription-sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -/** - * @deprecated Realtime has now launched and is generally available. The old beta API is now deprecated. - */ -class Realtime extends resource_APIResource { - constructor() { - super(...arguments); - this.sessions = new Sessions(this._client); - this.transcriptionSessions = new TranscriptionSessions(this._client); - } -} -Realtime.Sessions = Sessions; -Realtime.TranscriptionSessions = TranscriptionSessions; -//# sourceMappingURL=realtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/sessions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class sessions_Sessions extends resource_APIResource { - /** - * Create a ChatKit session - * - * @example - * ```ts - * const chatSession = - * await client.beta.chatkit.sessions.create({ - * user: 'x', - * workflow: { id: 'id' }, - * }); - * ``` - */ - create(body, options) { - return this._client.post('/chatkit/sessions', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * Cancel a ChatKit session - * - * @example - * ```ts - * const chatSession = - * await client.beta.chatkit.sessions.cancel('cksess_123'); - * ``` - */ - cancel(sessionID, options) { - return this._client.post(path_path `/chatkit/sessions/${sessionID}/cancel`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } -} -//# sourceMappingURL=sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/threads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Threads extends resource_APIResource { - /** - * Retrieve a ChatKit thread - * - * @example - * ```ts - * const chatkitThread = - * await client.beta.chatkit.threads.retrieve('cthr_123'); - * ``` - */ - retrieve(threadID, options) { - return this._client.get(path_path `/chatkit/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * List ChatKit threads - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const chatkitThread of client.beta.chatkit.threads.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/chatkit/threads', (ConversationCursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * Delete a ChatKit thread - * - * @example - * ```ts - * const thread = await client.beta.chatkit.threads.delete( - * 'cthr_123', - * ); - * ``` - */ - delete(threadID, options) { - return this._client.delete(path_path `/chatkit/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * List ChatKit thread items - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const thread of client.beta.chatkit.threads.listItems( - * 'cthr_123', - * )) { - * // ... - * } - * ``` - */ - listItems(threadID, query = {}, options) { - return this._client.getAPIList(path_path `/chatkit/threads/${threadID}/items`, (ConversationCursorPage), { query, ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]) }); - } -} -//# sourceMappingURL=threads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/chatkit.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class ChatKit extends resource_APIResource { - constructor() { - super(...arguments); - this.sessions = new sessions_Sessions(this._client); - this.threads = new Threads(this._client); - } -} -ChatKit.Sessions = sessions_Sessions; -ChatKit.Threads = Threads; -//# sourceMappingURL=chatkit.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class threads_messages_Messages extends resource_APIResource { - /** - * Create a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - create(threadID, body, options) { - return this._client.post(path_path `/threads/${threadID}/messages`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieve a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(messageID, params, options) { - const { thread_id } = params; - return this._client.get(path_path `/threads/${thread_id}/messages/${messageID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - update(messageID, params, options) { - const { thread_id, ...body } = params; - return this._client.post(path_path `/threads/${thread_id}/messages/${messageID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of messages for a given thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - list(threadID, query = {}, options) { - return this._client.getAPIList(path_path `/threads/${threadID}/messages`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Deletes a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - delete(messageID, params, options) { - const { thread_id } = params; - return this._client.delete(path_path `/threads/${thread_id}/messages/${messageID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class Steps extends resource_APIResource { - /** - * Retrieves a run step. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(stepID, params, options) { - const { thread_id, run_id, ...query } = params; - return this._client.get(path_path `/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of run steps belonging to a run. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - list(runID, params, options) { - const { thread_id, ...query } = params; - return this._client.getAPIList(path_path `/threads/${thread_id}/runs/${runID}/steps`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=steps.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/base64.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -const toBase64 = (data) => { - if (!data) - return ''; - if (typeof globalThis.Buffer !== 'undefined') { - return globalThis.Buffer.from(data).toString('base64'); - } - if (typeof data === 'string') { - data = encodeUTF8(data); - } - if (typeof btoa !== 'undefined') { - return btoa(String.fromCharCode.apply(null, data)); - } - throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); -}; -const fromBase64 = (str) => { - if (typeof globalThis.Buffer !== 'undefined') { - const buf = globalThis.Buffer.from(str, 'base64'); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - if (typeof atob !== 'undefined') { - const bstr = atob(str); - const buf = new Uint8Array(bstr.length); - for (let i = 0; i < bstr.length; i++) { - buf[i] = bstr.charCodeAt(i); - } - return buf; - } - throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); -}; -/** - * Converts a Base64 encoded string to a Float32Array. - * @param base64Str - The Base64 encoded string. - * @returns An Array of numbers interpreted as Float32 values. - */ -const toFloat32Array = (base64Str) => { - if (typeof Buffer !== 'undefined') { - // for Node.js environment - const buf = Buffer.from(base64Str, 'base64'); - return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); - } - else { - // for legacy web platform APIs - const binaryStr = atob(base64Str); - const len = binaryStr.length; - const bytes = new Uint8Array(len); - for (let i = 0; i < len; i++) { - bytes[i] = binaryStr.charCodeAt(i); - } - return Array.from(new Float32Array(bytes.buffer)); - } -}; -//# sourceMappingURL=base64.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/env.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. - * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. - */ -const env_readEnv = (env) => { - if (typeof globalThis.process !== 'undefined') { - return globalThis.process.env?.[env]?.trim() ?? undefined; - } - if (typeof globalThis.Deno !== 'undefined') { - return globalThis.Deno.env?.get?.(env)?.trim(); - } - return undefined; -}; -//# sourceMappingURL=env.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -//# sourceMappingURL=utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/AssistantStream.mjs -var _AssistantStream_instances, AssistantStream_a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; - - - - - -class AssistantStream extends EventStream { - constructor() { - super(...arguments); - _AssistantStream_instances.add(this); - //Track all events in a single list for reference - _AssistantStream_events.set(this, []); - //Used to accumulate deltas - //We are accumulating many types so the value here is not strict - _AssistantStream_runStepSnapshots.set(this, {}); - _AssistantStream_messageSnapshots.set(this, {}); - _AssistantStream_messageSnapshot.set(this, void 0); - _AssistantStream_finalRun.set(this, void 0); - _AssistantStream_currentContentIndex.set(this, void 0); - _AssistantStream_currentContent.set(this, void 0); - _AssistantStream_currentToolCallIndex.set(this, void 0); - _AssistantStream_currentToolCall.set(this, void 0); - //For current snapshot methods - _AssistantStream_currentEvent.set(this, void 0); - _AssistantStream_currentRunSnapshot.set(this, void 0); - _AssistantStream_currentRunStepSnapshot.set(this, void 0); - } - [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - //Catch all for passing along all events - this.on('event', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - static fromReadableStream(stream) { - const runner = new AssistantStream_a(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - this._connected(); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - toReadableStream() { - const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } - static createToolAssistantStream(runId, runs, params, options) { - const runner = new AssistantStream_a(); - runner._run(() => runner._runToolAssistantStream(runId, runs, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - async _createToolAssistantStream(run, runId, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await run.submitToolOutputs(runId, body, { - ...options, - signal: this.controller.signal, - }); - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - static createThreadAssistantStream(params, thread, options) { - const runner = new AssistantStream_a(); - runner._run(() => runner._threadAssistantStream(params, thread, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - static createAssistantStream(threadId, runs, params, options) { - const runner = new AssistantStream_a(); - runner._run(() => runner._runAssistantStream(threadId, runs, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - currentEvent() { - return tslib_classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); - } - currentRun() { - return tslib_classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); - } - currentMessageSnapshot() { - return tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); - } - currentRunStepSnapshot() { - return tslib_classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); - } - async finalRunSteps() { - await this.done(); - return Object.values(tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); - } - async finalMessages() { - await this.done(); - return Object.values(tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); - } - async finalRun() { - await this.done(); - if (!tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) - throw Error('Final run was not received.'); - return tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); - } - async _createThreadAssistantStream(thread, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - async _createAssistantStream(run, threadId, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - static accumulateDelta(acc, delta) { - for (const [key, deltaValue] of Object.entries(delta)) { - if (!acc.hasOwnProperty(key)) { - acc[key] = deltaValue; - continue; - } - let accValue = acc[key]; - if (accValue === null || accValue === undefined) { - acc[key] = deltaValue; - continue; - } - // We don't accumulate these special properties - if (key === 'index' || key === 'type') { - acc[key] = deltaValue; - continue; - } - // Type-specific accumulation logic - if (typeof accValue === 'string' && typeof deltaValue === 'string') { - accValue += deltaValue; - } - else if (typeof accValue === 'number' && typeof deltaValue === 'number') { - accValue += deltaValue; - } - else if (values_isObj(accValue) && values_isObj(deltaValue)) { - accValue = this.accumulateDelta(accValue, deltaValue); - } - else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { - if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { - accValue.push(...deltaValue); // Use spread syntax for efficient addition - continue; - } - for (const deltaEntry of deltaValue) { - if (!values_isObj(deltaEntry)) { - throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); - } - const index = deltaEntry['index']; - if (index == null) { - console.error(deltaEntry); - throw new Error('Expected array delta entry to have an `index` property'); - } - if (typeof index !== 'number') { - throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); - } - const accEntry = accValue[index]; - if (accEntry == null) { - accValue.push(deltaEntry); - } - else { - accValue[index] = this.accumulateDelta(accEntry, deltaEntry); - } - } - continue; - } - else { - throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); - } - acc[key] = accValue; - } - return acc; - } - _addRun(run) { - return run; - } - async _threadAssistantStream(params, thread, options) { - return await this._createThreadAssistantStream(thread, params, options); - } - async _runAssistantStream(threadId, runs, params, options) { - return await this._createAssistantStream(runs, threadId, params, options); - } - async _runToolAssistantStream(runId, runs, params, options) { - return await this._createToolAssistantStream(runs, runId, params, options); - } -} -AssistantStream_a = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); - switch (event.event) { - case 'thread.created': - //No action on this event. - break; - case 'thread.run.created': - case 'thread.run.queued': - case 'thread.run.in_progress': - case 'thread.run.requires_action': - case 'thread.run.completed': - case 'thread.run.incomplete': - case 'thread.run.failed': - case 'thread.run.cancelling': - case 'thread.run.cancelled': - case 'thread.run.expired': - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); - break; - case 'thread.run.step.created': - case 'thread.run.step.in_progress': - case 'thread.run.step.delta': - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); - break; - case 'thread.message.created': - case 'thread.message.in_progress': - case 'thread.message.delta': - case 'thread.message.completed': - case 'thread.message.incomplete': - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); - break; - case 'error': - //This is included for completeness, but errors are processed in the SSE event processing so this should not occur - throw new Error('Encountered an error event in event processing - errors should be processed earlier'); - default: - AssistantStream_assertNever(event); - } -}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - if (!tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) - throw Error('Final run has not been received'); - return tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); -}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { - const [accumulatedMessage, newContent] = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - tslib_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); - tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; - for (const content of newContent) { - const snapshotContent = accumulatedMessage.content[content.index]; - if (snapshotContent?.type == 'text') { - this._emit('textCreated', snapshotContent.text); - } - } - switch (event.event) { - case 'thread.message.created': - this._emit('messageCreated', event.data); - break; - case 'thread.message.in_progress': - break; - case 'thread.message.delta': - this._emit('messageDelta', event.data.delta, accumulatedMessage); - if (event.data.delta.content) { - for (const content of event.data.delta.content) { - //If it is text delta, emit a text delta event - if (content.type == 'text' && content.text) { - let textDelta = content.text; - let snapshot = accumulatedMessage.content[content.index]; - if (snapshot && snapshot.type == 'text') { - this._emit('textDelta', textDelta, snapshot.text); - } - else { - throw Error('The snapshot associated with this text delta is not text or missing'); - } - } - if (content.index != tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { - //See if we have in progress content - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { - switch (tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { - case 'text': - this._emit('textDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - case 'image_file': - this._emit('imageFileDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - } - } - tslib_classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); - } - tslib_classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); - } - } - break; - case 'thread.message.completed': - case 'thread.message.incomplete': - //We emit the latest content we were working on on completion (including incomplete) - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { - const currentContent = event.data.content[tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; - if (currentContent) { - switch (currentContent.type) { - case 'image_file': - this._emit('imageFileDone', currentContent.image_file, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - case 'text': - this._emit('textDone', currentContent.text, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - } - } - } - if (tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { - this._emit('messageDone', event.data); - } - tslib_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); - } -}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { - const accumulatedRunStep = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); - tslib_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); - switch (event.event) { - case 'thread.run.step.created': - this._emit('runStepCreated', event.data); - break; - case 'thread.run.step.delta': - const delta = event.data.delta; - if (delta.step_details && - delta.step_details.type == 'tool_calls' && - delta.step_details.tool_calls && - accumulatedRunStep.step_details.type == 'tool_calls') { - for (const toolCall of delta.step_details.tool_calls) { - if (toolCall.index == tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { - this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); - } - else { - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - } - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) - this._emit('toolCallCreated', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - } - } - } - this._emit('runStepDelta', event.data.delta, accumulatedRunStep); - break; - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - tslib_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); - const details = event.data.step_details; - if (details.type == 'tool_calls') { - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } - } - this._emit('runStepDone', event.data, accumulatedRunStep); - break; - case 'thread.run.step.in_progress': - break; - } -}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { - tslib_classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); - this._emit('event', event); -}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { - switch (event.event) { - case 'thread.run.step.created': - tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; - return event.data; - case 'thread.run.step.delta': - let snapshot = tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - if (!snapshot) { - throw Error('Received a RunStepDelta before creation of a snapshot'); - } - let data = event.data; - if (data.delta) { - const accumulated = AssistantStream_a.accumulateDelta(snapshot, data.delta); - tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; - } - return tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - case 'thread.run.step.in_progress': - tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; - break; - } - if (tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) - return tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - throw new Error('No snapshot available'); -}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { - let newContent = []; - switch (event.event) { - case 'thread.message.created': - //On creation the snapshot is just the initial message - return [event.data, newContent]; - case 'thread.message.delta': - if (!snapshot) { - throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); - } - let data = event.data; - //If this delta does not have content, nothing to process - if (data.delta.content) { - for (const contentElement of data.delta.content) { - if (contentElement.index in snapshot.content) { - let currentContent = snapshot.content[contentElement.index]; - snapshot.content[contentElement.index] = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); - } - else { - snapshot.content[contentElement.index] = contentElement; - // This is a new element - newContent.push(contentElement); - } - } - } - return [snapshot, newContent]; - case 'thread.message.in_progress': - case 'thread.message.completed': - case 'thread.message.incomplete': - //No changes on other thread events - if (snapshot) { - return [snapshot, newContent]; - } - else { - throw Error('Received thread message event with no existing snapshot'); - } - } - throw Error('Tried to accumulate a non-message event'); -}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { - return AssistantStream_a.accumulateDelta(currentContent, contentElement); -}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { - tslib_classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); - switch (event.event) { - case 'thread.run.created': - break; - case 'thread.run.queued': - break; - case 'thread.run.in_progress': - break; - case 'thread.run.requires_action': - case 'thread.run.cancelled': - case 'thread.run.failed': - case 'thread.run.completed': - case 'thread.run.expired': - case 'thread.run.incomplete': - tslib_classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } - break; - case 'thread.run.cancelling': - break; - } -}; -function AssistantStream_assertNever(_x) { } -//# sourceMappingURL=AssistantStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class Runs extends resource_APIResource { - constructor() { - super(...arguments); - this.steps = new Steps(this._client); - } - create(threadID, params, options) { - const { include, ...body } = params; - return this._client.post(path_path `/threads/${threadID}/runs`, { - query: { include }, - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - stream: params.stream ?? false, - }); - } - /** - * Retrieves a run. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(runID, params, options) { - const { thread_id } = params; - return this._client.get(path_path `/threads/${thread_id}/runs/${runID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a run. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - update(runID, params, options) { - const { thread_id, ...body } = params; - return this._client.post(path_path `/threads/${thread_id}/runs/${runID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of runs belonging to a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - list(threadID, query = {}, options) { - return this._client.getAPIList(path_path `/threads/${threadID}/runs`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Cancels a run that is `in_progress`. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - cancel(runID, params, options) { - const { thread_id } = params; - return this._client.post(path_path `/threads/${thread_id}/runs/${runID}/cancel`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * A helper to create a run an poll for a terminal state. More information on Run - * lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async createAndPoll(threadId, body, options) { - const run = await this.create(threadId, body, options); - return await this.poll(run.id, { thread_id: threadId }, options); - } - /** - * Create a Run stream - * - * @deprecated use `stream` instead - */ - createAndStream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); - } - /** - * A helper to poll a run status until it reaches a terminal state. More - * information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async poll(runId, params, options) { - const headers = headers_buildHeaders([ - options?.headers, - { - 'X-Stainless-Poll-Helper': 'true', - 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, - }, - ]); - while (true) { - const { data: run, response } = await this.retrieve(runId, params, { - ...options, - headers: { ...options?.headers, ...headers }, - }).withResponse(); - switch (run.status) { - //If we are in any sort of intermediate state we poll - case 'queued': - case 'in_progress': - case 'cancelling': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep_sleep(sleepInterval); - break; - //We return the run in any terminal state. - case 'requires_action': - case 'incomplete': - case 'cancelled': - case 'completed': - case 'failed': - case 'expired': - return run; - } - } - } - /** - * Create a Run stream - */ - stream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); - } - submitToolOutputs(runID, params, options) { - const { thread_id, ...body } = params; - return this._client.post(path_path `/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - stream: params.stream ?? false, - }); - } - /** - * A helper to submit a tool output to a run and poll for a terminal run state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async submitToolOutputsAndPoll(runId, params, options) { - const run = await this.submitToolOutputs(runId, params, options); - return await this.poll(run.id, params, options); - } - /** - * Submit the tool outputs from a previous run and stream the run to a terminal - * state. More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - submitToolOutputsStream(runId, params, options) { - return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); - } -} -Runs.Steps = Steps; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class threads_Threads extends resource_APIResource { - constructor() { - super(...arguments); - this.runs = new Runs(this._client); - this.messages = new threads_messages_Messages(this._client); - } - /** - * Create a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - create(body = {}, options) { - return this._client.post('/threads', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(threadID, options) { - return this._client.get(path_path `/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - update(threadID, body, options) { - return this._client.post(path_path `/threads/${threadID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - delete(threadID, options) { - return this._client.delete(path_path `/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - createAndRun(body, options) { - return this._client.post('/threads/runs', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - stream: body.stream ?? false, - }); - } - /** - * A helper to create a thread, start a run and then poll for a terminal state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async createAndRunPoll(body, options) { - const run = await this.createAndRun(body, options); - return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); - } - /** - * Create a thread and stream the run back - */ - createAndRunStream(body, options) { - return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); - } -} -threads_Threads.Runs = Runs; -threads_Threads.Messages = threads_messages_Messages; -//# sourceMappingURL=threads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class beta_Beta extends resource_APIResource { - constructor() { - super(...arguments); - this.realtime = new Realtime(this._client); - this.chatkit = new ChatKit(this._client); - this.assistants = new Assistants(this._client); - this.threads = new threads_Threads(this._client); - } -} -beta_Beta.Realtime = Realtime; -beta_Beta.ChatKit = ChatKit; -beta_Beta.Assistants = Assistants; -beta_Beta.Threads = threads_Threads; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class resources_completions_Completions extends resource_APIResource { - create(body, options) { - return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); - } -} -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/content.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Content extends resource_APIResource { - /** - * Retrieve Container File Content - */ - retrieve(fileID, params, options) { - const { container_id } = params; - return this._client.get(path_path `/containers/${container_id}/files/${fileID}/content`, { - ...options, - headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - __binaryResponse: true, - }); - } -} -//# sourceMappingURL=content.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class files_Files extends resource_APIResource { - constructor() { - super(...arguments); - this.content = new Content(this._client); - } - /** - * Create a Container File - * - * You can send either a multipart/form-data request with the raw file content, or - * a JSON request with a file ID. - */ - create(containerID, body, options) { - return this._client.post(path_path `/containers/${containerID}/files`, uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Retrieve Container File - */ - retrieve(fileID, params, options) { - const { container_id } = params; - return this._client.get(path_path `/containers/${container_id}/files/${fileID}`, options); - } - /** - * List Container files - */ - list(containerID, query = {}, options) { - return this._client.getAPIList(path_path `/containers/${containerID}/files`, (CursorPage), { - query, - ...options, - }); - } - /** - * Delete Container File - */ - delete(fileID, params, options) { - const { container_id } = params; - return this._client.delete(path_path `/containers/${container_id}/files/${fileID}`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } -} -files_Files.Content = Content; -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/containers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class Containers extends resource_APIResource { - constructor() { - super(...arguments); - this.files = new files_Files(this._client); - } - /** - * Create Container - */ - create(body, options) { - return this._client.post('/containers', { body, ...options }); - } - /** - * Retrieve Container - */ - retrieve(containerID, options) { - return this._client.get(path_path `/containers/${containerID}`, options); - } - /** - * List Containers - */ - list(query = {}, options) { - return this._client.getAPIList('/containers', (CursorPage), { query, ...options }); - } - /** - * Delete Container - */ - delete(containerID, options) { - return this._client.delete(path_path `/containers/${containerID}`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } -} -Containers.Files = files_Files; -//# sourceMappingURL=containers.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Items extends resource_APIResource { - /** - * Create items in a conversation with the given ID. - */ - create(conversationID, params, options) { - const { include, ...body } = params; - return this._client.post(path_path `/conversations/${conversationID}/items`, { - query: { include }, - body, - ...options, - }); - } - /** - * Get a single item from a conversation with the given IDs. - */ - retrieve(itemID, params, options) { - const { conversation_id, ...query } = params; - return this._client.get(path_path `/conversations/${conversation_id}/items/${itemID}`, { query, ...options }); - } - /** - * List all items for a conversation with the given ID. - */ - list(conversationID, query = {}, options) { - return this._client.getAPIList(path_path `/conversations/${conversationID}/items`, (ConversationCursorPage), { query, ...options }); - } - /** - * Delete an item from a conversation with the given IDs. - */ - delete(itemID, params, options) { - const { conversation_id } = params; - return this._client.delete(path_path `/conversations/${conversation_id}/items/${itemID}`, options); - } -} -//# sourceMappingURL=items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/conversations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Conversations extends resource_APIResource { - constructor() { - super(...arguments); - this.items = new Items(this._client); - } - /** - * Create a conversation. - */ - create(body = {}, options) { - return this._client.post('/conversations', { body, ...options }); - } - /** - * Get a conversation - */ - retrieve(conversationID, options) { - return this._client.get(path_path `/conversations/${conversationID}`, options); - } - /** - * Update a conversation - */ - update(conversationID, body, options) { - return this._client.post(path_path `/conversations/${conversationID}`, { body, ...options }); - } - /** - * Delete a conversation. Items in the conversation will not be deleted. - */ - delete(conversationID, options) { - return this._client.delete(path_path `/conversations/${conversationID}`, options); - } -} -Conversations.Items = Items; -//# sourceMappingURL=conversations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class embeddings_Embeddings extends resource_APIResource { - /** - * Creates an embedding vector representing the input text. - * - * @example - * ```ts - * const createEmbeddingResponse = - * await client.embeddings.create({ - * input: 'The quick brown fox jumped over the lazy dog', - * model: 'text-embedding-3-small', - * }); - * ``` - */ - create(body, options) { - const hasUserProvidedEncodingFormat = !!body.encoding_format; - // No encoding_format specified, defaulting to base64 for performance reasons - // See https://github.com/openai/openai-node/pull/1312 - let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; - if (hasUserProvidedEncodingFormat) { - log_loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format); - } - const response = this._client.post('/embeddings', { - body: { - ...body, - encoding_format: encoding_format, - }, - ...options, - }); - // if the user specified an encoding_format, return the response as-is - if (hasUserProvidedEncodingFormat) { - return response; - } - // in this stage, we are sure the user did not specify an encoding_format - // and we defaulted to base64 for performance reasons - // we are sure then that the response is base64 encoded, let's decode it - // the returned result will be a float32 array since this is OpenAI API's default encoding - log_loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64'); - return response._thenUnwrap((response) => { - if (response && response.data) { - response.data.forEach((embeddingBase64Obj) => { - const embeddingBase64Str = embeddingBase64Obj.embedding; - embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); - }); - } - return response; - }); - } -} -//# sourceMappingURL=embeddings.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class OutputItems extends resource_APIResource { - /** - * Get an evaluation run output item by ID. - */ - retrieve(outputItemID, params, options) { - const { eval_id, run_id } = params; - return this._client.get(path_path `/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); - } - /** - * Get a list of output items for an evaluation run. - */ - list(runID, params, options) { - const { eval_id, ...query } = params; - return this._client.getAPIList(path_path `/evals/${eval_id}/runs/${runID}/output_items`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=output-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class runs_Runs extends resource_APIResource { - constructor() { - super(...arguments); - this.outputItems = new OutputItems(this._client); - } - /** - * Kicks off a new run for a given evaluation, specifying the data source, and what - * model configuration to use to test. The datasource will be validated against the - * schema specified in the config of the evaluation. - */ - create(evalID, body, options) { - return this._client.post(path_path `/evals/${evalID}/runs`, { body, ...options }); - } - /** - * Get an evaluation run by ID. - */ - retrieve(runID, params, options) { - const { eval_id } = params; - return this._client.get(path_path `/evals/${eval_id}/runs/${runID}`, options); - } - /** - * Get a list of runs for an evaluation. - */ - list(evalID, query = {}, options) { - return this._client.getAPIList(path_path `/evals/${evalID}/runs`, (CursorPage), { - query, - ...options, - }); - } - /** - * Delete an eval run. - */ - delete(runID, params, options) { - const { eval_id } = params; - return this._client.delete(path_path `/evals/${eval_id}/runs/${runID}`, options); - } - /** - * Cancel an ongoing evaluation run. - */ - cancel(runID, params, options) { - const { eval_id } = params; - return this._client.post(path_path `/evals/${eval_id}/runs/${runID}`, options); - } -} -runs_Runs.OutputItems = OutputItems; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Evals extends resource_APIResource { - constructor() { - super(...arguments); - this.runs = new runs_Runs(this._client); - } - /** - * Create the structure of an evaluation that can be used to test a model's - * performance. An evaluation is a set of testing criteria and the config for a - * data source, which dictates the schema of the data used in the evaluation. After - * creating an evaluation, you can run it on different models and model parameters. - * We support several types of graders and datasources. For more information, see - * the [Evals guide](https://platform.openai.com/docs/guides/evals). - */ - create(body, options) { - return this._client.post('/evals', { body, ...options }); - } - /** - * Get an evaluation by ID. - */ - retrieve(evalID, options) { - return this._client.get(path_path `/evals/${evalID}`, options); - } - /** - * Update certain properties of an evaluation. - */ - update(evalID, body, options) { - return this._client.post(path_path `/evals/${evalID}`, { body, ...options }); - } - /** - * List evaluations for a project. - */ - list(query = {}, options) { - return this._client.getAPIList('/evals', (CursorPage), { query, ...options }); - } - /** - * Delete an evaluation. - */ - delete(evalID, options) { - return this._client.delete(path_path `/evals/${evalID}`, options); - } -} -Evals.Runs = runs_Runs; -//# sourceMappingURL=evals.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class resources_files_Files extends resource_APIResource { - /** - * Upload a file that can be used across various endpoints. Individual files can be - * up to 512 MB, and the size of all files uploaded by one organization can be up - * to 1 TB. - * - * - The Assistants API supports files up to 2 million tokens and of specific file - * types. See the - * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) - * for details. - * - The Fine-tuning API only supports `.jsonl` files. The input also has certain - * required formats for fine-tuning - * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) - * or - * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) - * models. - * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input - * also has a specific required - * [format](https://platform.openai.com/docs/api-reference/batch/request-input). - * - * Please [contact us](https://help.openai.com/) if you need to increase these - * storage limits. - */ - create(body, options) { - return this._client.post('/files', uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Returns information about a specific file. - */ - retrieve(fileID, options) { - return this._client.get(path_path `/files/${fileID}`, options); - } - /** - * Returns a list of files. - */ - list(query = {}, options) { - return this._client.getAPIList('/files', (CursorPage), { query, ...options }); - } - /** - * Delete a file and remove it from all vector stores. - */ - delete(fileID, options) { - return this._client.delete(path_path `/files/${fileID}`, options); - } - /** - * Returns the contents of the specified file. - */ - content(fileID, options) { - return this._client.get(path_path `/files/${fileID}/content`, { - ...options, - headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - __binaryResponse: true, - }); - } - /** - * Waits for the given file to be processed, default timeout is 30 mins. - */ - async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { - const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); - const start = Date.now(); - let file = await this.retrieve(id); - while (!file.status || !TERMINAL_STATES.has(file.status)) { - await sleep_sleep(pollInterval); - file = await this.retrieve(id); - if (Date.now() - start > maxWait) { - throw new error_APIConnectionTimeoutError({ - message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, - }); - } - } - return file; - } -} -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Methods extends resource_APIResource { -} -//# sourceMappingURL=methods.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Graders extends resource_APIResource { - /** - * Run a grader. - * - * @example - * ```ts - * const response = await client.fineTuning.alpha.graders.run({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * model_sample: 'model_sample', - * }); - * ``` - */ - run(body, options) { - return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); - } - /** - * Validate a grader. - * - * @example - * ```ts - * const response = - * await client.fineTuning.alpha.graders.validate({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * }); - * ``` - */ - validate(body, options) { - return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); - } -} -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Alpha extends resource_APIResource { - constructor() { - super(...arguments); - this.graders = new Graders(this._client); - } -} -Alpha.Graders = Graders; -//# sourceMappingURL=alpha.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Permissions extends resource_APIResource { - /** - * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). - * - * This enables organization owners to share fine-tuned models with other projects - * in their organization. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * { project_ids: ['string'] }, - * )) { - * // ... - * } - * ``` - */ - create(fineTunedModelCheckpoint, body, options) { - return this._client.getAPIList(path_path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (pagination_Page), { body, method: 'post', ...options }); - } - /** - * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - * - * Organization owners can use this endpoint to view all permissions for a - * fine-tuned model checkpoint. - * - * @example - * ```ts - * const permission = - * await client.fineTuning.checkpoints.permissions.retrieve( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - retrieve(fineTunedModelCheckpoint, query = {}, options) { - return this._client.get(path_path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { - query, - ...options, - }); - } - /** - * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - * - * Organization owners can use this endpoint to delete a permission for a - * fine-tuned model checkpoint. - * - * @example - * ```ts - * const permission = - * await client.fineTuning.checkpoints.permissions.delete( - * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', - * { - * fine_tuned_model_checkpoint: - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * }, - * ); - * ``` - */ - delete(permissionID, params, options) { - const { fine_tuned_model_checkpoint } = params; - return this._client.delete(path_path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); - } -} -//# sourceMappingURL=permissions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Checkpoints extends resource_APIResource { - constructor() { - super(...arguments); - this.permissions = new Permissions(this._client); - } -} -Checkpoints.Permissions = Permissions; -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class checkpoints_Checkpoints extends resource_APIResource { - /** - * List checkpoints for a fine-tuning job. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * )) { - * // ... - * } - * ``` - */ - list(fineTuningJobID, query = {}, options) { - return this._client.getAPIList(path_path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Jobs extends resource_APIResource { - constructor() { - super(...arguments); - this.checkpoints = new checkpoints_Checkpoints(this._client); - } - /** - * Creates a fine-tuning job which begins the process of creating a new model from - * a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.create({ - * model: 'gpt-4o-mini', - * training_file: 'file-abc123', - * }); - * ``` - */ - create(body, options) { - return this._client.post('/fine_tuning/jobs', { body, ...options }); - } - /** - * Get info about a fine-tuning job. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.retrieve( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - retrieve(fineTuningJobID, options) { - return this._client.get(path_path `/fine_tuning/jobs/${fineTuningJobID}`, options); - } - /** - * List your organization's fine-tuning jobs - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fineTuningJob of client.fineTuning.jobs.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options }); - } - /** - * Immediately cancel a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.cancel( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - cancel(fineTuningJobID, options) { - return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); - } - /** - * Get status updates for a fine-tuning job. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * )) { - * // ... - * } - * ``` - */ - listEvents(fineTuningJobID, query = {}, options) { - return this._client.getAPIList(path_path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options }); - } - /** - * Pause a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.pause( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - pause(fineTuningJobID, options) { - return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); - } - /** - * Resume a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.resume( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - resume(fineTuningJobID, options) { - return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); - } -} -Jobs.Checkpoints = checkpoints_Checkpoints; -//# sourceMappingURL=jobs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class FineTuning extends resource_APIResource { - constructor() { - super(...arguments); - this.methods = new Methods(this._client); - this.jobs = new Jobs(this._client); - this.checkpoints = new Checkpoints(this._client); - this.alpha = new Alpha(this._client); - } -} -FineTuning.Methods = Methods; -FineTuning.Jobs = Jobs; -FineTuning.Checkpoints = Checkpoints; -FineTuning.Alpha = Alpha; -//# sourceMappingURL=fine-tuning.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class GraderModels extends resource_APIResource { -} -//# sourceMappingURL=grader-models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class graders_Graders extends resource_APIResource { - constructor() { - super(...arguments); - this.graderModels = new GraderModels(this._client); - } -} -graders_Graders.GraderModels = GraderModels; -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Images extends resource_APIResource { - /** - * Creates a variation of a given image. This endpoint only supports `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.createVariation({ - * image: fs.createReadStream('otter.png'), - * }); - * ``` - */ - createVariation(body, options) { - return this._client.post('/images/variations', uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } - edit(body, options) { - return this._client.post('/images/edits', uploads_multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client)); - } - generate(body, options) { - return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false }); - } -} -//# sourceMappingURL=images.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class resources_models_Models extends resource_APIResource { - /** - * Retrieves a model instance, providing basic information about the model such as - * the owner and permissioning. - */ - retrieve(model, options) { - return this._client.get(path_path `/models/${model}`, options); - } - /** - * Lists the currently available models, and provides basic information about each - * one such as the owner and availability. - */ - list(options) { - return this._client.getAPIList('/models', (pagination_Page), options); - } - /** - * Delete a fine-tuned model. You must have the Owner role in your organization to - * delete a model. - */ - delete(model, options) { - return this._client.delete(path_path `/models/${model}`, options); - } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Moderations extends resource_APIResource { - /** - * Classifies if text and/or image inputs are potentially harmful. Learn more in - * the [moderation guide](https://platform.openai.com/docs/guides/moderation). - */ - create(body, options) { - return this._client.post('/moderations', { body, ...options }); - } -} -//# sourceMappingURL=moderations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/calls.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Calls extends resource_APIResource { - /** - * Accept an incoming SIP call and configure the realtime session that will handle - * it. - * - * @example - * ```ts - * await client.realtime.calls.accept('call_id', { - * type: 'realtime', - * }); - * ``` - */ - accept(callID, body, options) { - return this._client.post(path_path `/realtime/calls/${callID}/accept`, { - body, - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - /** - * End an active Realtime API call, whether it was initiated over SIP or WebRTC. - * - * @example - * ```ts - * await client.realtime.calls.hangup('call_id'); - * ``` - */ - hangup(callID, options) { - return this._client.post(path_path `/realtime/calls/${callID}/hangup`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - /** - * Transfer an active SIP call to a new destination using the SIP REFER verb. - * - * @example - * ```ts - * await client.realtime.calls.refer('call_id', { - * target_uri: 'tel:+14155550123', - * }); - * ``` - */ - refer(callID, body, options) { - return this._client.post(path_path `/realtime/calls/${callID}/refer`, { - body, - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - /** - * Decline an incoming SIP call by returning a SIP status code to the caller. - * - * @example - * ```ts - * await client.realtime.calls.reject('call_id'); - * ``` - */ - reject(callID, body = {}, options) { - return this._client.post(path_path `/realtime/calls/${callID}/reject`, { - body, - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } -} -//# sourceMappingURL=calls.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/client-secrets.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class ClientSecrets extends resource_APIResource { - /** - * Create a Realtime client secret with an associated session configuration. - * - * @example - * ```ts - * const clientSecret = - * await client.realtime.clientSecrets.create(); - * ``` - */ - create(body, options) { - return this._client.post('/realtime/client_secrets', { body, ...options }); - } -} -//# sourceMappingURL=client-secrets.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/realtime.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class realtime_Realtime extends resource_APIResource { - constructor() { - super(...arguments); - this.clientSecrets = new ClientSecrets(this._client); - this.calls = new Calls(this._client); - } -} -realtime_Realtime.ClientSecrets = ClientSecrets; -realtime_Realtime.Calls = Calls; -//# sourceMappingURL=realtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/responses/ResponseStream.mjs -var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse; - - - - -class ResponseStream extends EventStream { - constructor(params) { - super(); - _ResponseStream_instances.add(this); - _ResponseStream_params.set(this, void 0); - _ResponseStream_currentResponseSnapshot.set(this, void 0); - _ResponseStream_finalResponse.set(this, void 0); - tslib_classPrivateFieldSet(this, _ResponseStream_params, params, "f"); - } - static createResponse(client, params, options) { - const runner = new ResponseStream(params); - runner._run(() => runner._createOrRetrieveResponse(client, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - async _createOrRetrieveResponse(client, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); - let stream; - let starting_after = null; - if ('response_id' in params) { - stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true }); - starting_after = params.starting_after ?? null; - } - else { - stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); - } - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); - } - [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) { - if (this.ended) - return; - const maybeEmit = (name, event) => { - if (starting_after == null || event.sequence_number > starting_after) { - this._emit(name, event); - } - }; - const response = tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); - maybeEmit('event', event); - switch (event.type) { - case 'response.output_text.delta': { - const output = response.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - const content = output.content[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'output_text') { - throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); - } - maybeEmit('response.output_text.delta', { - ...event, - snapshot: content.text, - }); - } - break; - } - case 'response.function_call_arguments.delta': { - const output = response.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'function_call') { - maybeEmit('response.function_call_arguments.delta', { - ...event, - snapshot: output.arguments, - }); - } - break; - } - default: - maybeEmit(event.type, event); - break; - } - }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - const snapshot = tslib_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); - if (!snapshot) { - throw new error_OpenAIError(`request ended without sending any events`); - } - tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - const parsedResponse = finalizeResponse(snapshot, tslib_classPrivateFieldGet(this, _ResponseStream_params, "f")); - tslib_classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); - return parsedResponse; - }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) { - let snapshot = tslib_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); - if (!snapshot) { - if (event.type !== 'response.created') { - throw new error_OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); - } - snapshot = tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); - return snapshot; - } - switch (event.type) { - case 'response.output_item.added': { - snapshot.output.push(event.item); - break; - } - case 'response.content_part.added': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - const type = output.type; - const part = event.part; - if (type === 'message' && part.type !== 'reasoning_text') { - output.content.push(part); - } - else if (type === 'reasoning' && part.type === 'reasoning_text') { - if (!output.content) { - output.content = []; - } - output.content.push(part); - } - break; - } - case 'response.output_text.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - const content = output.content[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'output_text') { - throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); - } - content.text += event.delta; - } - break; - } - case 'response.function_call_arguments.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'function_call') { - output.arguments += event.delta; - } - break; - } - case 'response.reasoning_text.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'reasoning') { - const content = output.content?.[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'reasoning_text') { - throw new error_OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); - } - content.text += event.delta; - } - break; - } - case 'response.completed': { - tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); - break; - } - } - return snapshot; - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('event', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true })); - } - const event = pushQueue.shift(); - return { value: event, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - /** - * @returns a promise that resolves with the final Response, or rejects - * if an error occurred or the stream ended prematurely without producing a REsponse. - */ - async finalResponse() { - await this.done(); - const response = tslib_classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); - if (!response) - throw new error_OpenAIError('stream ended without producing a ChatCompletion'); - return response; - } -} -function finalizeResponse(snapshot, params) { - return maybeParseResponse(snapshot, params); -} -//# sourceMappingURL=ResponseStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class InputItems extends resource_APIResource { - /** - * Returns a list of input items for a given response. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const responseItem of client.responses.inputItems.list( - * 'response_id', - * )) { - * // ... - * } - * ``` - */ - list(responseID, query = {}, options) { - return this._client.getAPIList(path_path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=input-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-tokens.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class InputTokens extends resource_APIResource { - /** - * Get input token counts - * - * @example - * ```ts - * const response = await client.responses.inputTokens.count(); - * ``` - */ - count(body = {}, options) { - return this._client.post('/responses/input_tokens', { body, ...options }); - } -} -//# sourceMappingURL=input-tokens.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/responses.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class Responses extends resource_APIResource { - constructor() { - super(...arguments); - this.inputItems = new InputItems(this._client); - this.inputTokens = new InputTokens(this._client); - } - create(body, options) { - return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => { - if ('object' in rsp && rsp.object === 'response') { - addOutputText(rsp); - } - return rsp; - }); - } - retrieve(responseID, query = {}, options) { - return this._client.get(path_path `/responses/${responseID}`, { - query, - ...options, - stream: query?.stream ?? false, - })._thenUnwrap((rsp) => { - if ('object' in rsp && rsp.object === 'response') { - addOutputText(rsp); - } - return rsp; - }); - } - /** - * Deletes a model response with the given ID. - * - * @example - * ```ts - * await client.responses.delete( - * 'resp_677efb5139a88190b512bc3fef8e535d', - * ); - * ``` - */ - delete(responseID, options) { - return this._client.delete(path_path `/responses/${responseID}`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - parse(body, options) { - return this._client.responses - .create(body, options) - ._thenUnwrap((response) => parseResponse(response, body)); - } - /** - * Creates a model response stream - */ - stream(body, options) { - return ResponseStream.createResponse(this._client, body, options); - } - /** - * Cancels a model response with the given ID. Only responses created with the - * `background` parameter set to `true` can be cancelled. - * [Learn more](https://platform.openai.com/docs/guides/background). - * - * @example - * ```ts - * const response = await client.responses.cancel( - * 'resp_677efb5139a88190b512bc3fef8e535d', - * ); - * ``` - */ - cancel(responseID, options) { - return this._client.post(path_path `/responses/${responseID}/cancel`, options); - } -} -Responses.InputItems = InputItems; -Responses.InputTokens = InputTokens; -//# sourceMappingURL=responses.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Parts extends resource_APIResource { - /** - * Adds a - * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. - * A Part represents a chunk of bytes from the file you are trying to upload. - * - * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload - * maximum of 8 GB. - * - * It is possible to add multiple Parts in parallel. You can decide the intended - * order of the Parts when you - * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). - */ - create(uploadID, body, options) { - return this._client.post(path_path `/uploads/${uploadID}/parts`, uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } -} -//# sourceMappingURL=parts.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Uploads extends resource_APIResource { - constructor() { - super(...arguments); - this.parts = new Parts(this._client); - } - /** - * Creates an intermediate - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object - * that you can add - * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. - * Currently, an Upload can accept at most 8 GB in total and expires after an hour - * after you create it. - * - * Once you complete the Upload, we will create a - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * contains all the parts you uploaded. This File is usable in the rest of our - * platform as a regular File object. - * - * For certain `purpose` values, the correct `mime_type` must be specified. Please - * refer to documentation for the - * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). - * - * For guidance on the proper filename extensions for each purpose, please follow - * the documentation on - * [creating a File](https://platform.openai.com/docs/api-reference/files/create). - */ - create(body, options) { - return this._client.post('/uploads', { body, ...options }); - } - /** - * Cancels the Upload. No Parts may be added after an Upload is cancelled. - */ - cancel(uploadID, options) { - return this._client.post(path_path `/uploads/${uploadID}/cancel`, options); - } - /** - * Completes the - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). - * - * Within the returned Upload object, there is a nested - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * is ready to use in the rest of the platform. - * - * You can specify the order of the Parts by passing in an ordered list of the Part - * IDs. - * - * The number of bytes uploaded upon completion must match the number of bytes - * initially specified when creating the Upload object. No Parts may be added after - * an Upload is completed. - */ - complete(uploadID, body, options) { - return this._client.post(path_path `/uploads/${uploadID}/complete`, { body, ...options }); - } -} -Uploads.Parts = Parts; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs -/** - * Like `Promise.allSettled()` but throws an error if any promises are rejected. - */ -const allSettledWithThrow = async (promises) => { - const results = await Promise.allSettled(promises); - const rejected = results.filter((result) => result.status === 'rejected'); - if (rejected.length) { - for (const result of rejected) { - console.error(result.reason); - } - throw new Error(`${rejected.length} promise(s) failed - see the above errors`); - } - // Note: TS was complaining about using `.filter().map()` here for some reason - const values = []; - for (const result of results) { - if (result.status === 'fulfilled') { - values.push(result.value); - } - } - return values; -}; -//# sourceMappingURL=Util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class FileBatches extends resource_APIResource { - /** - * Create a vector store file batch. - */ - create(vectorStoreID, body, options) { - return this._client.post(path_path `/vector_stores/${vectorStoreID}/file_batches`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a vector store file batch. - */ - retrieve(batchID, params, options) { - const { vector_store_id } = params; - return this._client.get(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Cancel a vector store file batch. This attempts to cancel the processing of - * files in this batch as soon as possible. - */ - cancel(batchID, params, options) { - const { vector_store_id } = params; - return this._client.post(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Create a vector store batch and poll until all files have been processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const batch = await this.create(vectorStoreId, body); - return await this.poll(vectorStoreId, batch.id, options); - } - /** - * Returns a list of vector store files in a batch. - */ - listFiles(batchID, params, options) { - const { vector_store_id, ...query } = params; - return this._client.getAPIList(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (CursorPage), { query, ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); - } - /** - * Wait for the given file batch to be processed. - * - * Note: this will return even if one of the files failed to process, you need to - * check batch.file_counts.failed_count to handle this case. - */ - async poll(vectorStoreID, batchID, options) { - const headers = headers_buildHeaders([ - options?.headers, - { - 'X-Stainless-Poll-Helper': 'true', - 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, - }, - ]); - while (true) { - const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { - ...options, - headers, - }).withResponse(); - switch (batch.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep_sleep(sleepInterval); - break; - case 'failed': - case 'cancelled': - case 'completed': - return batch; - } - } - } - /** - * Uploads the given files concurrently and then creates a vector store file batch. - * - * The concurrency limit is configurable using the `maxConcurrency` parameter. - */ - async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { - if (files == null || files.length == 0) { - throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); - } - const configuredConcurrency = options?.maxConcurrency ?? 5; - // We cap the number of workers at the number of files (so we don't start any unnecessary workers) - const concurrencyLimit = Math.min(configuredConcurrency, files.length); - const client = this._client; - const fileIterator = files.values(); - const allFileIds = [...fileIds]; - // This code is based on this design. The libraries don't accommodate our environment limits. - // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all - async function processFiles(iterator) { - for (let item of iterator) { - const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); - allFileIds.push(fileObj.id); - } - } - // Start workers to process results - const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); - // Wait for all processing to complete. - await allSettledWithThrow(workers); - return await this.createAndPoll(vectorStoreId, { - file_ids: allFileIds, - }); - } -} -//# sourceMappingURL=file-batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class vector_stores_files_Files extends resource_APIResource { - /** - * Create a vector store file by attaching a - * [File](https://platform.openai.com/docs/api-reference/files) to a - * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). - */ - create(vectorStoreID, body, options) { - return this._client.post(path_path `/vector_stores/${vectorStoreID}/files`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a vector store file. - */ - retrieve(fileID, params, options) { - const { vector_store_id } = params; - return this._client.get(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Update attributes on a vector store file. - */ - update(fileID, params, options) { - const { vector_store_id, ...body } = params; - return this._client.post(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of vector store files. - */ - list(vectorStoreID, query = {}, options) { - return this._client.getAPIList(path_path `/vector_stores/${vectorStoreID}/files`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete a vector store file. This will remove the file from the vector store but - * the file itself will not be deleted. To delete the file, use the - * [delete file](https://platform.openai.com/docs/api-reference/files/delete) - * endpoint. - */ - delete(fileID, params, options) { - const { vector_store_id } = params; - return this._client.delete(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * 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); - } - /** - * Wait for the vector store file to finish processing. - * - * Note: this will return even if the file failed to process, you need to check - * file.last_error and file.status to handle these cases - */ - async poll(vectorStoreID, fileID, options) { - const headers = headers_buildHeaders([ - options?.headers, - { - 'X-Stainless-Poll-Helper': 'true', - 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, - }, - ]); - while (true) { - const fileResponse = await this.retrieve(fileID, { - vector_store_id: vectorStoreID, - }, { ...options, headers }).withResponse(); - const file = fileResponse.data; - switch (file.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep_sleep(sleepInterval); - break; - case 'failed': - case 'completed': - return file; - } - } - } - /** - * Upload a file to the `files` API and then attach it to the given vector store. - * - * 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: file, 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); - return await this.poll(vectorStoreId, fileInfo.id, options); - } - /** - * Retrieve the parsed contents of a vector store file. - */ - content(fileID, params, options) { - const { vector_store_id } = params; - return this._client.getAPIList(path_path `/vector_stores/${vector_store_id}/files/${fileID}/content`, (pagination_Page), { ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); - } -} -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -class VectorStores extends resource_APIResource { - constructor() { - super(...arguments); - this.files = new vector_stores_files_Files(this._client); - this.fileBatches = new FileBatches(this._client); - } - /** - * Create a vector store. - */ - create(body, options) { - return this._client.post('/vector_stores', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a vector store. - */ - retrieve(vectorStoreID, options) { - return this._client.get(path_path `/vector_stores/${vectorStoreID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a vector store. - */ - update(vectorStoreID, body, options) { - return this._client.post(path_path `/vector_stores/${vectorStoreID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of vector stores. - */ - list(query = {}, options) { - return this._client.getAPIList('/vector_stores', (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete a vector store. - */ - delete(vectorStoreID, options) { - return this._client.delete(path_path `/vector_stores/${vectorStoreID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Search a vector store for relevant chunks based on a query and file attributes - * filter. - */ - search(vectorStoreID, body, options) { - return this._client.getAPIList(path_path `/vector_stores/${vectorStoreID}/search`, (pagination_Page), { - body, - method: 'post', - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -VectorStores.Files = vector_stores_files_Files; -VectorStores.FileBatches = FileBatches; -//# sourceMappingURL=vector-stores.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/videos.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Videos extends resource_APIResource { - /** - * Create a video - */ - create(body, options) { - return this._client.post('/videos', uploads_maybeMultipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Retrieve a video - */ - retrieve(videoID, options) { - return this._client.get(path_path `/videos/${videoID}`, options); - } - /** - * List videos - */ - list(query = {}, options) { - return this._client.getAPIList('/videos', (ConversationCursorPage), { query, ...options }); - } - /** - * Delete a video - */ - delete(videoID, options) { - return this._client.delete(path_path `/videos/${videoID}`, options); - } - /** - * Download video content - */ - downloadContent(videoID, query = {}, options) { - return this._client.get(path_path `/videos/${videoID}/content`, { - query, - ...options, - headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - __binaryResponse: true, - }); - } - /** - * Create a video remix - */ - remix(videoID, body, options) { - return this._client.post(path_path `/videos/${videoID}/remix`, uploads_maybeMultipartFormRequestOptions({ body, ...options }, this._client)); - } -} -//# sourceMappingURL=videos.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/webhooks.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader; - - - - -class Webhooks extends resource_APIResource { - constructor() { - super(...arguments); - _Webhooks_instances.add(this); - } - /** - * Validates that the given payload was sent by OpenAI and parses the payload. - */ - async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { - await this.verifySignature(payload, headers, secret, tolerance); - return JSON.parse(payload); - } - /** - * Validates whether or not the webhook payload was sent by OpenAI. - * - * An error will be raised if the webhook payload was not sent by OpenAI. - * - * @param payload - The webhook payload - * @param headers - The webhook headers - * @param secret - The webhook secret (optional, will use client secret if not provided) - * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) - */ - async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { - if (typeof crypto === 'undefined' || - typeof crypto.subtle.importKey !== 'function' || - typeof crypto.subtle.verify !== 'function') { - throw new Error('Webhook signature verification is only supported when the `crypto` global is defined'); - } - tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); - const headersObj = headers_buildHeaders([headers]).values; - const signatureHeader = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-signature'); - const timestamp = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-timestamp'); - const webhookId = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-id'); - // Validate timestamp to prevent replay attacks - const timestampSeconds = parseInt(timestamp, 10); - if (isNaN(timestampSeconds)) { - throw new InvalidWebhookSignatureError('Invalid webhook timestamp format'); - } - const nowSeconds = Math.floor(Date.now() / 1000); - if (nowSeconds - timestampSeconds > tolerance) { - throw new InvalidWebhookSignatureError('Webhook timestamp is too old'); - } - if (timestampSeconds > nowSeconds + tolerance) { - throw new InvalidWebhookSignatureError('Webhook timestamp is too new'); - } - // Extract signatures from v1, format - // The signature header can have multiple values, separated by spaces. - // Each value is in the format v1,. We should accept if any match. - const signatures = signatureHeader - .split(' ') - .map((part) => (part.startsWith('v1,') ? part.substring(3) : part)); - // Decode the secret if it starts with whsec_ - const decodedSecret = secret.startsWith('whsec_') ? - Buffer.from(secret.replace('whsec_', ''), 'base64') - : Buffer.from(secret, 'utf-8'); - // Create the signed payload: {webhook_id}.{timestamp}.{payload} - const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; - // Import the secret as a cryptographic key for HMAC - const key = await crypto.subtle.importKey('raw', decodedSecret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']); - // Check if any signature matches using timing-safe WebCrypto verify - for (const signature of signatures) { - try { - const signatureBytes = Buffer.from(signature, 'base64'); - const isValid = await crypto.subtle.verify('HMAC', key, signatureBytes, new TextEncoder().encode(signedPayload)); - if (isValid) { - return; // Valid signature found - } - } - catch { - // Invalid base64 or signature format, continue to next signature - continue; - } - } - throw new InvalidWebhookSignatureError('The given webhook signature does not match the expected signature'); - } -} -_Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) { - if (typeof secret !== 'string' || secret.length === 0) { - throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); - } -}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) { - if (!headers) { - throw new Error(`Headers are required`); - } - const value = headers.get(name); - if (value === null || value === undefined) { - throw new Error(`Missing required header: ${name}`); - } - return value; -}; -//# sourceMappingURL=webhooks.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/client.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _OpenAI_instances, client_a, _OpenAI_encoder, _OpenAI_baseURLOverridden; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/** - * API Client for interfacing with the OpenAI API. - */ -class OpenAI { - /** - * API Client for interfacing with the OpenAI API. - * - * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] - * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] - * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] - * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] - * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = env_readEnv('OPENAI_BASE_URL'), apiKey = env_readEnv('OPENAI_API_KEY'), organization = env_readEnv('OPENAI_ORG_ID') ?? null, project = env_readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = env_readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) { - _OpenAI_instances.add(this); - _OpenAI_encoder.set(this, void 0); - this.completions = new resources_completions_Completions(this); - this.chat = new Chat(this); - this.embeddings = new embeddings_Embeddings(this); - this.files = new resources_files_Files(this); - this.images = new Images(this); - this.audio = new Audio(this); - this.moderations = new Moderations(this); - this.models = new resources_models_Models(this); - this.fineTuning = new FineTuning(this); - this.graders = new graders_Graders(this); - this.vectorStores = new VectorStores(this); - this.webhooks = new Webhooks(this); - this.beta = new beta_Beta(this); - this.batches = new resources_batches_Batches(this); - this.uploads = new Uploads(this); - this.responses = new Responses(this); - this.realtime = new realtime_Realtime(this); - this.conversations = new Conversations(this); - this.evals = new Evals(this); - this.containers = new Containers(this); - this.videos = new Videos(this); - if (apiKey === undefined) { - throw new error_OpenAIError('Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.'); - } - const options = { - apiKey, - organization, - project, - webhookSecret, - ...opts, - baseURL: baseURL || `https://api.openai.com/v1`, - }; - if (!options.dangerouslyAllowBrowser && detect_platform_isRunningInBrowser()) { - throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); - } - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? client_a.DEFAULT_TIMEOUT /* 10 minutes */; - this.logger = options.logger ?? console; - const defaultLogLevel = 'warn'; - // Set default logLevel early so that we can log a warning in parseLogLevel. - this.logLevel = defaultLogLevel; - this.logLevel = - log_parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - log_parseLogLevel(env_readEnv('OPENAI_LOG'), "process.env['OPENAI_LOG']", this) ?? - defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? shims_getDefaultFetch(); - tslib_classPrivateFieldSet(this, _OpenAI_encoder, request_options_FallbackEncoder, "f"); - this._options = options; - this.apiKey = typeof apiKey === 'string' ? apiKey : 'Missing Key'; - this.organization = organization; - this.project = project; - this.webhookSecret = webhookSecret; - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - organization: this.organization, - project: this.project, - webhookSecret: this.webhookSecret, - ...options, - }); - return client; - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - return; - } - async authHeaders(opts) { - return headers_buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); - } - stringifyQuery(query) { - return stringify_stringify(query, { arrayFormat: 'brackets' }); - } - getUserAgent() { - return `${this.constructor.name}/JS ${version_VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid_uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return error_APIError.generate(status, error, message, headers); - } - async _callApiKey() { - const apiKey = this._options.apiKey; - if (typeof apiKey !== 'function') - return false; - let token; - try { - token = await apiKey(); - } - catch (err) { - if (err instanceof error_OpenAIError) - throw err; - throw new error_OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, - // @ts-ignore - { cause: err }); - } - if (typeof token !== 'string' || !token) { - throw new error_OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`); - } - this.apiKey = token; - return true; - } - buildURL(path, query, defaultBaseURL) { - const baseURL = (!tslib_classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; - const url = values_isAbsoluteURL(path) ? - new URL(path) - : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!values_isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { - await this._callApiKey(); - } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => { - return { method, path, ...opts }; - })); - } - request(options, remainingRetries = null) { - return new api_promise_APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); - } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining, - }); - await this.prepareRequest(req, { url, options }); - /** Not an API request ID, just for correlating local log entries. */ - const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); - const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - log_loggerFor(this).debug(`[${requestLogID}] sending request`, log_formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers, - })); - if (options.signal?.aborted) { - throw new error_APIUserAbortError(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new error_APIUserAbortError(); - } - // detect native connection timeout errors - // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" - // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" - // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = errors_isAbortError(response) || - /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); - if (retriesRemaining) { - log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); - log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, log_formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); - log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, log_formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - if (isTimeout) { - throw new error_APIConnectionTimeoutError(); - } - throw new error_APIConnectionError({ cause: response }); - } - const specialHeaders = [...response.headers.entries()] - .filter(([name]) => name === 'x-request-id') - .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) - .join(''); - const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - // We don't need the body of this response. - await shims_CancelReadableStream(response.body); - log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err) => errors_castToError(err).message); - const errJSON = values_safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime, - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; - } - log_loggerFor(this).info(responseInfo); - log_loggerFor(this).debug(`[${requestLogID}] response start`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null, undefined); - return new pagination_PagePromise(this, request, Page); - } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - if (signal) - signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || - (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); - const fetchOptions = { - signal: controller.signal, - ...(isReadableBody ? { duplex: 'half' } : {}), - method: 'GET', - ...options, - }; - if (method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = method.toUpperCase(); - } - try { - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - return await this.fetch.call(undefined, url, fetchOptions); - } - finally { - clearTimeout(timeout); - } - } - async shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') - return true; - if (shouldRetryHeader === 'false') - return false; - // Retry on request timeouts. - if (response.status === 408) - return true; - // Retry on lock timeouts. - if (response.status === 409) - return true; - // Retry on rate limits. - if (response.status === 429) - return true; - // Retry internal errors. - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. - const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - const retryAfterHeader = responseHeaders?.get('retry-after'); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; - } - else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep_sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8.0; - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - // Apply some jitter, take up to at most 25 percent of the retry time. - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, defaultBaseURL } = options; - const url = this.buildURL(path, query, defaultBaseURL); - if ('timeout' in options) - values_validatePositiveInteger('timeout', options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...(options.signal && { signal: options.signal }), - ...(globalThis.ReadableStream && - body instanceof globalThis.ReadableStream && { duplex: 'half' }), - ...(body && { body }), - ...(this.fetchOptions ?? {}), - ...(options.fetchOptions ?? {}), - }; - return { req, url, timeout: options.timeout }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount, }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== 'get') { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = headers_buildHeaders([ - idempotencyHeaders, - { - Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...detect_platform_getPlatformHeaders(), - 'OpenAI-Organization': this.organization, - 'OpenAI-Project': this.project, - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers, - ]); - this.validateHeaders(headers); - return headers.values; - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: undefined, body: undefined }; - } - const headers = headers_buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || - body instanceof ArrayBuffer || - body instanceof DataView || - (typeof body === 'string' && - // Preserve legacy string encoding behavior for now - headers.values.has('content-type')) || - // `Blob` is superset of `File` - (globalThis.Blob && body instanceof globalThis.Blob) || - // `FormData` -> `multipart/form-data` - body instanceof FormData || - // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || - // Send chunked stream (each chunk has own `length`) - (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { - return { bodyHeaders: undefined, body: body }; - } - else if (typeof body === 'object' && - (Symbol.asyncIterator in body || - (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; - } - else { - return tslib_classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }); - } - } -} -client_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() { - return this.baseURL !== 'https://api.openai.com/v1'; -}; -OpenAI.OpenAI = client_a; -OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes -OpenAI.OpenAIError = error_OpenAIError; -OpenAI.APIError = error_APIError; -OpenAI.APIConnectionError = error_APIConnectionError; -OpenAI.APIConnectionTimeoutError = error_APIConnectionTimeoutError; -OpenAI.APIUserAbortError = error_APIUserAbortError; -OpenAI.NotFoundError = error_NotFoundError; -OpenAI.ConflictError = error_ConflictError; -OpenAI.RateLimitError = error_RateLimitError; -OpenAI.BadRequestError = error_BadRequestError; -OpenAI.AuthenticationError = error_AuthenticationError; -OpenAI.InternalServerError = error_InternalServerError; -OpenAI.PermissionDeniedError = error_PermissionDeniedError; -OpenAI.UnprocessableEntityError = error_UnprocessableEntityError; -OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; -OpenAI.toFile = to_file_toFile; -OpenAI.Completions = resources_completions_Completions; -OpenAI.Chat = Chat; -OpenAI.Embeddings = embeddings_Embeddings; -OpenAI.Files = resources_files_Files; -OpenAI.Images = Images; -OpenAI.Audio = Audio; -OpenAI.Moderations = Moderations; -OpenAI.Models = resources_models_Models; -OpenAI.FineTuning = FineTuning; -OpenAI.Graders = graders_Graders; -OpenAI.VectorStores = VectorStores; -OpenAI.Webhooks = Webhooks; -OpenAI.Beta = beta_Beta; -OpenAI.Batches = resources_batches_Batches; -OpenAI.Uploads = Uploads; -OpenAI.Responses = Responses; -OpenAI.Realtime = realtime_Realtime; -OpenAI.Conversations = Conversations; -OpenAI.Evals = Evals; -OpenAI.Containers = Containers; -OpenAI.Videos = Videos; -//# sourceMappingURL=client.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/azure.mjs - - - - -/** API Client for interfacing with the Azure OpenAI API. */ -class AzureOpenAI extends OpenAI { - /** - * API Client for interfacing with the Azure OpenAI API. - * - * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] - * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` - * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] - * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. - * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] - * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = env_readEnv('OPENAI_BASE_URL'), apiKey = env_readEnv('AZURE_OPENAI_API_KEY'), apiVersion = env_readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { - if (!apiVersion) { - throw new error_OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); - } - if (typeof azureADTokenProvider === 'function') { - dangerouslyAllowBrowser = true; - } - if (!azureADTokenProvider && !apiKey) { - throw new error_OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); - } - if (azureADTokenProvider && apiKey) { - throw new error_OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); - } - opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; - if (!baseURL) { - if (!endpoint) { - endpoint = process.env['AZURE_OPENAI_ENDPOINT']; - } - if (!endpoint) { - throw new error_OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); - } - baseURL = `${endpoint}/openai`; - } - else { - if (endpoint) { - throw new error_OpenAIError('baseURL and endpoint are mutually exclusive'); - } - } - super({ - apiKey: azureADTokenProvider ?? apiKey, - baseURL, - ...opts, - ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), - }); - this.apiVersion = ''; - this.apiVersion = apiVersion; - this.deploymentName = deployment; - } - async buildRequest(options, props = {}) { - if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { - if (!values_isObj(options.body)) { - throw new Error('Expected request body to be an object'); - } - const model = this.deploymentName || options.body['model'] || options.__metadata?.['model']; - if (model !== undefined && !this.baseURL.includes('/deployments')) { - options.path = `/deployments/${model}${options.path}`; - } - } - return super.buildRequest(options, props); - } - async authHeaders(opts) { - if (typeof this._options.apiKey === 'string') { - return headers_buildHeaders([{ 'api-key': this.apiKey }]); - } - return super.authHeaders(opts); - } -} -const _deployments_endpoints = new Set([ - '/completions', - '/chat/completions', - '/embeddings', - '/audio/transcriptions', - '/audio/translations', - '/audio/speech', - '/images/generations', - '/batches', - '/images/edits', -]); -//# sourceMappingURL=azure.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/base.js - - - - - - - - - - - - - - -//#region src/chat_models/base.ts -/** @internal */ -var BaseChatOpenAI = class extends BaseChatModel { - temperature; - topP; - frequencyPenalty; - presencePenalty; - n; - logitBias; - model = "gpt-3.5-turbo"; - modelKwargs; - stop; - stopSequences; - user; - timeout; - streaming = false; - streamUsage = true; - maxTokens; - logprobs; - topLogprobs; - apiKey; - organization; - __includeRawResponse; - /** @internal */ - client; - /** @internal */ - clientConfig; - /** - * Whether the model supports the `strict` argument when passing in tools. - * If `undefined` the `strict` argument will not be passed to OpenAI. - */ - supportsStrictToolCalling; - audio; - modalities; - reasoning; - /** - * Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable - * output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your - * OpenAI organization or project. This must be configured directly with OpenAI. - * - * See: - * https://platform.openai.com/docs/guides/your-data - * https://platform.openai.com/docs/api-reference/responses/create#responses-create-store - * - * @default false - */ - zdrEnabled; - /** - * Service tier to use for this request. Can be "auto", "default", or "flex" or "priority". - * Specifies the service tier for prioritization and latency optimization. - */ - service_tier; - /** - * Used by OpenAI to cache responses for similar requests to optimize your cache - * hit rates. - * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). - */ - promptCacheKey; - /** - * The verbosity of the model's response. - */ - verbosity; - defaultOptions; - _llmType() { - return "openai"; - } - static lc_name() { - return "ChatOpenAI"; - } - get callKeys() { - return [ - ...super.callKeys, - "options", - "function_call", - "functions", - "tools", - "tool_choice", - "promptIndex", - "response_format", - "seed", - "reasoning", - "service_tier" - ]; - } - lc_serializable = true; - get lc_secrets() { - return { - apiKey: "OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION" - }; - } - get lc_aliases() { - return { - apiKey: "openai_api_key", - modelName: "model" - }; - } - get lc_serializable_keys() { - return [ - "configuration", - "logprobs", - "topLogprobs", - "prefixMessages", - "supportsStrictToolCalling", - "modalities", - "audio", - "temperature", - "maxTokens", - "topP", - "frequencyPenalty", - "presencePenalty", - "n", - "logitBias", - "user", - "streaming", - "streamUsage", - "model", - "modelName", - "modelKwargs", - "stop", - "stopSequences", - "timeout", - "apiKey", - "cache", - "maxConcurrency", - "maxRetries", - "verbose", - "callbacks", - "tags", - "metadata", - "disableStreaming", - "zdrEnabled", - "reasoning", - "promptCacheKey", - "verbosity" - ]; - } - getLsParams(options) { - const params = this.invocationParams(options); - return { - ls_provider: "openai", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: params.temperature ?? void 0, - ls_max_tokens: params.max_tokens ?? void 0, - ls_stop: options.stop - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams(), - ...this.clientConfig - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return this._identifyingParams(); - } - constructor(fields) { - super(fields ?? {}); - const configApiKey = typeof fields?.configuration?.apiKey === "string" ? fields?.configuration?.apiKey : void 0; - this.apiKey = fields?.apiKey ?? configApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - this.model = fields?.model ?? fields?.modelName ?? this.model; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.logprobs = fields?.logprobs; - this.topLogprobs = fields?.topLogprobs; - this.n = fields?.n ?? this.n; - this.logitBias = fields?.logitBias; - this.stop = fields?.stopSequences ?? fields?.stop; - this.stopSequences = this.stop; - this.user = fields?.user; - this.__includeRawResponse = fields?.__includeRawResponse; - this.audio = fields?.audio; - this.modalities = fields?.modalities; - this.reasoning = fields?.reasoning; - this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens; - this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey; - this.verbosity = fields?.verbosity ?? this.verbosity; - this.disableStreaming = fields?.disableStreaming === true; - this.streaming = fields?.streaming === true; - if (this.disableStreaming) this.streaming = false; - if (fields?.streaming === false) this.disableStreaming = true; - this.streamUsage = fields?.streamUsage ?? this.streamUsage; - if (this.disableStreaming) this.streamUsage = false; - this.clientConfig = { - apiKey: this.apiKey, - organization: this.organization, - dangerouslyAllowBrowser: true, - ...fields?.configuration - }; - if (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling; - if (fields?.service_tier !== void 0) this.service_tier = fields.service_tier; - this.zdrEnabled = fields?.zdrEnabled ?? false; - } - /** - * Returns backwards compatible reasoning parameters from constructor params and call options - * @internal - */ - _getReasoningParams(options) { - if (!isReasoningModel(this.model)) return; - let reasoning; - if (this.reasoning !== void 0) reasoning = { - ...reasoning, - ...this.reasoning - }; - if (options?.reasoning !== void 0) reasoning = { - ...reasoning, - ...options.reasoning - }; - return reasoning; - } - /** - * Returns an openai compatible response format from a set of options - * @internal - */ - _getResponseFormat(resFormat) { - if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && isInteropZodSchema(resFormat.json_schema.schema)) return interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description }); - return resFormat; - } - _combineCallOptions(additionalOptions) { - return { - ...this.defaultOptions, - ...additionalOptions ?? {} - }; - } - /** @internal */ - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!params.baseURL) delete params.baseURL; - this.client = new OpenAI(params); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - return requestOptions; - } - _convertChatOpenAIToolToCompletionsTool(tool, fields) { - if (isCustomTool(tool)) return convertResponsesCustomTool(tool.metadata.customTool); - if (isOpenAITool(tool)) { - if (fields?.strict !== void 0) return { - ...tool, - function: { - ...tool.function, - strict: fields.strict - } - }; - return tool; - } - return _convertToOpenAITool(tool, fields); - } - bindTools(tools, kwargs) { - let strict; - if (kwargs?.strict !== void 0) strict = kwargs.strict; - else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; - return this.withConfig({ - tools: tools.map((tool) => isBuiltInTool(tool) || isCustomTool(tool) ? tool : this._convertChatOpenAIToolToCompletionsTool(tool, { strict })), - ...kwargs - }); - } - async stream(input, options) { - return super.stream(input, this._combineCallOptions(options)); - } - async invoke(input, options) { - return super.invoke(input, this._combineCallOptions(options)); - } - /** @ignore */ - _combineLLMOutput(...llmOutputs) { - return llmOutputs.reduce((acc, llmOutput) => { - if (llmOutput && llmOutput.tokenUsage) { - acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0; - acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; - acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; - } - return acc; - }, { tokenUsage: { - completionTokens: 0, - promptTokens: 0, - totalTokens: 0 - } }); - } - async getNumTokensFromMessages(messages) { - let totalCount = 0; - let tokensPerMessage = 0; - let tokensPerName = 0; - if (this.model === "gpt-3.5-turbo-0301") { - tokensPerMessage = 4; - tokensPerName = -1; - } else { - tokensPerMessage = 3; - tokensPerName = 1; - } - const countPerMessage = await Promise.all(messages.map(async (message) => { - const textCount = await this.getNumTokens(message.content); - const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); - const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0; - let count = textCount + tokensPerMessage + roleCount + nameCount; - const openAIMessage = message; - if (openAIMessage._getType() === "function") count -= 2; - if (openAIMessage.additional_kwargs?.function_call) count += 3; - if (openAIMessage?.additional_kwargs.function_call?.name) count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name); - if (openAIMessage.additional_kwargs.function_call?.arguments) try { - count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments))); - } catch (error) { - console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call)); - count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments); - } - totalCount += count; - return count; - })); - totalCount += 3; - return { - totalCount, - countPerMessage - }; - } - /** @internal */ - async _getNumTokensFromGenerations(generations) { - const generationUsages = await Promise.all(generations.map(async (generation) => { - if (generation.message.additional_kwargs?.function_call) return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0]; - else return await this.getNumTokens(generation.message.content); - })); - return generationUsages.reduce((a, b) => a + b, 0); - } - /** @internal */ - async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) { - let tokens = (await this.getNumTokensFromMessages(messages)).totalCount; - if (functions && function_call !== "auto") { - const promptDefinitions = formatFunctionDefinitions(functions); - tokens += await this.getNumTokens(promptDefinitions); - tokens += 9; - } - if (functions && messages.find((m) => m._getType() === "system")) tokens -= 4; - if (function_call === "none") tokens += 1; - else if (typeof function_call === "object") tokens += await this.getNumTokens(function_call.name) + 4; - return tokens; - } - /** @internal */ - _getStructuredOutputMethod(config) { - const ensuredConfig = { ...config }; - if (!this.model.startsWith("gpt-3") && !this.model.startsWith("gpt-4-") && this.model !== "gpt-4") { - if (ensuredConfig?.method === void 0) return "jsonSchema"; - } else if (ensuredConfig.method === "jsonSchema") console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`); - return ensuredConfig.method; - } - /** - * Add structured output to the model. - * - * The OpenAI model family supports the following structured output methods: - * - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`, - * `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later. - * - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality - * of your application. - * - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model - * output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify. - * We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case. - * - * The default method is `functionCalling`. - * - * @see https://platform.openai.com/docs/guides/structured-outputs - * @param outputSchema - The schema to use for structured output. - * @param config - The structured output method options. - * @returns The model with structured output. - */ - withStructuredOutput(outputSchema, config) { - let llm; - let outputParser; - const { schema, name, includeRaw } = { - ...config, - schema: outputSchema - }; - if (config?.strict !== void 0 && config.method === "jsonMode") throw new Error("Argument `strict` is only supported for `method` = 'function_calling'"); - const method = getStructuredOutputMethod(this.model, config?.method); - if (method === "jsonMode") { - if (isInteropZodSchema(schema)) outputParser = StructuredOutputParser.fromZodSchema(schema); - else outputParser = new JsonOutputParser(); - const asJsonSchema = toJsonSchema(schema); - llm = this.withConfig({ - outputVersion: "v0", - response_format: { type: "json_object" }, - ls_structured_output_format: { - kwargs: { method: "json_mode" }, - schema: { - title: name ?? "extract", - ...asJsonSchema - } - } - }); - } else if (method === "jsonSchema") { - const openaiJsonSchemaParams = { - name: name ?? "extract", - description: getSchemaDescription(schema), - schema, - strict: config?.strict - }; - const asJsonSchema = toJsonSchema(openaiJsonSchemaParams.schema); - llm = this.withConfig({ - outputVersion: "v0", - response_format: { - type: "json_schema", - json_schema: openaiJsonSchemaParams - }, - ls_structured_output_format: { - kwargs: { method: "json_schema" }, - schema: { - title: openaiJsonSchemaParams.name, - description: openaiJsonSchemaParams.description, - ...asJsonSchema - } - } - }); - if (isInteropZodSchema(schema)) { - const altParser = StructuredOutputParser.fromZodSchema(schema); - outputParser = RunnableLambda.from((aiMessage) => { - if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed; - return altParser; - }); - } else outputParser = new JsonOutputParser(); - } else { - let functionName = name ?? "extract"; - if (isInteropZodSchema(schema)) { - const asJsonSchema = toJsonSchema(schema); - llm = this.withConfig({ - outputVersion: "v0", - tools: [{ - type: "function", - function: { - name: functionName, - description: asJsonSchema.description, - parameters: asJsonSchema - } - }], - tool_choice: { - type: "function", - function: { name: functionName } - }, - ls_structured_output_format: { - kwargs: { method: "function_calling" }, - schema: { - title: functionName, - ...asJsonSchema - } - }, - ...config?.strict !== void 0 ? { strict: config.strict } : {} - }); - outputParser = new JsonOutputKeyToolsParser({ - returnSingle: true, - keyName: functionName, - zodSchema: schema - }); - } else { - let openAIFunctionDefinition; - if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { - openAIFunctionDefinition = schema; - functionName = schema.name; - } else { - functionName = schema.title ?? functionName; - openAIFunctionDefinition = { - name: functionName, - description: schema.description ?? "", - parameters: schema - }; - } - const asJsonSchema = toJsonSchema(schema); - llm = this.withConfig({ - outputVersion: "v0", - tools: [{ - type: "function", - function: openAIFunctionDefinition - }], - tool_choice: { - type: "function", - function: { name: functionName } - }, - ls_structured_output_format: { - kwargs: { method: "function_calling" }, - schema: { - title: functionName, - ...asJsonSchema - } - }, - ...config?.strict !== void 0 ? { strict: config.strict } : {} - }); - outputParser = new JsonOutputKeyToolsParser({ - returnSingle: true, - keyName: functionName - }); - } - } - if (!includeRaw) return llm.pipe(outputParser); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/errors.js -//#region src/utils/errors.ts -function utils_errors_addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`; - return error; -} - -//#endregion - -//# sourceMappingURL=errors.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/client.js - - - -//#region src/utils/client.ts -function wrapOpenAIClientError(e) { - if (!e || typeof e !== "object") return e; - let error; - if (e.constructor.name === error_APIConnectionTimeoutError.name && "message" in e && typeof e.message === "string") { - error = new Error(e.message); - error.name = "TimeoutError"; - } else if (e.constructor.name === error_APIUserAbortError.name && "message" in e && typeof e.message === "string") { - error = new Error(e.message); - error.name = "AbortError"; - } else if ("status" in e && e.status === 400 && "message" in e && typeof e.message === "string" && e.message.includes("tool_calls")) error = utils_errors_addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); - else if ("status" in e && e.status === 401) error = utils_errors_addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); - else if ("status" in e && e.status === 429) error = utils_errors_addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); - else if ("status" in e && e.status === 404) error = utils_errors_addLangChainErrorFields(e, "MODEL_NOT_FOUND"); - else error = e; - return error; -} - -//#endregion - -//# sourceMappingURL=client.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/standard.js - - - -//#region src/utils/standard.ts -function _convertToChatCompletionsData(block) { - if (block.type === "image") { - if (block.url) return { - type: "image_url", - image_url: { url: block.url } - }; - else if (block.data) return { - type: "image_url", - image_url: { url: `data:${block.mimeType};base64,${block.data}` } - }; - } - if (block.type === "audio") { - if (block.data) { - const format = misc_iife(() => { - const [, format$1] = block.mimeType.split("/"); - if (format$1 === "wav" || format$1 === "mp3") return format$1; - return "wav"; - }); - return { - type: "input_audio", - input_audio: { - data: block.data.toString(), - format - } - }; - } - } - if (block.type === "file") { - if (block.data) return { - type: "file", - file: { file_data: block.data.toString() } - }; - if (block.fileId) return { - type: "file", - file: { file_id: block.fileId } - }; - } - return void 0; -} -function _convertToCompletionsMessageFromV1(message, model) { - let role = messageToOpenAIRole(message); - if (role === "system" && isReasoningModel(model)) role = "developer"; - if (role === "developer") return { - role: "developer", - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "system") return { - role: "system", - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "assistant") return { - role: "assistant", - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "tool" && ToolMessage.isInstance(message)) return { - role: "tool", - tool_call_id: message.tool_call_id, - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "function") return { - role: "function", - name: message.name ?? "", - content: message.contentBlocks.filter((block) => block.type === "text").join("") - }; - function* iterateUserContent(blocks) { - for (const block of blocks) { - if (block.type === "text") yield { - type: "text", - text: block.text - }; - const data = _convertToChatCompletionsData(block); - if (data) yield data; - } - } - return { - role: "user", - content: Array.from(iterateUserContent(message.contentBlocks)) - }; -} -function _convertToResponsesMessageFromV1(message) { - const isResponsesMessage = isAIMessage(message) && message.response_metadata?.model_provider === "openai"; - function* iterateItems() { - const messageRole = misc_iife(() => { - try { - const role = messageToOpenAIRole(message); - if (role === "system" || role === "developer" || role === "assistant" || role === "user") return role; - return "assistant"; - } catch { - return "assistant"; - } - }); - let currentMessage = void 0; - const functionCallIdsWithBlocks = /* @__PURE__ */ new Set(); - const serverFunctionCallIdsWithBlocks = /* @__PURE__ */ new Set(); - const pendingFunctionChunks = /* @__PURE__ */ new Map(); - const pendingServerFunctionChunks = /* @__PURE__ */ new Map(); - function* flushMessage() { - if (!currentMessage) return; - const content = currentMessage.content; - if (typeof content === "string" && content.length > 0 || Array.isArray(content) && content.length > 0) yield currentMessage; - currentMessage = void 0; - } - const pushMessageContent = (content) => { - if (!currentMessage) currentMessage = { - type: "message", - role: messageRole, - content: [] - }; - if (typeof currentMessage.content === "string") currentMessage.content = currentMessage.content.length > 0 ? [{ - type: "input_text", - text: currentMessage.content - }, ...content] : [...content]; - else currentMessage.content.push(...content); - }; - const toJsonString = (value) => { - if (typeof value === "string") return value; - try { - return JSON.stringify(value ?? {}); - } catch { - return "{}"; - } - }; - const resolveImageItem = (block) => { - const detail = misc_iife(() => { - const raw = block.metadata?.detail; - if (raw === "low" || raw === "high" || raw === "auto") return raw; - return "auto"; - }); - if (block.fileId) return { - type: "input_image", - detail, - file_id: block.fileId - }; - if (block.url) return { - type: "input_image", - detail, - image_url: block.url - }; - if (block.data) { - const base64Data = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); - const mimeType = block.mimeType ?? "image/png"; - return { - type: "input_image", - detail, - image_url: `data:${mimeType};base64,${base64Data}` - }; - } - return void 0; - }; - const resolveFileItem = (block) => { - const filename = block.metadata?.filename ?? block.metadata?.name ?? block.metadata?.title; - if (block.fileId && typeof filename === "string") return { - type: "input_file", - file_id: block.fileId, - ...filename ? { filename } : {} - }; - if (block.url && typeof filename === "string") return { - type: "input_file", - file_url: block.url, - ...filename ? { filename } : {} - }; - if (block.data && typeof filename === "string") { - const encoded = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); - const mimeType = block.mimeType ?? "application/octet-stream"; - return { - type: "input_file", - file_data: `data:${mimeType};base64,${encoded}`, - ...filename ? { filename } : {} - }; - } - return void 0; - }; - const convertReasoningBlock = (block) => { - const summaryEntries = misc_iife(() => { - if (Array.isArray(block.summary)) { - const candidate = block.summary; - const mapped = candidate?.map((item) => item?.text).filter((text) => typeof text === "string") ?? []; - if (mapped.length > 0) return mapped; - } - return block.reasoning ? [block.reasoning] : []; - }); - const summary = summaryEntries.length > 0 ? summaryEntries.map((text) => ({ - type: "summary_text", - text - })) : [{ - type: "summary_text", - text: "" - }]; - const reasoningItem = { - type: "reasoning", - id: block.id ?? "", - summary - }; - if (block.reasoning) reasoningItem.content = [{ - type: "reasoning_text", - text: block.reasoning - }]; - return reasoningItem; - }; - const convertFunctionCall = (block) => ({ - type: "function_call", - name: block.name ?? "", - call_id: block.id ?? "", - arguments: toJsonString(block.args) - }); - const convertFunctionCallOutput = (block) => { - const output = toJsonString(block.output); - const status = block.status === "success" ? "completed" : block.status === "error" ? "incomplete" : void 0; - return { - type: "function_call_output", - call_id: block.toolCallId ?? "", - output, - ...status ? { status } : {} - }; - }; - for (const block of message.contentBlocks) if (block.type === "text") pushMessageContent([{ - type: "input_text", - text: block.text - }]); - else if (block.type === "invalid_tool_call") {} else if (block.type === "reasoning") { - yield* flushMessage(); - yield convertReasoningBlock(block); - } else if (block.type === "tool_call") { - yield* flushMessage(); - const id = block.id ?? ""; - if (id) { - functionCallIdsWithBlocks.add(id); - pendingFunctionChunks.delete(id); - } - yield convertFunctionCall(block); - } else if (block.type === "tool_call_chunk") { - if (block.id) { - const existing = pendingFunctionChunks.get(block.id) ?? { - name: block.name, - args: [] - }; - if (block.name) existing.name = block.name; - if (block.args) existing.args.push(block.args); - pendingFunctionChunks.set(block.id, existing); - } - } else if (block.type === "server_tool_call") { - yield* flushMessage(); - const id = block.id ?? ""; - if (id) { - serverFunctionCallIdsWithBlocks.add(id); - pendingServerFunctionChunks.delete(id); - } - yield convertFunctionCall(block); - } else if (block.type === "server_tool_call_chunk") { - if (block.id) { - const existing = pendingServerFunctionChunks.get(block.id) ?? { - name: block.name, - args: [] - }; - if (block.name) existing.name = block.name; - if (block.args) existing.args.push(block.args); - pendingServerFunctionChunks.set(block.id, existing); - } - } else if (block.type === "server_tool_call_result") { - yield* flushMessage(); - yield convertFunctionCallOutput(block); - } else if (block.type === "audio") {} else if (block.type === "file") { - const fileItem = resolveFileItem(block); - if (fileItem) pushMessageContent([fileItem]); - } else if (block.type === "image") { - const imageItem = resolveImageItem(block); - if (imageItem) pushMessageContent([imageItem]); - } else if (block.type === "video") { - const videoItem = resolveFileItem(block); - if (videoItem) pushMessageContent([videoItem]); - } else if (block.type === "text-plain") { - if (block.text) pushMessageContent([{ - type: "input_text", - text: block.text - }]); - } else if (block.type === "non_standard" && isResponsesMessage) { - yield* flushMessage(); - yield block.value; - } - yield* flushMessage(); - for (const [id, chunk] of pendingFunctionChunks) { - if (!id || functionCallIdsWithBlocks.has(id)) continue; - const args = chunk.args.join(""); - if (!chunk.name && !args) continue; - yield { - type: "function_call", - call_id: id, - name: chunk.name ?? "", - arguments: args - }; - } - for (const [id, chunk] of pendingServerFunctionChunks) { - if (!id || serverFunctionCallIdsWithBlocks.has(id)) continue; - const args = chunk.args.join(""); - if (!chunk.name && !args) continue; - yield { - type: "function_call", - call_id: id, - name: chunk.name ?? "", - arguments: args - }; - } - } - return Array.from(iterateItems()); -} - -//#endregion - -//# sourceMappingURL=standard.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/message_inputs.js - - - - - -//#region src/utils/message_inputs.ts -const completionsApiContentBlockConverter = { - providerName: "ChatOpenAI", - fromStandardTextBlock(block) { - return { - type: "text", - text: block.text - }; - }, - fromStandardImageBlock(block) { - if (block.source_type === "url") return { - type: "image_url", - image_url: { - url: block.url, - ...block.metadata?.detail ? { detail: block.metadata.detail } : {} - } - }; - if (block.source_type === "base64") { - const url = `data:${block.mime_type ?? ""};base64,${block.data}`; - return { - type: "image_url", - image_url: { - url, - ...block.metadata?.detail ? { detail: block.metadata.detail } : {} - } - }; - } - throw new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); - }, - fromStandardAudioBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (!data) throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); - const rawMimeType = data.mime_type || block.mime_type || ""; - let mimeType; - try { - mimeType = parseMimeType(rawMimeType); - } catch { - throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - } - if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - return { - type: "input_audio", - input_audio: { - format: mimeType.subtype, - data: data.data - } - }; - } - if (block.source_type === "base64") { - let mimeType; - try { - mimeType = parseMimeType(block.mime_type ?? ""); - } catch { - throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - } - if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - return { - type: "input_audio", - input_audio: { - format: mimeType.subtype, - data: block.data - } - }; - } - throw new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); - }, - fromStandardFileBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (!data) throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); - return { - type: "file", - file: { - file_data: block.url, - ...block.metadata?.filename || block.metadata?.name ? { filename: block.metadata?.filename || block.metadata?.name } : {} - } - }; - } - if (block.source_type === "base64") return { - type: "file", - file: { - file_data: `data:${block.mime_type ?? ""};base64,${block.data}`, - ...block.metadata?.filename || block.metadata?.name || block.metadata?.title ? { filename: block.metadata?.filename || block.metadata?.name || block.metadata?.title } : {} - } - }; - if (block.source_type === "id") return { - type: "file", - file: { file_id: block.id } - }; - throw new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); - } -}; -function message_inputs_convertMessagesToOpenAIParams(messages, model) { - return messages.flatMap((message) => { - if ("output_version" in message.response_metadata && message.response_metadata?.output_version === "v1") return _convertToCompletionsMessageFromV1(message); - let role = messageToOpenAIRole(message); - if (role === "system" && isReasoningModel(model)) role = "developer"; - const content = typeof message.content === "string" ? message.content : message.content.map((m) => { - if (isDataContentBlock(m)) return convertToProviderContentBlock(m, completionsApiContentBlockConverter); - return m; - }); - const completionParam = { - role, - content - }; - if (message.name != null) completionParam.name = message.name; - if (message.additional_kwargs.function_call != null) { - completionParam.function_call = message.additional_kwargs.function_call; - completionParam.content = ""; - } - if (isAIMessage(message) && !!message.tool_calls?.length) { - completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI); - completionParam.content = ""; - } else { - if (message.additional_kwargs.tool_calls != null) completionParam.tool_calls = message.additional_kwargs.tool_calls; - if (message.tool_call_id != null) completionParam.tool_call_id = message.tool_call_id; - } - if (message.additional_kwargs.audio && typeof message.additional_kwargs.audio === "object" && "id" in message.additional_kwargs.audio) { - const audioMessage = { - role: "assistant", - audio: { id: message.additional_kwargs.audio.id } - }; - return [completionParam, audioMessage]; - } - return completionParam; - }); -} - -//#endregion - -//# sourceMappingURL=message_inputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/responses.js - - - - - - - - - - - - -//#region src/chat_models/responses.ts -const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"; -/** -* OpenAI Responses API implementation. -* -* Will be exported in a later version of @langchain/openai. -* -* @internal -*/ -var ChatOpenAIResponses = class extends BaseChatOpenAI { - invocationParams(options) { - let strict; - if (options?.strict !== void 0) strict = options.strict; - else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; - const params = { - model: this.model, - temperature: this.temperature, - top_p: this.topP, - user: this.user, - stream: this.streaming, - previous_response_id: options?.previous_response_id, - truncation: options?.truncation, - include: options?.include, - tools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, { - stream: this.streaming, - strict - }) : void 0, - tool_choice: isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => { - const formatted = formatToOpenAIToolChoice(options?.tool_choice); - if (typeof formatted === "object" && "type" in formatted) { - if (formatted.type === "function") return { - type: "function", - name: formatted.function.name - }; - else if (formatted.type === "allowed_tools") return { - type: "allowed_tools", - mode: formatted.allowed_tools.mode, - tools: formatted.allowed_tools.tools - }; - else if (formatted.type === "custom") return { - type: "custom", - name: formatted.custom.name - }; - } - return void 0; - })(), - text: (() => { - if (options?.text) return options.text; - const format = this._getResponseFormat(options?.response_format); - if (format?.type === "json_schema") { - if (format.json_schema.schema != null) return { - format: { - type: "json_schema", - schema: format.json_schema.schema, - description: format.json_schema.description, - name: format.json_schema.name, - strict: format.json_schema.strict - }, - verbosity: options?.verbosity - }; - return void 0; - } - return { - format, - verbosity: options?.verbosity - }; - })(), - parallel_tool_calls: options?.parallel_tool_calls, - max_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, - prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, - ...this.zdrEnabled ? { store: false } : {}, - ...this.modelKwargs - }; - const reasoning = this._getReasoningParams(options); - if (reasoning !== void 0) params.reasoning = reasoning; - return params; - } - async _generate(messages, options) { - const invocationParams = this.invocationParams(options); - if (invocationParams.stream) { - const stream = this._streamResponseChunks(messages, options); - let finalChunk; - for await (const chunk of stream) { - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - finalChunk = finalChunk?.concat(chunk) ?? chunk; - } - return { - generations: finalChunk ? [finalChunk] : [], - llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata } - }; - } else { - const input = this._convertMessagesToResponsesParams(messages); - const data = await this.completionWithRetry({ - input, - ...invocationParams, - stream: false - }, { - signal: options?.signal, - ...options?.options - }); - return { - generations: [{ - text: data.output_text, - message: this._convertResponsesMessageToBaseMessage(data) - }], - llmOutput: { - id: data.id, - estimatedTokenUsage: data.usage ? { - promptTokens: data.usage.input_tokens, - completionTokens: data.usage.output_tokens, - totalTokens: data.usage.total_tokens - } : void 0 - } - }; - } - } - async *_streamResponseChunks(messages, options, runManager) { - const streamIterable = await this.completionWithRetry({ - ...this.invocationParams(options), - input: this._convertMessagesToResponsesParams(messages), - stream: true - }, options); - for await (const data of streamIterable) { - const chunk = this._convertResponsesDeltaToBaseMessageChunk(data); - if (chunk == null) continue; - yield chunk; - await runManager?.handleLLMNewToken(chunk.text || "", { - prompt: options.promptIndex ?? 0, - completion: 0 - }, void 0, void 0, void 0, { chunk }); - } - } - async completionWithRetry(request, requestOptions) { - return this.caller.call(async () => { - const clientOptions = this._getClientOptions(requestOptions); - try { - if (request.text?.format?.type === "json_schema" && !request.stream) return await this.client.responses.parse(request, clientOptions); - return await this.client.responses.create(request, clientOptions); - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** @internal */ - _convertResponsesMessageToBaseMessage(response) { - if (response.error) { - const error = new Error(response.error.message); - error.name = response.error.code; - throw error; - } - let messageId; - const content = []; - const tool_calls = []; - const invalid_tool_calls = []; - const response_metadata = { - model_provider: "openai", - model: response.model, - created_at: response.created_at, - id: response.id, - incomplete_details: response.incomplete_details, - metadata: response.metadata, - object: response.object, - status: response.status, - user: response.user, - service_tier: response.service_tier, - model_name: response.model - }; - const additional_kwargs = {}; - for (const item of response.output) if (item.type === "message") { - messageId = item.id; - content.push(...item.content.flatMap((part) => { - if (part.type === "output_text") { - if ("parsed" in part && part.parsed != null) additional_kwargs.parsed = part.parsed; - return { - type: "text", - text: part.text, - annotations: part.annotations - }; - } - if (part.type === "refusal") { - additional_kwargs.refusal = part.refusal; - return []; - } - return part; - })); - } else if (item.type === "function_call") { - const fnAdapter = { - function: { - name: item.name, - arguments: item.arguments - }, - id: item.call_id - }; - try { - tool_calls.push(parseToolCall(fnAdapter, { returnId: true })); - } catch (e) { - let errMessage; - if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message; - invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage)); - } - additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {}; - if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id; - } else if (item.type === "reasoning") additional_kwargs.reasoning = item; - else if (item.type === "custom_tool_call") { - const parsed = parseCustomToolCall(item); - if (parsed) tool_calls.push(parsed); - else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed custom tool call")); - } else { - additional_kwargs.tool_outputs ??= []; - additional_kwargs.tool_outputs.push(item); - } - return new AIMessage({ - id: messageId, - content, - tool_calls, - invalid_tool_calls, - usage_metadata: _convertOpenAIResponsesUsageToLangChainUsage(response.usage), - additional_kwargs, - response_metadata - }); - } - /** @internal */ - _convertResponsesDeltaToBaseMessageChunk(chunk) { - const content = []; - let generationInfo = {}; - let usage_metadata; - const tool_call_chunks = []; - const response_metadata = { model_provider: "openai" }; - const additional_kwargs = {}; - let id; - if (chunk.type === "response.output_text.delta") content.push({ - type: "text", - text: chunk.delta, - index: chunk.content_index - }); - else if (chunk.type === "response.output_text.annotation.added") content.push({ - type: "text", - text: "", - annotations: [chunk.annotation], - index: chunk.content_index - }); - else if (chunk.type === "response.output_item.added" && chunk.item.type === "message") id = chunk.item.id; - else if (chunk.type === "response.output_item.added" && chunk.item.type === "function_call") { - tool_call_chunks.push({ - type: "tool_call_chunk", - name: chunk.item.name, - args: chunk.item.arguments, - id: chunk.item.call_id, - index: chunk.output_index - }); - additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [chunk.item.call_id]: chunk.item.id }; - } else if (chunk.type === "response.output_item.done" && [ - "web_search_call", - "file_search_call", - "computer_call", - "code_interpreter_call", - "mcp_call", - "mcp_list_tools", - "mcp_approval_request", - "image_generation_call", - "custom_tool_call" - ].includes(chunk.item.type)) additional_kwargs.tool_outputs = [chunk.item]; - else if (chunk.type === "response.created") { - response_metadata.id = chunk.response.id; - response_metadata.model_name = chunk.response.model; - response_metadata.model = chunk.response.model; - } else if (chunk.type === "response.completed") { - const msg = this._convertResponsesMessageToBaseMessage(chunk.response); - usage_metadata = _convertOpenAIResponsesUsageToLangChainUsage(chunk.response.usage); - if (chunk.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text); - for (const [key, value] of Object.entries(chunk.response)) if (key !== "id") response_metadata[key] = value; - } else if (chunk.type === "response.function_call_arguments.delta" || chunk.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({ - type: "tool_call_chunk", - args: chunk.delta, - index: chunk.output_index - }); - else if (chunk.type === "response.web_search_call.completed" || chunk.type === "response.file_search_call.completed") generationInfo = { tool_outputs: { - id: chunk.item_id, - type: chunk.type.replace("response.", "").replace(".completed", ""), - status: "completed" - } }; - else if (chunk.type === "response.refusal.done") additional_kwargs.refusal = chunk.refusal; - else if (chunk.type === "response.output_item.added" && "item" in chunk && chunk.item.type === "reasoning") { - const summary = chunk.item.summary ? chunk.item.summary.map((s, index) => ({ - ...s, - index - })) : void 0; - additional_kwargs.reasoning = { - id: chunk.item.id, - type: chunk.item.type, - ...summary ? { summary } : {} - }; - } else if (chunk.type === "response.reasoning_summary_part.added") additional_kwargs.reasoning = { - type: "reasoning", - summary: [{ - ...chunk.part, - index: chunk.summary_index - }] - }; - else if (chunk.type === "response.reasoning_summary_text.delta") additional_kwargs.reasoning = { - type: "reasoning", - summary: [{ - text: chunk.delta, - type: "summary_text", - index: chunk.summary_index - }] - }; - else if (chunk.type === "response.image_generation_call.partial_image") return null; - else return null; - return new ChatGenerationChunk({ - text: content.map((part) => part.text).join(""), - message: new AIMessageChunk({ - id, - content, - tool_call_chunks, - usage_metadata, - additional_kwargs, - response_metadata - }), - generationInfo - }); - } - /** @internal */ - _convertMessagesToResponsesParams(messages) { - return messages.flatMap((lcMsg) => { - const responseMetadata = lcMsg.response_metadata; - if (responseMetadata?.output_version === "v1") return _convertToResponsesMessageFromV1(lcMsg); - const additional_kwargs = lcMsg.additional_kwargs; - let role = messageToOpenAIRole(lcMsg); - if (role === "system" && isReasoningModel(this.model)) role = "developer"; - if (role === "function") throw new Error("Function messages are not supported in Responses API"); - if (role === "tool") { - const toolMessage = lcMsg; - if (additional_kwargs?.type === "computer_call_output") { - const output = (() => { - if (typeof toolMessage.content === "string") return { - type: "computer_screenshot", - image_url: toolMessage.content - }; - if (Array.isArray(toolMessage.content)) { - const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot"); - if (oaiScreenshot) return oaiScreenshot; - const lcImage = toolMessage.content.find((i) => i.type === "image_url"); - if (lcImage) return { - type: "computer_screenshot", - image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url - }; - } - throw new Error("Invalid computer call output"); - })(); - return { - type: "computer_call_output", - output, - call_id: toolMessage.tool_call_id - }; - } - if (toolMessage.additional_kwargs?.customTool) return { - type: "custom_tool_call_output", - call_id: toolMessage.tool_call_id, - output: toolMessage.content - }; - return { - type: "function_call_output", - call_id: toolMessage.tool_call_id, - id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0, - output: typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content - }; - } - if (role === "assistant") { - if (!this.zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => "type" in item)) return responseMetadata?.output; - const input = []; - if (additional_kwargs?.reasoning && !this.zdrEnabled) { - const reasoningItem = this._convertReasoningSummary(additional_kwargs.reasoning); - input.push(reasoningItem); - } - let { content } = lcMsg; - if (additional_kwargs?.refusal) { - if (typeof content === "string") content = [{ - type: "output_text", - text: content, - annotations: [] - }]; - content = [...content, { - type: "refusal", - refusal: additional_kwargs.refusal - }]; - } - if (typeof content === "string" || content.length > 0) input.push({ - type: "message", - role: "assistant", - ...lcMsg.id && !this.zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {}, - content: misc_iife(() => { - if (typeof content === "string") return content; - return content.flatMap((item) => { - if (item.type === "text") return { - type: "output_text", - text: item.text, - annotations: item.annotations ?? [] - }; - if (item.type === "output_text" || item.type === "refusal") return item; - return []; - }); - }) - }); - const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY]; - if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => { - if (isCustomToolCall(toolCall)) return { - type: "custom_tool_call", - id: toolCall.call_id, - call_id: toolCall.id ?? "", - input: toolCall.args.input, - name: toolCall.name - }; - return { - type: "function_call", - name: toolCall.name, - arguments: JSON.stringify(toolCall.args), - call_id: toolCall.id, - ...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} - }; - })); - else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({ - type: "function_call", - name: toolCall.function.name, - call_id: toolCall.id, - arguments: toolCall.function.arguments, - ...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} - }))); - const toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs; - const fallthroughCallTypes = [ - "computer_call", - "mcp_call", - "code_interpreter_call", - "image_generation_call" - ]; - if (toolOutputs != null) { - const castToolOutputs = toolOutputs; - const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type)); - if (fallthroughCalls.length > 0) input.push(...fallthroughCalls); - } - return input; - } - if (role === "user" || role === "system" || role === "developer") { - if (typeof lcMsg.content === "string") return { - type: "message", - role, - content: lcMsg.content - }; - const messages$1 = []; - const content = lcMsg.content.flatMap((item) => { - if (item.type === "mcp_approval_response") messages$1.push({ - type: "mcp_approval_response", - approval_request_id: item.approval_request_id, - approve: item.approve - }); - if (isDataContentBlock(item)) return convertToProviderContentBlock(item, completionsApiContentBlockConverter); - if (item.type === "text") return { - type: "input_text", - text: item.text - }; - if (item.type === "image_url") { - const imageUrl = misc_iife(() => { - if (typeof item.image_url === "string") return item.image_url; - else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url; - return void 0; - }); - const detail = misc_iife(() => { - if (typeof item.image_url === "string") return "auto"; - else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail; - return void 0; - }); - return { - type: "input_image", - image_url: imageUrl, - detail - }; - } - if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item; - return []; - }); - if (content.length > 0) messages$1.push({ - type: "message", - role, - content - }); - return messages$1; - } - console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`); - return []; - }); - } - /** @internal */ - _convertReasoningSummary(reasoning) { - const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => { - const last = acc[acc.length - 1]; - if (last.index === curr.index) last.text += curr.text; - else acc.push(curr); - return acc; - }, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index"))); - return { - ...reasoning, - summary - }; - } - /** @internal */ - _reduceChatOpenAITools(tools, fields) { - const reducedTools = []; - for (const tool of tools) if (isBuiltInTool(tool)) { - if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1; - reducedTools.push(tool); - } else if (isCustomTool(tool)) { - const customToolData = tool.metadata.customTool; - reducedTools.push({ - type: "custom", - name: customToolData.name, - description: customToolData.description, - format: customToolData.format - }); - } else if (isOpenAITool(tool)) reducedTools.push({ - type: "function", - name: tool.function.name, - parameters: tool.function.parameters, - description: tool.function.description, - strict: fields?.strict ?? null - }); - else if (isOpenAICustomTool(tool)) reducedTools.push(convertCompletionsCustomTool(tool)); - return reducedTools; - } -}; - -//#endregion - -//# sourceMappingURL=responses.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/completions.js - - - - - - - - - - -//#region src/chat_models/completions.ts -/** -* OpenAI Completions API implementation. -* @internal -*/ -var ChatOpenAICompletions = class extends BaseChatOpenAI { - /** @internal */ - invocationParams(options, extra) { - let strict; - if (options?.strict !== void 0) strict = options.strict; - else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; - let streamOptionsConfig = {}; - if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options }; - else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } }; - const params = { - model: this.model, - temperature: this.temperature, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - logprobs: this.logprobs, - top_logprobs: this.topLogprobs, - n: this.n, - logit_bias: this.logitBias, - stop: options?.stop ?? this.stopSequences, - user: this.user, - stream: this.streaming, - functions: options?.functions, - function_call: options?.function_call, - tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0, - tool_choice: formatToOpenAIToolChoice(options?.tool_choice), - response_format: this._getResponseFormat(options?.response_format), - seed: options?.seed, - ...streamOptionsConfig, - parallel_tool_calls: options?.parallel_tool_calls, - ...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {}, - ...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {}, - ...this.modelKwargs, - prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, - verbosity: options?.verbosity ?? this.verbosity - }; - if (options?.prediction !== void 0) params.prediction = options.prediction; - if (this.service_tier !== void 0) params.service_tier = this.service_tier; - if (options?.service_tier !== void 0) params.service_tier = options.service_tier; - const reasoning = this._getReasoningParams(options); - if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort; - if (isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; - else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; - return params; - } - async _generate(messages, options, runManager) { - const usageMetadata = {}; - const params = this.invocationParams(options); - const messagesMapped = message_inputs_convertMessagesToOpenAIParams(messages, this.model); - if (params.stream) { - const stream = this._streamResponseChunks(messages, options, runManager); - const finalChunks = {}; - for await (const chunk of stream) { - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - const index = chunk.generationInfo?.completion ?? 0; - if (finalChunks[index] === void 0) finalChunks[index] = chunk; - else finalChunks[index] = finalChunks[index].concat(chunk); - } - const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); - const { functions, function_call } = this.invocationParams(options); - const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call); - const completionTokenUsage = await this._getNumTokensFromGenerations(generations); - usageMetadata.input_tokens = promptTokenUsage; - usageMetadata.output_tokens = completionTokenUsage; - usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage; - return { - generations, - llmOutput: { estimatedTokenUsage: { - promptTokens: usageMetadata.input_tokens, - completionTokens: usageMetadata.output_tokens, - totalTokens: usageMetadata.total_tokens - } } - }; - } else { - const data = await this.completionWithRetry({ - ...params, - stream: false, - messages: messagesMapped - }, { - signal: options?.signal, - ...options?.options - }); - const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {}; - if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens; - if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens; - if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens; - if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = { - ...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens }, - ...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens } - }; - if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = { - ...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens }, - ...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens } - }; - const generations = []; - for (const part of data?.choices ?? []) { - const text = part.message?.content ?? ""; - const generation = { - text, - message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data) - }; - generation.generationInfo = { - ...part.finish_reason ? { finish_reason: part.finish_reason } : {}, - ...part.logprobs ? { logprobs: part.logprobs } : {} - }; - if (isAIMessage(generation.message)) generation.message.usage_metadata = usageMetadata; - generation.message = new AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_")))); - generations.push(generation); - } - return { - generations, - llmOutput: { tokenUsage: { - promptTokens: usageMetadata.input_tokens, - completionTokens: usageMetadata.output_tokens, - totalTokens: usageMetadata.total_tokens - } } - }; - } - } - async *_streamResponseChunks(messages, options, runManager) { - const messagesMapped = message_inputs_convertMessagesToOpenAIParams(messages, this.model); - const params = { - ...this.invocationParams(options, { streaming: true }), - messages: messagesMapped, - stream: true - }; - let defaultRole; - const streamIterable = await this.completionWithRetry(params, options); - let usage; - for await (const data of streamIterable) { - const choice = data?.choices?.[0]; - if (data.usage) usage = data.usage; - if (!choice) continue; - const { delta } = choice; - if (!delta) continue; - const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole); - defaultRole = delta.role ?? defaultRole; - const newTokenIndices = { - prompt: options.promptIndex ?? 0, - completion: choice.index ?? 0 - }; - if (typeof chunk.content !== "string") { - console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported."); - continue; - } - const generationInfo = { ...newTokenIndices }; - if (choice.finish_reason != null) { - generationInfo.finish_reason = choice.finish_reason; - generationInfo.system_fingerprint = data.system_fingerprint; - generationInfo.model_name = data.model; - generationInfo.service_tier = data.service_tier; - } - if (this.logprobs) generationInfo.logprobs = choice.logprobs; - const generationChunk = new ChatGenerationChunk({ - message: chunk, - text: chunk.content, - generationInfo - }); - yield generationChunk; - await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk }); - } - if (usage) { - const inputTokenDetails = { - ...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens }, - ...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens } - }; - const outputTokenDetails = { - ...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens }, - ...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens } - }; - const generationChunk = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: "", - response_metadata: { usage: { ...usage } }, - usage_metadata: { - input_tokens: usage.prompt_tokens, - output_tokens: usage.completion_tokens, - total_tokens: usage.total_tokens, - ...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails }, - ...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails } - } - }), - text: "" - }); - yield generationChunk; - } - if (options.signal?.aborted) throw new Error("AbortError"); - } - async completionWithRetry(request, requestOptions) { - const clientOptions = this._getClientOptions(requestOptions); - const isParseableFormat = request.response_format && request.response_format.type === "json_schema"; - return this.caller.call(async () => { - try { - if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions); - else return await this.client.chat.completions.create(request, clientOptions); - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** @internal */ - _convertCompletionsMessageToBaseMessage(message, rawResponse) { - const rawToolCalls = message.tool_calls; - switch (message.role) { - case "assistant": { - const toolCalls = []; - const invalidToolCalls = []; - for (const rawToolCall of rawToolCalls ?? []) try { - toolCalls.push(parseToolCall(rawToolCall, { returnId: true })); - } catch (e) { - invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message)); - } - const additional_kwargs = { - function_call: message.function_call, - tool_calls: rawToolCalls - }; - if (this.__includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse; - const response_metadata = { - model_provider: "openai", - model_name: rawResponse.model, - ...rawResponse.system_fingerprint ? { - usage: { ...rawResponse.usage }, - system_fingerprint: rawResponse.system_fingerprint - } : {} - }; - if (message.audio) additional_kwargs.audio = message.audio; - const content = handleMultiModalOutput(message.content || "", rawResponse.choices?.[0]?.message); - return new AIMessage({ - content, - tool_calls: toolCalls, - invalid_tool_calls: invalidToolCalls, - additional_kwargs, - response_metadata, - id: rawResponse.id - }); - } - default: return new ChatMessage(message.content || "", message.role ?? "unknown"); - } - } - /** @internal */ - _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) { - const role = delta.role ?? defaultRole; - const content = delta.content ?? ""; - let additional_kwargs; - if (delta.function_call) additional_kwargs = { function_call: delta.function_call }; - else if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls }; - else additional_kwargs = {}; - if (this.__includeRawResponse) additional_kwargs.__raw_response = rawResponse; - if (delta.audio) additional_kwargs.audio = { - ...delta.audio, - index: rawResponse.choices[0].index - }; - const response_metadata = { - model_provider: "openai", - usage: { ...rawResponse.usage } - }; - if (role === "user") return new HumanMessageChunk({ - content, - response_metadata - }); - else if (role === "assistant") { - const toolCallChunks = []; - if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({ - name: rawToolCall.function?.name, - args: rawToolCall.function?.arguments, - id: rawToolCall.id, - index: rawToolCall.index, - type: "tool_call_chunk" - }); - return new AIMessageChunk({ - content, - tool_call_chunks: toolCallChunks, - additional_kwargs, - id: rawResponse.id, - response_metadata - }); - } else if (role === "system") return new SystemMessageChunk({ - content, - response_metadata - }); - else if (role === "developer") return new SystemMessageChunk({ - content, - response_metadata, - additional_kwargs: { __openai_role__: "developer" } - }); - else if (role === "function") return new FunctionMessageChunk({ - content, - additional_kwargs, - name: delta.name, - response_metadata - }); - else if (role === "tool") return new ToolMessageChunk({ - content, - additional_kwargs, - tool_call_id: delta.tool_call_id, - response_metadata - }); - else return new ChatMessageChunk({ - content, - role, - response_metadata - }); - } -}; - -//#endregion - -//# sourceMappingURL=completions.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/index.js - - - - - -//#region src/chat_models/index.ts -/** -* OpenAI chat model integration. -* -* To use with Azure, import the `AzureChatOpenAI` class. -* -* Setup: -* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`. -* -* ```bash -* npm install @langchain/openai -* export OPENAI_API_KEY="your-api-key" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.withConfig`, call options should be passed via the first argument -* const llmWithArgsBound = llm.withConfig({ -* stop: ["\n"], -* tools: [...], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* tool_choice: "auto", -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { ChatOpenAI } from '@langchain/openai'; -* -* const llm = new ChatOpenAI({ -* model: "gpt-4o-mini", -* temperature: 0, -* maxTokens: undefined, -* timeout: undefined, -* maxRetries: 2, -* // apiKey: "...", -* // configuration: { -* // baseURL: "...", -* // } -* // organization: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "tokenUsage": { -* "completionTokens": 5, -* "promptTokens": 28, -* "totalTokens": 33 -* }, -* "finish_reason": "stop", -* "system_fingerprint": "fp_3aa7262c27" -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", -* "content": "" -* } -* AIMessageChunk { -* "content": "J" -* } -* AIMessageChunk { -* "content": "'adore" -* } -* AIMessageChunk { -* "content": " la" -* } -* AIMessageChunk { -* "content": " programmation",, -* } -* AIMessageChunk { -* "content": ".",, -* } -* AIMessageChunk { -* "content": "", -* "response_metadata": { -* "finish_reason": "stop", -* "system_fingerprint": "fp_c9aa9c0491" -* }, -* } -* AIMessageChunk { -* "content": "", -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "prompt": 0, -* "completion": 0, -* "finish_reason": "stop", -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools( -* [GetWeather, GetPopulation], -* { -* // strict: true // enforce tool args schema is respected -* } -* ); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_s9KQB1UWj45LLGaEnjz0179q' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* import { z } from 'zod'; -* -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { -* name: "Joke", -* strict: true, // Optionally enable OpenAI structured outputs -* }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: 'Why was the cat sitting on the computer?', -* punchline: 'Because it wanted to keep an eye on the mouse!', -* rating: 7 -* } -* ``` -*
-* -*
-* -*
-* JSON Object Response Format -* -* ```typescript -* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); -* const jsonLlmAiMsg = await jsonLlm.invoke( -* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" -* ); -* console.log(jsonLlmAiMsg.content); -* ``` -* -* ```txt -* { -* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } -* ``` -*
-* -*
-* -*
-* Logprobs -* -* ```typescript -* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); -* const aiMsgForLogprobs = await logprobsLlm.invoke(input); -* console.log(aiMsgForLogprobs.response_metadata.logprobs); -* ``` -* -* ```txt -* { -* content: [ -* { -* token: 'J', -* logprob: -0.000050616763, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: "'", -* logprob: -0.01868736, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: 'ad', -* logprob: -0.0000030545007, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: ' la', -* logprob: -0.515404, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: ' programm', -* logprob: -0.0000118755715, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: '.', -* logprob: -0.0000037697225, -* bytes: [Array], -* top_logprobs: [] -* } -* ], -* refusal: null -* } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, -* finish_reason: 'stop', -* system_fingerprint: 'fp_3aa7262c27' -* } -* ``` -*
-* -*
-* -*
-* JSON Schema Structured Output -* -* ```typescript -* const llmForJsonSchema = new ChatOpenAI({ -* model: "gpt-4o-2024-08-06", -* }).withStructuredOutput( -* z.object({ -* command: z.string().describe("The command to execute"), -* expectedOutput: z.string().describe("The expected output of the command"), -* options: z -* .array(z.string()) -* .describe("The options you can pass to the command"), -* }), -* { -* method: "jsonSchema", -* strict: true, // Optional when using the `jsonSchema` method -* } -* ); -* -* const jsonSchemaRes = await llmForJsonSchema.invoke( -* "What is the command to list files in a directory?" -* ); -* console.log(jsonSchemaRes); -* ``` -* -* ```txt -* { -* command: 'ls', -* expectedOutput: 'A list of files and subdirectories within the specified directory.', -* options: [ -* '-a: include directory entries whose names begin with a dot (.).', -* '-l: use a long listing format.', -* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).', -* '-t: sort by time, newest first.', -* '-r: reverse order while sorting.', -* '-S: sort by file size, largest first.', -* '-R: list subdirectories recursively.' -* ] -* } -* ``` -*
-* -*
-* -*
-* Audio Outputs -* -* ```typescript -* import { ChatOpenAI } from "@langchain/openai"; -* -* const modelWithAudioOutput = new ChatOpenAI({ -* model: "gpt-4o-audio-preview", -* // You may also pass these fields to `.withConfig` as a call argument. -* modalities: ["text", "audio"], // Specifies that the model should output audio. -* audio: { -* voice: "alloy", -* format: "wav", -* }, -* }); -* -* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); -* const castMessageContent = audioOutputResult.content[0] as Record; -* -* console.log({ -* ...castMessageContent, -* data: castMessageContent.data.slice(0, 100) // Sliced for brevity -* }) -* ``` -* -* ```txt -* { -* id: 'audio_67117718c6008190a3afad3e3054b9b6', -* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', -* expires_at: 1729201448, -* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' -* } -* ``` -*
-* -*
-* -*
-* Audio Outputs -* -* ```typescript -* import { ChatOpenAI } from "@langchain/openai"; -* -* const modelWithAudioOutput = new ChatOpenAI({ -* model: "gpt-4o-audio-preview", -* // You may also pass these fields to `.withConfig` as a call argument. -* modalities: ["text", "audio"], // Specifies that the model should output audio. -* audio: { -* voice: "alloy", -* format: "wav", -* }, -* }); -* -* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); -* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record; -* -* console.log({ -* ...castAudioContent, -* data: castAudioContent.data.slice(0, 100) // Sliced for brevity -* }) -* ``` -* -* ```txt -* { -* id: 'audio_67117718c6008190a3afad3e3054b9b6', -* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', -* expires_at: 1729201448, -* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' -* } -* ``` -*
-* -*
-*/ -var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI { - /** - * Whether to use the responses API for all requests. If `false` the responses API will be used - * only when required in order to fulfill the request. - */ - useResponsesApi = false; - responses; - completions; - get lc_serializable_keys() { - return [...super.lc_serializable_keys, "useResponsesApi"]; - } - get callKeys() { - return [...super.callKeys, "useResponsesApi"]; - } - constructor(fields) { - super(fields); - this.fields = fields; - this.useResponsesApi = fields?.useResponsesApi ?? false; - this.responses = fields?.responses ?? new ChatOpenAIResponses(fields); - this.completions = fields?.completions ?? new ChatOpenAICompletions(fields); - } - _useResponsesApi(options) { - const usesBuiltInTools = options?.tools?.some(isBuiltInTool); - const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null; - const hasCustomTools = options?.tools?.some(isOpenAICustomTool) || options?.tools?.some(isCustomTool); - return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools; - } - getLsParams(options) { - const optionsWithDefaults = this._combineCallOptions(options); - if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults); - return this.completions.getLsParams(optionsWithDefaults); - } - invocationParams(options) { - const optionsWithDefaults = this._combineCallOptions(options); - if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults); - return this.completions.invocationParams(optionsWithDefaults); - } - /** @ignore */ - async _generate(messages, options, runManager) { - if (this._useResponsesApi(options)) return this.responses._generate(messages, options); - return this.completions._generate(messages, options, runManager); - } - async *_streamResponseChunks(messages, options, runManager) { - if (this._useResponsesApi(options)) { - yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager); - return; - } - yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager); - } - withConfig(config) { - const newModel = new ChatOpenAI(this.fields); - newModel.defaultOptions = { - ...this.defaultOptions, - ...config - }; - return newModel; - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/common.js - - - - -//#region src/azure/chat_models/common.ts -const AZURE_ALIASES = { - openAIApiKey: "openai_api_key", - openAIApiVersion: "openai_api_version", - openAIBasePath: "openai_api_base", - deploymentName: "deployment_name", - azureOpenAIEndpoint: "azure_endpoint", - azureOpenAIApiVersion: "openai_api_version", - azureOpenAIBasePath: "openai_api_base", - azureOpenAIApiDeploymentName: "deployment_name" -}; -const AZURE_SECRETS = { azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" }; -const AZURE_SERIALIZABLE_KEYS = [ - "azureOpenAIApiKey", - "azureOpenAIApiVersion", - "azureOpenAIBasePath", - "azureOpenAIEndpoint", - "azureOpenAIApiInstanceName", - "azureOpenAIApiDeploymentName", - "deploymentName", - "openAIApiKey", - "openAIApiVersion" -]; -function _constructAzureFields(fields) { - this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? fields?.openAIApiKey ?? fields?.apiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); - this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = fields?.azureOpenAIApiDeploymentName ?? fields?.deploymentName ?? getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"); - this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); - this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); - this.azureADTokenProvider = fields?.azureADTokenProvider; - if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error("Azure OpenAI API key or Token Provider not found"); -} -function _getAzureClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - azureADTokenProvider: this.azureADTokenProvider, - baseURL: this.clientConfig.baseURL, - azureOpenAIEndpoint: this.azureOpenAIEndpoint - }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; - if (!params.baseURL) delete params.baseURL; - let env = getEnv(); - if (env === "node" || env === "deno") env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`; - const defaultHeaders = normalizeHeaders(params.defaultHeaders); - params.defaultHeaders = { - ...params.defaultHeaders, - "User-Agent": defaultHeaders["User-Agent"] ? `langchainjs-azure-openai/2.0.0 (${env})${defaultHeaders["User-Agent"]}` : `langchainjs-azure-openai/2.0.0 (${env})` - }; - this.client = new AzureOpenAI({ - apiVersion: this.azureOpenAIApiVersion, - azureADTokenProvider: this.azureADTokenProvider, - deployment: this.azureOpenAIApiDeploymentName, - ...params - }); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query - }; - } - return requestOptions; -} -function _serializeAzureChat(input) { - const json = input; - function isRecord(obj) { - return typeof obj === "object" && obj != null; - } - if (isRecord(json) && isRecord(json.kwargs)) { - delete json.kwargs.azure_openai_base_path; - delete json.kwargs.azure_openai_api_deployment_name; - delete json.kwargs.azure_openai_api_key; - delete json.kwargs.azure_openai_api_version; - delete json.kwargs.azure_open_ai_base_path; - if (!json.kwargs.azure_endpoint && this.azureOpenAIEndpoint) json.kwargs.azure_endpoint = this.azureOpenAIEndpoint; - if (!json.kwargs.azure_endpoint && this.azureOpenAIBasePath) { - const parts = this.azureOpenAIBasePath.split("/openai/deployments/"); - if (parts.length === 2 && parts[0].startsWith("http")) { - const [endpoint] = parts; - json.kwargs.azure_endpoint = endpoint; - } - } - if (!json.kwargs.azure_endpoint && this.azureOpenAIApiInstanceName) json.kwargs.azure_endpoint = `https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`; - if (!json.kwargs.deployment_name && this.azureOpenAIApiDeploymentName) json.kwargs.deployment_name = this.azureOpenAIApiDeploymentName; - if (!json.kwargs.deployment_name && this.azureOpenAIBasePath) { - const parts = this.azureOpenAIBasePath.split("/openai/deployments/"); - if (parts.length === 2) { - const [, deployment] = parts; - json.kwargs.deployment_name = deployment; - } - } - if (json.kwargs.azure_endpoint && json.kwargs.deployment_name && json.kwargs.openai_api_base) delete json.kwargs.openai_api_base; - if (json.kwargs.azure_openai_api_instance_name && json.kwargs.azure_endpoint) delete json.kwargs.azure_openai_api_instance_name; - } - return json; -} - -//#endregion - -//# sourceMappingURL=common.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/completions.js - - - -//#region src/azure/chat_models/completions.ts -var AzureChatOpenAICompletions = class extends ChatOpenAICompletions { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - _llmType() { - return "azure_openai"; - } - get lc_aliases() { - return { - ...super.lc_aliases, - ...AZURE_ALIASES - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - ...AZURE_SECRETS - }; - } - get lc_serializable_keys() { - return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; - } - getLsParams(options) { - const params = super.getLsParams(options); - params.ls_provider = "azure"; - return params; - } - constructor(fields) { - super(fields); - _constructAzureFields.call(this, fields); - } - _getClientOptions(options) { - return _getAzureClientOptions.call(this, options); - } - toJSON() { - return _serializeAzureChat.call(this, super.toJSON()); - } -}; - -//#endregion - -//# sourceMappingURL=completions.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/responses.js - - - -//#region src/azure/chat_models/responses.ts -var AzureChatOpenAIResponses = class extends ChatOpenAIResponses { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - _llmType() { - return "azure_openai"; - } - get lc_aliases() { - return { - ...super.lc_aliases, - ...AZURE_ALIASES - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - ...AZURE_SECRETS - }; - } - get lc_serializable_keys() { - return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; - } - getLsParams(options) { - const params = super.getLsParams(options); - params.ls_provider = "azure"; - return params; - } - constructor(fields) { - super(fields); - _constructAzureFields.call(this, fields); - } - _getClientOptions(options) { - return _getAzureClientOptions.call(this, options); - } - toJSON() { - return _serializeAzureChat.call(this, super.toJSON()); - } -}; - -//#endregion - -//# sourceMappingURL=responses.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/index.js - - - - - -//#region src/azure/chat_models/index.ts -/** -* Azure OpenAI chat model integration. -* -* Setup: -* Install `@langchain/openai` and set the following environment variables: -* -* ```bash -* npm install @langchain/openai -* export AZURE_OPENAI_API_KEY="your-api-key" -* export AZURE_OPENAI_API_DEPLOYMENT_NAME="your-deployment-name" -* export AZURE_OPENAI_API_VERSION="your-version" -* export AZURE_OPENAI_BASE_PATH="your-base-path" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.AzureChatOpenAI.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.withConfig`, call options should be passed via the first argument -* const llmWithArgsBound = llm.withConfig({ -* stop: ["\n"], -* tools: [...], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* tool_choice: "auto", -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { AzureChatOpenAI } from '@langchain/openai'; -* -* const llm = new AzureChatOpenAI({ -* azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY, // In Node.js defaults to process.env.AZURE_OPENAI_API_KEY -* azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_INSTANCE_NAME -* azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME -* azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION, // In Node.js defaults to process.env.AZURE_OPENAI_API_VERSION -* temperature: 0, -* maxTokens: undefined, -* timeout: undefined, -* maxRetries: 2, -* // apiKey: "...", -* // baseUrl: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "tokenUsage": { -* "completionTokens": 5, -* "promptTokens": 28, -* "totalTokens": 33 -* }, -* "finish_reason": "stop", -* "system_fingerprint": "fp_3aa7262c27" -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", -* "content": "" -* } -* AIMessageChunk { -* "content": "J" -* } -* AIMessageChunk { -* "content": "'adore" -* } -* AIMessageChunk { -* "content": " la" -* } -* AIMessageChunk { -* "content": " programmation",, -* } -* AIMessageChunk { -* "content": ".",, -* } -* AIMessageChunk { -* "content": "", -* "response_metadata": { -* "finish_reason": "stop", -* "system_fingerprint": "fp_c9aa9c0491" -* }, -* } -* AIMessageChunk { -* "content": "", -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "prompt": 0, -* "completion": 0, -* "finish_reason": "stop", -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_s9KQB1UWj45LLGaEnjz0179q' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* import { z } from 'zod'; -* -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: 'Why was the cat sitting on the computer?', -* punchline: 'Because it wanted to keep an eye on the mouse!', -* rating: 7 -* } -* ``` -*
-* -*
-* -*
-* JSON Object Response Format -* -* ```typescript -* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); -* const jsonLlmAiMsg = await jsonLlm.invoke( -* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" -* ); -* console.log(jsonLlmAiMsg.content); -* ``` -* -* ```txt -* { -* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } -* ``` -*
-* -*
-* -*
-* Logprobs -* -* ```typescript -* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); -* const aiMsgForLogprobs = await logprobsLlm.invoke(input); -* console.log(aiMsgForLogprobs.response_metadata.logprobs); -* ``` -* -* ```txt -* { -* content: [ -* { -* token: 'J', -* logprob: -0.000050616763, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: "'", -* logprob: -0.01868736, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: 'ad', -* logprob: -0.0000030545007, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: ' la', -* logprob: -0.515404, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: ' programm', -* logprob: -0.0000118755715, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: '.', -* logprob: -0.0000037697225, -* bytes: [Array], -* top_logprobs: [] -* } -* ], -* refusal: null -* } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, -* finish_reason: 'stop', -* system_fingerprint: 'fp_3aa7262c27' -* } -* ``` -*
-*/ -var AzureChatOpenAI = class extends ChatOpenAI { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - _llmType() { - return "azure_openai"; - } - get lc_aliases() { - return { - ...super.lc_aliases, - ...AZURE_ALIASES - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - ...AZURE_SECRETS - }; - } - get lc_serializable_keys() { - return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; - } - getLsParams(options) { - const params = super.getLsParams(options); - params.ls_provider = "azure"; - return params; - } - constructor(fields) { - super({ - ...fields, - completions: new AzureChatOpenAICompletions(fields), - responses: new AzureChatOpenAIResponses(fields) - }); - _constructAzureFields.call(this, fields); - } - /** @internal */ - _getStructuredOutputMethod(config) { - const ensuredConfig = { ...config }; - if (this.model.startsWith("gpt-4o")) { - if (ensuredConfig?.method === void 0) return "functionCalling"; - } - return super._getStructuredOutputMethod(ensuredConfig); - } - toJSON() { - return _serializeAzureChat.call(this, super.toJSON()); - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/llms.js - - - - - - - - - -//#region src/llms.ts -/** -* Wrapper around OpenAI large language models. -* -* To use you should have the `openai` package installed, with the -* `OPENAI_API_KEY` environment variable set. -* -* To use with Azure, import the `AzureOpenAI` class. -* -* @remarks -* Any parameters that are valid to be passed to {@link -* https://platform.openai.com/docs/api-reference/completions/create | -* `openai.createCompletion`} can be passed through {@link modelKwargs}, even -* if not explicitly available on this class. -* @example -* ```typescript -* const model = new OpenAI({ -* modelName: "gpt-4", -* temperature: 0.7, -* maxTokens: 1000, -* maxRetries: 5, -* }); -* -* const res = await model.invoke( -* "Question: What would be a good company name for a company that makes colorful socks?\nAnswer:" -* ); -* console.log({ res }); -* ``` -*/ -var OpenAI$2 = class extends BaseLLM { - static lc_name() { - return "OpenAI"; - } - get callKeys() { - return [...super.callKeys, "options"]; - } - lc_serializable = true; - get lc_secrets() { - return { - openAIApiKey: "OPENAI_API_KEY", - apiKey: "OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION" - }; - } - get lc_aliases() { - return { - modelName: "model", - openAIApiKey: "openai_api_key", - apiKey: "openai_api_key" - }; - } - temperature; - maxTokens; - topP; - frequencyPenalty; - presencePenalty; - n = 1; - bestOf; - logitBias; - model = "gpt-3.5-turbo-instruct"; - /** @deprecated Use "model" instead */ - modelName; - modelKwargs; - batchSize = 20; - timeout; - stop; - stopSequences; - user; - streaming = false; - openAIApiKey; - apiKey; - organization; - client; - clientConfig; - constructor(fields) { - super(fields ?? {}); - this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - this.apiKey = this.openAIApiKey; - this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - this.model = fields?.model ?? fields?.modelName ?? this.model; - if ((this.model?.startsWith("gpt-3.5-turbo") || this.model?.startsWith("gpt-4") || this.model?.startsWith("o1")) && !this.model?.includes("-instruct")) throw new Error([ - `Your chosen OpenAI model, "${this.model}", is a chat model and not a text-in/text-out LLM.`, - `Passing it into the "OpenAI" class is no longer supported.`, - `Please use the "ChatOpenAI" class instead.`, - "", - `See this page for more information:`, - "|", - `└> https://js.langchain.com/docs/integrations/chat/openai` - ].join("\n")); - this.modelName = this.model; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.batchSize = fields?.batchSize ?? this.batchSize; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.maxTokens = fields?.maxTokens ?? this.maxTokens; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.n = fields?.n ?? this.n; - this.bestOf = fields?.bestOf ?? this.bestOf; - this.logitBias = fields?.logitBias; - this.stop = fields?.stopSequences ?? fields?.stop; - this.stopSequences = this.stop; - this.user = fields?.user; - this.streaming = fields?.streaming ?? false; - if (this.streaming && this.bestOf && this.bestOf > 1) throw new Error("Cannot stream results when bestOf > 1"); - this.clientConfig = { - apiKey: this.apiKey, - organization: this.organization, - dangerouslyAllowBrowser: true, - ...fields?.configuration - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - return { - model: this.model, - temperature: this.temperature, - max_tokens: this.maxTokens, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - n: this.n, - best_of: this.bestOf, - logit_bias: this.logitBias, - stop: options?.stop ?? this.stopSequences, - user: this.user, - stream: this.streaming, - ...this.modelKwargs - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams(), - ...this.clientConfig - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return this._identifyingParams(); - } - /** - * Call out to OpenAI's endpoint with k unique prompts - * - * @param [prompts] - The prompts to pass into the model. - * @param [options] - Optional list of stop words to use when generating. - * @param [runManager] - Optional callback manager to use when generating. - * - * @returns The full LLM output. - * - * @example - * ```ts - * import { OpenAI } from "langchain/llms/openai"; - * const openai = new OpenAI(); - * const response = await openai.generate(["Tell me a joke."]); - * ``` - */ - async _generate(prompts, options, runManager) { - const subPrompts = chunkArray(prompts, this.batchSize); - const choices = []; - const tokenUsage = {}; - const params = this.invocationParams(options); - if (params.max_tokens === -1) { - if (prompts.length !== 1) throw new Error("max_tokens set to -1 not supported for multiple inputs"); - params.max_tokens = await calculateMaxTokens({ - prompt: prompts[0], - modelName: this.model - }); - } - for (let i = 0; i < subPrompts.length; i += 1) { - const data = params.stream ? await (async () => { - const choices$1 = []; - let response; - const stream = await this.completionWithRetry({ - ...params, - stream: true, - prompt: subPrompts[i] - }, options); - for await (const message of stream) { - if (!response) response = { - id: message.id, - object: message.object, - created: message.created, - model: message.model - }; - for (const part of message.choices) { - if (!choices$1[part.index]) choices$1[part.index] = part; - else { - const choice = choices$1[part.index]; - choice.text += part.text; - choice.finish_reason = part.finish_reason; - choice.logprobs = part.logprobs; - } - runManager?.handleLLMNewToken(part.text, { - prompt: Math.floor(part.index / this.n), - completion: part.index % this.n - }); - } - } - if (options.signal?.aborted) throw new Error("AbortError"); - return { - ...response, - choices: choices$1 - }; - })() : await this.completionWithRetry({ - ...params, - stream: false, - prompt: subPrompts[i] - }, { - signal: options.signal, - ...options.options - }); - choices.push(...data.choices); - const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data.usage ? data.usage : { - completion_tokens: void 0, - prompt_tokens: void 0, - total_tokens: void 0 - }; - if (completionTokens) tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens; - if (promptTokens) tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; - if (totalTokens) tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; - } - const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ - text: choice.text ?? "", - generationInfo: { - finishReason: choice.finish_reason, - logprobs: choice.logprobs - } - }))); - return { - generations, - llmOutput: { tokenUsage } - }; - } - async *_streamResponseChunks(input, options, runManager) { - const params = { - ...this.invocationParams(options), - prompt: input, - stream: true - }; - const stream = await this.completionWithRetry(params, options); - for await (const data of stream) { - const choice = data?.choices[0]; - if (!choice) continue; - const chunk = new GenerationChunk({ - text: choice.text, - generationInfo: { finishReason: choice.finish_reason } - }); - yield chunk; - runManager?.handleLLMNewToken(chunk.text ?? ""); - } - if (options.signal?.aborted) throw new Error("AbortError"); - } - async completionWithRetry(request, options) { - const requestOptions = this._getClientOptions(options); - return this.caller.call(async () => { - try { - const res = await this.client.completions.create(request, requestOptions); - return res; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** - * Calls the OpenAI API with retry logic in case of failures. - * @param request The request to send to the OpenAI API. - * @param options Optional configuration for the API call. - * @returns The response from the OpenAI API. - */ - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!params.baseURL) delete params.baseURL; - this.client = new OpenAI(params); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - return requestOptions; - } - _llmType() { - return "openai"; - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/llms.js - - - - - -//#region src/azure/llms.ts -var AzureOpenAI$1 = class extends OpenAI$2 { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - get lc_aliases() { - return { - ...super.lc_aliases, - openAIApiKey: "openai_api_key", - openAIApiVersion: "openai_api_version", - openAIBasePath: "openai_api_base", - deploymentName: "deployment_name", - azureOpenAIEndpoint: "azure_endpoint", - azureOpenAIApiVersion: "openai_api_version", - azureOpenAIBasePath: "openai_api_base", - azureOpenAIApiDeploymentName: "deployment_name" - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" - }; - } - constructor(fields) { - super(fields); - this.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiCompletionsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); - this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? fields?.openAIApiKey ?? fields?.apiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); - this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); - this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); - this.azureADTokenProvider = fields?.azureADTokenProvider; - if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error("Azure OpenAI API key or Token Provider not found"); - } - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - azureADTokenProvider: this.azureADTokenProvider, - baseURL: this.clientConfig.baseURL - }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; - if (!params.baseURL) delete params.baseURL; - const defaultHeaders = normalizeHeaders(params.defaultHeaders); - params.defaultHeaders = { - ...params.defaultHeaders, - "User-Agent": defaultHeaders["User-Agent"] ? `${defaultHeaders["User-Agent"]}: langchainjs-azure-openai-v2` : `langchainjs-azure-openai-v2` - }; - this.client = new AzureOpenAI({ - apiVersion: this.azureOpenAIApiVersion, - azureADTokenProvider: this.azureADTokenProvider, - ...params - }); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query - }; - } - return requestOptions; - } - toJSON() { - const json = super.toJSON(); - function isRecord(obj) { - return typeof obj === "object" && obj != null; - } - if (isRecord(json) && isRecord(json.kwargs)) { - delete json.kwargs.azure_openai_base_path; - delete json.kwargs.azure_openai_api_deployment_name; - delete json.kwargs.azure_openai_api_key; - delete json.kwargs.azure_openai_api_version; - delete json.kwargs.azure_open_ai_base_path; - } - return json; - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/embeddings.js - - - - - - - -//#region src/embeddings.ts -/** -* Class for generating embeddings using the OpenAI API. -* -* To use with Azure, import the `AzureOpenAIEmbeddings` class. -* -* @example -* ```typescript -* // Embed a query using OpenAIEmbeddings to generate embeddings for a given text -* const model = new OpenAIEmbeddings(); -* const res = await model.embedQuery( -* "What would be a good company name for a company that makes colorful socks?", -* ); -* console.log({ res }); -* -* ``` -*/ -var OpenAIEmbeddings = class extends Embeddings { - model = "text-embedding-ada-002"; - /** @deprecated Use "model" instead */ - modelName; - batchSize = 512; - stripNewLines = true; - /** - * The number of dimensions the resulting output embeddings should have. - * Only supported in `text-embedding-3` and later models. - */ - dimensions; - timeout; - organization; - encodingFormat; - client; - clientConfig; - constructor(fields) { - const fieldsWithDefaults = { - maxConcurrency: 2, - ...fields - }; - super(fieldsWithDefaults); - const apiKey = fieldsWithDefaults?.apiKey ?? fieldsWithDefaults?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - this.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - this.model = fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model; - this.modelName = this.model; - this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize; - this.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines; - this.timeout = fieldsWithDefaults?.timeout; - this.dimensions = fieldsWithDefaults?.dimensions; - this.encodingFormat = fieldsWithDefaults?.encodingFormat; - this.clientConfig = { - apiKey, - organization: this.organization, - dangerouslyAllowBrowser: true, - ...fields?.configuration - }; - } - /** - * Method to generate embeddings for an array of documents. Splits the - * documents into batches and makes requests to the OpenAI API to generate - * embeddings. - * @param texts Array of documents to generate embeddings for. - * @returns Promise that resolves to a 2D array of embeddings for each document. - */ - async embedDocuments(texts) { - const batches = chunkArray(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize); - const batchRequests = batches.map((batch) => { - const params = { - model: this.model, - input: batch - }; - if (this.dimensions) params.dimensions = this.dimensions; - if (this.encodingFormat) params.encoding_format = this.encodingFormat; - return this.embeddingWithRetry(params); - }); - const batchResponses = await Promise.all(batchRequests); - const embeddings = []; - for (let i = 0; i < batchResponses.length; i += 1) { - const batch = batches[i]; - const { data: batchResponse } = batchResponses[i]; - for (let j = 0; j < batch.length; j += 1) embeddings.push(batchResponse[j].embedding); - } - return embeddings; - } - /** - * Method to generate an embedding for a single document. Calls the - * embeddingWithRetry method with the document as the input. - * @param text Document to generate an embedding for. - * @returns Promise that resolves to an embedding for the document. - */ - async embedQuery(text) { - const params = { - model: this.model, - input: this.stripNewLines ? text.replace(/\n/g, " ") : text - }; - if (this.dimensions) params.dimensions = this.dimensions; - if (this.encodingFormat) params.encoding_format = this.encodingFormat; - const { data } = await this.embeddingWithRetry(params); - return data[0].embedding; - } - /** - * Private method to make a request to the OpenAI API to generate - * embeddings. Handles the retry logic and returns the response from the - * API. - * @param request Request to send to the OpenAI API. - * @returns Promise that resolves to the response from the API. - */ - async embeddingWithRetry(request) { - if (!this.client) { - const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!params.baseURL) delete params.baseURL; - this.client = new OpenAI(params); - } - const requestOptions = {}; - return this.caller.call(async () => { - try { - const res = await this.client.embeddings.create(request, requestOptions); - return res; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/embeddings.js - - - - - - -//#region src/azure/embeddings.ts -var AzureOpenAIEmbeddings = class extends OpenAIEmbeddings { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - constructor(fields) { - super(fields); - this.batchSize = fields?.batchSize ?? 1; - this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? fields?.apiKey ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); - this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); - this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiEmbeddingsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); - this.azureADTokenProvider = fields?.azureADTokenProvider; - } - async embeddingWithRetry(request) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - azureADTokenProvider: this.azureADTokenProvider, - baseURL: this.clientConfig.baseURL - }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; - if (!params.baseURL) delete params.baseURL; - const defaultHeaders = normalizeHeaders(params.defaultHeaders); - params.defaultHeaders = { - ...params.defaultHeaders, - "User-Agent": defaultHeaders["User-Agent"] ? `${defaultHeaders["User-Agent"]}: langchainjs-azure-openai-v2` : `langchainjs-azure-openai-v2` - }; - this.client = new AzureOpenAI({ - apiVersion: this.azureOpenAIApiVersion, - azureADTokenProvider: this.azureADTokenProvider, - deployment: this.azureOpenAIApiDeploymentName, - ...params - }); - } - const requestOptions = {}; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query - }; - } - return this.caller.call(async () => { - try { - const res = await this.client.embeddings.create(request, requestOptions); - return res; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/dalle.js - - - - -//#region src/tools/dalle.ts -/** -* A tool for generating images with Open AIs Dall-E 2 or 3 API. -*/ -var DallEAPIWrapper = class extends Tool { - static lc_name() { - return "DallEAPIWrapper"; - } - name = "dalle_api_wrapper"; - description = "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."; - client; - static toolName = "dalle_api_wrapper"; - model = "dall-e-3"; - style = "vivid"; - quality = "standard"; - n = 1; - size = "1024x1024"; - dallEResponseFormat = "url"; - user; - constructor(fields) { - if (fields?.responseFormat !== void 0 && ["url", "b64_json"].includes(fields.responseFormat)) { - fields.dallEResponseFormat = fields.responseFormat; - fields.responseFormat = "content"; - } - super(fields); - const openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - const organization = fields?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - const clientConfig = { - apiKey: openAIApiKey, - organization, - dangerouslyAllowBrowser: true, - baseURL: fields?.baseUrl - }; - this.client = new OpenAI(clientConfig); - this.model = fields?.model ?? fields?.modelName ?? this.model; - this.style = fields?.style ?? this.style; - this.quality = fields?.quality ?? this.quality; - this.n = fields?.n ?? this.n; - this.size = fields?.size ?? this.size; - this.dallEResponseFormat = fields?.dallEResponseFormat ?? this.dallEResponseFormat; - this.user = fields?.user; - } - /** - * Processes the API response if multiple images are generated. - * Returns a list of MessageContentImageUrl objects. If the response - * format is `url`, then the `image_url` field will contain the URL. - * If it is `b64_json`, then the `image_url` field will contain an object - * with a `url` field with the base64 encoded image. - * - * @param {OpenAIClient.Images.ImagesResponse[]} response The API response - * @returns {MessageContentImageUrl[]} - */ - processMultipleGeneratedUrls(response) { - if (this.dallEResponseFormat === "url") return response.flatMap((res) => { - const imageUrlContent = res.data?.flatMap((item) => { - if (!item.url) return []; - return { - type: "image_url", - image_url: item.url - }; - }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "string" && item.image_url !== void 0) ?? []; - return imageUrlContent; - }); - else return response.flatMap((res) => { - const b64Content = res.data?.flatMap((item) => { - if (!item.b64_json) return []; - return { - type: "image_url", - image_url: { url: item.b64_json } - }; - }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "object" && "url" in item.image_url && typeof item.image_url.url === "string" && item.image_url.url !== void 0) ?? []; - return b64Content; - }); - } - /** @ignore */ - async _call(input) { - const generateImageFields = { - model: this.model, - prompt: input, - n: 1, - size: this.size, - response_format: this.dallEResponseFormat, - style: this.style, - quality: this.quality, - user: this.user - }; - if (this.n > 1) { - const results = await Promise.all(Array.from({ length: this.n }).map(() => this.client.images.generate(generateImageFields))); - return this.processMultipleGeneratedUrls(results); - } - const response = await this.client.images.generate(generateImageFields); - let data = ""; - if (this.dallEResponseFormat === "url") [data] = response.data?.map((item) => item.url).filter((url) => url !== "undefined") ?? []; - else [data] = response.data?.map((item) => item.b64_json).filter((b64_json) => b64_json !== "undefined") ?? []; - return data; - } -}; - -//#endregion - -//# sourceMappingURL=dalle.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/index.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/custom.js - - - - -//#region src/tools/custom.ts -function customTool(func, fields) { - return new DynamicTool({ - ...fields, - description: "", - metadata: { customTool: fields }, - func: async (input, runManager, config) => new Promise((resolve, reject) => { - const childConfig = patchConfig(config, { callbacks: runManager?.getChild() }); - AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - resolve(func(input, childConfig)); - } catch (e) { - reject(e); - } - }); - }) - }); -} - -//#endregion - -//# sourceMappingURL=custom.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/prompts.js - - -//#region src/utils/prompts.ts -/** -* Convert a formatted LangChain prompt (e.g. pulled from the hub) into -* a format expected by OpenAI's JS SDK. -* -* Requires the "@langchain/openai" package to be installed in addition -* to the OpenAI SDK. -* -* @example -* ```ts -* import { convertPromptToOpenAI } from "langsmith/utils/hub/openai"; -* import { pull } from "langchain/hub"; -* -* import OpenAI from 'openai'; -* -* const prompt = await pull("jacob/joke-generator"); -* const formattedPrompt = await prompt.invoke({ -* topic: "cats", -* }); -* -* const { messages } = convertPromptToOpenAI(formattedPrompt); -* -* const openAIClient = new OpenAI(); -* -* const openaiResponse = await openAIClient.chat.completions.create({ -* model: "gpt-4o-mini", -* messages, -* }); -* ``` -* @param formattedPrompt -* @returns A partial OpenAI payload. -*/ -function convertPromptToOpenAI(formattedPrompt) { - const messages = formattedPrompt.toChatMessages(); - return { messages: _convertMessagesToOpenAIParams(messages) }; -} - -//#endregion - -//# sourceMappingURL=prompts.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/index.js - - - - - - - - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./src/providers/openai.provider.ts - -/** - * OpenAI GPT provider implementation - */ -class OpenAIProvider { - name = 'openai'; - apiKey; - constructor(apiKey) { - this.apiKey = apiKey || process.env.OPENAI_API_KEY || ''; - } - isConfigured() { - return !!this.apiKey; - } - getDefaultModel() { - return 'gpt-4-turbo-preview'; - } - getChatModel(config = {}) { - if (!this.isConfigured()) { - throw new Error('OpenAI API key is not configured'); - } - return new ChatOpenAI({ - openAIApiKey: this.apiKey, - modelName: config.model || this.getDefaultModel(), - temperature: config.temperature ?? 0.2, - maxTokens: config.maxTokens ?? 4000, - }); - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/zod_to_genai_parameters.js - - - -//#region src/utils/zod_to_genai_parameters.ts -function removeAdditionalProperties(obj) { - if (typeof obj === "object" && obj !== null) { - const newObj = { ...obj }; - if ("additionalProperties" in newObj) delete newObj.additionalProperties; - if ("$schema" in newObj) delete newObj.$schema; - if ("strict" in newObj) delete newObj.strict; - for (const key in newObj) if (key in newObj) { - if (Array.isArray(newObj[key])) newObj[key] = newObj[key].map(removeAdditionalProperties); - else if (typeof newObj[key] === "object" && newObj[key] !== null) newObj[key] = removeAdditionalProperties(newObj[key]); - } - return newObj; - } - return obj; -} -function schemaToGenerativeAIParameters(schema) { - const jsonSchema = removeAdditionalProperties(isInteropZodSchema(schema) ? toJsonSchema(schema) : schema); - const { $schema,...rest } = jsonSchema; - return rest; -} -function jsonSchemaToGeminiParameters(schema) { - const jsonSchema = removeAdditionalProperties(schema); - const { $schema,...rest } = jsonSchema; - return rest; -} - -//#endregion - -//# sourceMappingURL=zod_to_genai_parameters.js.map -// EXTERNAL MODULE: external "crypto" -var external_crypto_ = __nccwpck_require__(6982); -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/native.js - -/* harmony default export */ const esm_native = ({ randomUUID: external_crypto_.randomUUID }); - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/rng.js - -const rnds8Pool = new Uint8Array(256); -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - (0,external_crypto_.randomFillSync)(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, (poolPtr += 16)); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/stringify.js - -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - return (byteToHex[arr[offset + 0]] + - byteToHex[arr[offset + 1]] + - byteToHex[arr[offset + 2]] + - byteToHex[arr[offset + 3]] + - '-' + - byteToHex[arr[offset + 4]] + - byteToHex[arr[offset + 5]] + - '-' + - byteToHex[arr[offset + 6]] + - byteToHex[arr[offset + 7]] + - '-' + - byteToHex[arr[offset + 8]] + - byteToHex[arr[offset + 9]] + - '-' + - byteToHex[arr[offset + 10]] + - byteToHex[arr[offset + 11]] + - byteToHex[arr[offset + 12]] + - byteToHex[arr[offset + 13]] + - byteToHex[arr[offset + 14]] + - byteToHex[arr[offset + 15]]).toLowerCase(); -} -function esm_stringify_stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - if (!validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -/* harmony default export */ const esm_stringify = ((/* unused pure expression or super */ null && (esm_stringify_stringify))); - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/v4.js - - - -function v4_v4(options, buf, offset) { - if (esm_native.randomUUID && !buf && !options) { - return esm_native.randomUUID(); - } - options = options || {}; - const rnds = options.random ?? options.rng?.() ?? rng(); - if (rnds.length < 16) { - throw new Error('Random bytes length must be >= 16'); - } - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - if (buf) { - offset = offset || 0; - if (offset < 0 || offset + 16 > buf.length) { - throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); - } - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return unsafeStringify(rnds); -} -/* harmony default export */ const esm_v4 = (v4_v4); - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/common.js - - - - - - - -//#region src/utils/common.ts -function getMessageAuthor(message) { - const type = message._getType(); - if (ChatMessage.isInstance(message)) return message.role; - if (type === "tool") return type; - return message.name ?? type; -} -/** -* Maps a message type to a Google Generative AI chat author. -* @param message The message to map. -* @param model The model to use for mapping. -* @returns The message type mapped to a Google Generative AI chat author. -*/ -function convertAuthorToRole(author) { - switch (author) { - case "supervisor": - case "ai": - case "model": return "model"; - case "system": return "system"; - case "human": return "user"; - case "tool": - case "function": return "function"; - default: throw new Error(`Unknown / unsupported author: ${author}`); - } -} -function messageContentMedia(content) { - if ("mimeType" in content && "data" in content) return { inlineData: { - mimeType: content.mimeType, - data: content.data - } }; - if ("mimeType" in content && "fileUri" in content) return { fileData: { - mimeType: content.mimeType, - fileUri: content.fileUri - } }; - throw new Error("Invalid media content"); -} -function inferToolNameFromPreviousMessages(message, previousMessages) { - return previousMessages.map((msg) => { - if (isAIMessage(msg)) return msg.tool_calls ?? []; - return []; - }).flat().find((toolCall) => { - return toolCall.id === message.tool_call_id; - })?.name; -} -function _getStandardContentBlockConverter(isMultimodalModel) { - const standardContentBlockConverter = { - providerName: "Google Gemini", - fromStandardTextBlock(block) { - return { text: block.text }; - }, - fromStandardImageBlock(block) { - if (!isMultimodalModel) throw new Error("This model does not support images"); - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (data) return { inlineData: { - mimeType: data.mime_type, - data: data.data - } }; - else return { fileData: { - mimeType: block.mime_type ?? "", - fileUri: block.url - } }; - } - if (block.source_type === "base64") return { inlineData: { - mimeType: block.mime_type ?? "", - data: block.data - } }; - throw new Error(`Unsupported source type: ${block.source_type}`); - }, - fromStandardAudioBlock(block) { - if (!isMultimodalModel) throw new Error("This model does not support audio"); - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (data) return { inlineData: { - mimeType: data.mime_type, - data: data.data - } }; - else return { fileData: { - mimeType: block.mime_type ?? "", - fileUri: block.url - } }; - } - if (block.source_type === "base64") return { inlineData: { - mimeType: block.mime_type ?? "", - data: block.data - } }; - throw new Error(`Unsupported source type: ${block.source_type}`); - }, - fromStandardFileBlock(block) { - if (!isMultimodalModel) throw new Error("This model does not support files"); - if (block.source_type === "text") return { text: block.text }; - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (data) return { inlineData: { - mimeType: data.mime_type, - data: data.data - } }; - else return { fileData: { - mimeType: block.mime_type ?? "", - fileUri: block.url - } }; - } - if (block.source_type === "base64") return { inlineData: { - mimeType: block.mime_type ?? "", - data: block.data - } }; - throw new Error(`Unsupported source type: ${block.source_type}`); - } - }; - return standardContentBlockConverter; -} -function _convertLangChainContentToPart(content, isMultimodalModel) { - if (isDataContentBlock(content)) return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel)); - if (content.type === "text") return { text: content.text }; - else if (content.type === "executableCode") return { executableCode: content.executableCode }; - else if (content.type === "codeExecutionResult") return { codeExecutionResult: content.codeExecutionResult }; - else if (content.type === "image_url") { - if (!isMultimodalModel) throw new Error(`This model does not support images`); - let source; - if (typeof content.image_url === "string") source = content.image_url; - else if (typeof content.image_url === "object" && "url" in content.image_url) source = content.image_url.url; - else throw new Error("Please provide image as base64 encoded data URL"); - const [dm, data] = source.split(","); - if (!dm.startsWith("data:")) throw new Error("Please provide image as base64 encoded data URL"); - const [mimeType, encoding] = dm.replace(/^data:/, "").split(";"); - if (encoding !== "base64") throw new Error("Please provide image as base64 encoded data URL"); - return { inlineData: { - data, - mimeType - } }; - } else if (content.type === "media") return messageContentMedia(content); - else if (content.type === "tool_use") return { functionCall: { - name: content.name, - args: content.input - } }; - else if (content.type?.includes("/") && content.type.split("/").length === 2 && "data" in content && typeof content.data === "string") return { inlineData: { - mimeType: content.type, - data: content.data - } }; - else if ("functionCall" in content) return void 0; - else if ("type" in content) throw new Error(`Unknown content type ${content.type}`); - else throw new Error(`Unknown content ${JSON.stringify(content)}`); -} -function convertMessageContentToParts(message, isMultimodalModel, previousMessages) { - if (isToolMessage(message)) { - const messageName = message.name ?? inferToolNameFromPreviousMessages(message, previousMessages); - if (messageName === void 0) throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${message.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`); - const result = Array.isArray(message.content) ? message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0) : message.content; - if (message.status === "error") return [{ functionResponse: { - name: messageName, - response: { error: { details: result } } - } }]; - return [{ functionResponse: { - name: messageName, - response: { result } - } }]; - } - let functionCalls = []; - const messageParts = []; - if (typeof message.content === "string" && message.content) messageParts.push({ text: message.content }); - if (Array.isArray(message.content)) messageParts.push(...message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0)); - if (isAIMessage(message) && message.tool_calls?.length) functionCalls = message.tool_calls.map((tc) => { - return { functionCall: { - name: tc.name, - args: tc.args - } }; - }); - return [...messageParts, ...functionCalls]; -} -function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false) { - return messages.reduce((acc, message, index) => { - if (!isBaseMessage(message)) throw new Error("Unsupported message input"); - const author = getMessageAuthor(message); - if (author === "system" && index !== 0) throw new Error("System message should be the first one"); - const role = convertAuthorToRole(author); - const prevContent = acc.content[acc.content.length]; - if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error("Google Generative AI requires alternate messages between authors"); - const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index)); - if (acc.mergeWithPreviousContent) { - const prevContent$1 = acc.content[acc.content.length - 1]; - if (!prevContent$1) throw new Error("There was a problem parsing your system message. Please try a prompt without one."); - prevContent$1.parts.push(...parts); - return { - mergeWithPreviousContent: false, - content: acc.content - }; - } - let actualRole = role; - if (actualRole === "function" || actualRole === "system" && !convertSystemMessageToHumanContent) actualRole = "user"; - const content = { - role: actualRole, - parts - }; - return { - mergeWithPreviousContent: author === "system" && !convertSystemMessageToHumanContent, - content: [...acc.content, content] - }; - }, { - content: [], - mergeWithPreviousContent: false - }).content; -} -function mapGenerateContentResultToChatResult(response, extra) { - if (!response.candidates || response.candidates.length === 0 || !response.candidates[0]) return { - generations: [], - llmOutput: { filters: response.promptFeedback } - }; - const functionCalls = response.functionCalls(); - const [candidate] = response.candidates; - const { content: candidateContent,...generationInfo } = candidate; - let content; - if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length === 1 && candidateContent.parts[0].text) content = candidateContent.parts[0].text; - else if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length > 0) content = candidateContent.parts.map((p) => { - if ("text" in p) return { - type: "text", - text: p.text - }; - else if ("inlineData" in p) return { - type: "inlineData", - inlineData: p.inlineData - }; - else if ("functionCall" in p) return { - type: "functionCall", - functionCall: p.functionCall - }; - else if ("functionResponse" in p) return { - type: "functionResponse", - functionResponse: p.functionResponse - }; - else if ("fileData" in p) return { - type: "fileData", - fileData: p.fileData - }; - else if ("executableCode" in p) return { - type: "executableCode", - executableCode: p.executableCode - }; - else if ("codeExecutionResult" in p) return { - type: "codeExecutionResult", - codeExecutionResult: p.codeExecutionResult - }; - return p; - }); - else content = []; - let text = ""; - if (typeof content === "string") text = content; - else if (Array.isArray(content) && content.length > 0) { - const block = content.find((b) => "text" in b); - text = block?.text ?? text; - } - const generation = { - text, - message: new AIMessage({ - content: content ?? "", - tool_calls: functionCalls?.map((fc) => { - return { - ...fc, - type: "tool_call", - id: "id" in fc && typeof fc.id === "string" ? fc.id : esm_v4() - }; - }), - additional_kwargs: { ...generationInfo }, - usage_metadata: extra?.usageMetadata - }), - generationInfo - }; - return { - generations: [generation], - llmOutput: { tokenUsage: { - promptTokens: extra?.usageMetadata?.input_tokens, - completionTokens: extra?.usageMetadata?.output_tokens, - totalTokens: extra?.usageMetadata?.total_tokens - } } - }; -} -function convertResponseContentToChatGenerationChunk(response, extra) { - if (!response.candidates || response.candidates.length === 0) return null; - const functionCalls = response.functionCalls(); - const [candidate] = response.candidates; - const { content: candidateContent,...generationInfo } = candidate; - let content; - if (Array.isArray(candidateContent?.parts) && candidateContent.parts.every((p) => "text" in p)) content = candidateContent.parts.map((p) => p.text).join(""); - else if (Array.isArray(candidateContent?.parts)) content = candidateContent.parts.map((p) => { - if ("text" in p) return { - type: "text", - text: p.text - }; - else if ("inlineData" in p) return { - type: "inlineData", - inlineData: p.inlineData - }; - else if ("functionCall" in p) return { - type: "functionCall", - functionCall: p.functionCall - }; - else if ("functionResponse" in p) return { - type: "functionResponse", - functionResponse: p.functionResponse - }; - else if ("fileData" in p) return { - type: "fileData", - fileData: p.fileData - }; - else if ("executableCode" in p) return { - type: "executableCode", - executableCode: p.executableCode - }; - else if ("codeExecutionResult" in p) return { - type: "codeExecutionResult", - codeExecutionResult: p.codeExecutionResult - }; - return p; - }); - else content = []; - let text = ""; - if (content && typeof content === "string") text = content; - else if (Array.isArray(content)) { - const block = content.find((b) => "text" in b); - text = block?.text ?? ""; - } - const toolCallChunks = []; - if (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({ - ...fc, - args: JSON.stringify(fc.args), - index: extra.index, - type: "tool_call_chunk", - id: "id" in fc && typeof fc.id === "string" ? fc.id : esm_v4() - }))); - return new ChatGenerationChunk({ - text, - message: new AIMessageChunk({ - content: content || "", - name: !candidateContent ? void 0 : candidateContent.role, - tool_call_chunks: toolCallChunks, - additional_kwargs: {}, - response_metadata: { model_provider: "google-genai" }, - usage_metadata: extra.usageMetadata - }), - generationInfo - }); -} -function convertToGenerativeAITools(tools) { - if (tools.every((tool) => "functionDeclarations" in tool && Array.isArray(tool.functionDeclarations))) return tools; - return [{ functionDeclarations: tools.map((tool) => { - if (isLangChainTool(tool)) { - const jsonSchema = schemaToGenerativeAIParameters(tool.schema); - if (jsonSchema.type === "object" && "properties" in jsonSchema && Object.keys(jsonSchema.properties).length === 0) return { - name: tool.name, - description: tool.description - }; - return { - name: tool.name, - description: tool.description, - parameters: jsonSchema - }; - } - if (isOpenAITool(tool)) return { - name: tool.function.name, - description: tool.function.description ?? `A function available to call.`, - parameters: jsonSchemaToGeminiParameters(tool.function.parameters) - }; - return tool; - }) }]; -} - -//#endregion - -//# sourceMappingURL=common.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/output_parsers.js - - - -//#region src/output_parsers.ts -var GoogleGenerativeAIToolsOutputParser = class extends BaseLLMOutputParser { - static lc_name() { - return "GoogleGenerativeAIToolsOutputParser"; - } - lc_namespace = [ - "langchain", - "google_genai", - "output_parsers" - ]; - returnId = false; - /** The type of tool calls to return. */ - keyName; - /** Whether to return only the first tool call. */ - returnSingle = false; - zodSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - } - async _validateResult(result) { - if (this.zodSchema === void 0) return result; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); - if (zodParsedResult.success) return zodParsedResult.data; - else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(result, null, 2)); - } - async parseResult(generations) { - const tools = generations.flatMap((generation) => { - const { message } = generation; - if (!("tool_calls" in message) || !Array.isArray(message.tool_calls)) return []; - return message.tool_calls; - }); - if (tools[0] === void 0) throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser."); - const [tool] = tools; - const validatedResult = await this._validateResult(tool.args); - return validatedResult; - } -}; - -//#endregion - -//# sourceMappingURL=output_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@google/generative-ai/dist/index.mjs -/** - * Contains the list of OpenAPI data types - * as defined by https://swagger.io/docs/specification/data-models/data-types/ - * @public - */ -var SchemaType; -(function (SchemaType) { - /** String type. */ - SchemaType["STRING"] = "string"; - /** Number type. */ - SchemaType["NUMBER"] = "number"; - /** Integer type. */ - SchemaType["INTEGER"] = "integer"; - /** Boolean type. */ - SchemaType["BOOLEAN"] = "boolean"; - /** Array type. */ - SchemaType["ARRAY"] = "array"; - /** Object type. */ - SchemaType["OBJECT"] = "object"; -})(SchemaType || (SchemaType = {})); - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @public - */ -var ExecutableCodeLanguage; -(function (ExecutableCodeLanguage) { - ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified"; - ExecutableCodeLanguage["PYTHON"] = "python"; -})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {})); -/** - * Possible outcomes of code execution. - * @public - */ -var Outcome; -(function (Outcome) { - /** - * Unspecified status. This value should not be used. - */ - Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified"; - /** - * Code execution completed successfully. - */ - Outcome["OUTCOME_OK"] = "outcome_ok"; - /** - * Code execution finished but with a failure. `stderr` should contain the - * reason. - */ - Outcome["OUTCOME_FAILED"] = "outcome_failed"; - /** - * Code execution ran for too long, and was cancelled. There may or may not - * be a partial output present. - */ - Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded"; -})(Outcome || (Outcome = {})); - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Possible roles. - * @public - */ -const POSSIBLE_ROLES = ["user", "model", "function", "system"]; -/** - * Harm categories that would cause prompts or candidates to be blocked. - * @public - */ -var HarmCategory; -(function (HarmCategory) { - HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; - HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; - HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; - HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; - HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; - HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; -})(HarmCategory || (HarmCategory = {})); -/** - * Threshold above which a prompt or candidate will be blocked. - * @public - */ -var HarmBlockThreshold; -(function (HarmBlockThreshold) { - /** Threshold is unspecified. */ - HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; - /** Content with NEGLIGIBLE will be allowed. */ - HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; - /** Content with NEGLIGIBLE and LOW will be allowed. */ - HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; - /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */ - HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; - /** All content will be allowed. */ - HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; -})(HarmBlockThreshold || (HarmBlockThreshold = {})); -/** - * Probability that a prompt or candidate matches a harm category. - * @public - */ -var HarmProbability; -(function (HarmProbability) { - /** Probability is unspecified. */ - HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; - /** Content has a negligible chance of being unsafe. */ - HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; - /** Content has a low chance of being unsafe. */ - HarmProbability["LOW"] = "LOW"; - /** Content has a medium chance of being unsafe. */ - HarmProbability["MEDIUM"] = "MEDIUM"; - /** Content has a high chance of being unsafe. */ - HarmProbability["HIGH"] = "HIGH"; -})(HarmProbability || (HarmProbability = {})); -/** - * Reason that a prompt was blocked. - * @public - */ -var BlockReason; -(function (BlockReason) { - // A blocked reason was not specified. - BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; - // Content was blocked by safety settings. - BlockReason["SAFETY"] = "SAFETY"; - // Content was blocked, but the reason is uncategorized. - BlockReason["OTHER"] = "OTHER"; -})(BlockReason || (BlockReason = {})); -/** - * Reason that a candidate finished. - * @public - */ -var FinishReason; -(function (FinishReason) { - // Default value. This value is unused. - FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; - // Natural stop point of the model or provided stop sequence. - FinishReason["STOP"] = "STOP"; - // The maximum number of tokens as specified in the request was reached. - FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; - // The candidate content was flagged for safety reasons. - FinishReason["SAFETY"] = "SAFETY"; - // The candidate content was flagged for recitation reasons. - FinishReason["RECITATION"] = "RECITATION"; - // The candidate content was flagged for using an unsupported language. - FinishReason["LANGUAGE"] = "LANGUAGE"; - // Token generation stopped because the content contains forbidden terms. - FinishReason["BLOCKLIST"] = "BLOCKLIST"; - // Token generation stopped for potentially containing prohibited content. - FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; - // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). - FinishReason["SPII"] = "SPII"; - // The function call generated by the model is invalid. - FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; - // Unknown reason. - FinishReason["OTHER"] = "OTHER"; -})(FinishReason || (FinishReason = {})); -/** - * Task type for embedding content. - * @public - */ -var TaskType; -(function (TaskType) { - TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED"; - TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY"; - TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT"; - TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY"; - TaskType["CLASSIFICATION"] = "CLASSIFICATION"; - TaskType["CLUSTERING"] = "CLUSTERING"; -})(TaskType || (TaskType = {})); -/** - * @public - */ -var FunctionCallingMode; -(function (FunctionCallingMode) { - // Unspecified function calling mode. This value should not be used. - FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; - // Default model behavior, model decides to predict either a function call - // or a natural language repspose. - FunctionCallingMode["AUTO"] = "AUTO"; - // Model is constrained to always predicting a function call only. - // If "allowed_function_names" are set, the predicted function call will be - // limited to any one of "allowed_function_names", else the predicted - // function call will be any one of the provided "function_declarations". - FunctionCallingMode["ANY"] = "ANY"; - // Model will not predict any function call. Model behavior is same as when - // not passing any function declarations. - FunctionCallingMode["NONE"] = "NONE"; -})(FunctionCallingMode || (FunctionCallingMode = {})); -/** - * The mode of the predictor to be used in dynamic retrieval. - * @public - */ -var DynamicRetrievalMode; -(function (DynamicRetrievalMode) { - // Unspecified function calling mode. This value should not be used. - DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; - // Run retrieval only when system decides it is necessary. - DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; -})(DynamicRetrievalMode || (DynamicRetrievalMode = {})); - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Basic error type for this SDK. - * @public - */ -class GoogleGenerativeAIError extends Error { - constructor(message) { - super(`[GoogleGenerativeAI Error]: ${message}`); - } -} -/** - * Errors in the contents of a response from the model. This includes parsing - * errors, or responses including a safety block reason. - * @public - */ -class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError { - constructor(message, response) { - super(message); - this.response = response; - } -} -/** - * Error class covering HTTP errors when calling the server. Includes HTTP - * status, statusText, and optional details, if provided in the server response. - * @public - */ -class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError { - constructor(message, status, statusText, errorDetails) { - super(message); - this.status = status; - this.statusText = statusText; - this.errorDetails = errorDetails; - } -} -/** - * Errors in the contents of a request originating from user input. - * @public - */ -class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError { -} -/** - * Error thrown when a request is aborted, either due to a timeout or - * intentional cancellation by the user. - * @public - */ -class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError { -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com"; -const DEFAULT_API_VERSION = "v1beta"; -/** - * We can't `require` package.json if this runs on web. We will use rollup to - * swap in the version number here at build time. - */ -const PACKAGE_VERSION = "0.24.1"; -const PACKAGE_LOG_HEADER = "genai-js"; -var Task; -(function (Task) { - Task["GENERATE_CONTENT"] = "generateContent"; - Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent"; - Task["COUNT_TOKENS"] = "countTokens"; - Task["EMBED_CONTENT"] = "embedContent"; - Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents"; -})(Task || (Task = {})); -class RequestUrl { - constructor(model, task, apiKey, stream, requestOptions) { - this.model = model; - this.task = task; - this.apiKey = apiKey; - this.stream = stream; - this.requestOptions = requestOptions; - } - toString() { - var _a, _b; - const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION; - const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL; - let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`; - if (this.stream) { - url += "?alt=sse"; - } - return url; - } -} -/** - * Simple, but may become more complex if we add more versions to log. - */ -function getClientHeaders(requestOptions) { - const clientHeaders = []; - if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) { - clientHeaders.push(requestOptions.apiClient); - } - clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`); - return clientHeaders.join(" "); -} -async function getHeaders(url) { - var _a; - const headers = new Headers(); - headers.append("Content-Type", "application/json"); - headers.append("x-goog-api-client", getClientHeaders(url.requestOptions)); - headers.append("x-goog-api-key", url.apiKey); - let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders; - if (customHeaders) { - if (!(customHeaders instanceof Headers)) { - try { - customHeaders = new Headers(customHeaders); - } - catch (e) { - throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`); - } - } - for (const [headerName, headerValue] of customHeaders.entries()) { - if (headerName === "x-goog-api-key") { - throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`); - } - else if (headerName === "x-goog-api-client") { - throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`); - } - headers.append(headerName, headerValue); - } - } - return headers; -} -async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) { - const url = new RequestUrl(model, task, apiKey, stream, requestOptions); - return { - url: url.toString(), - fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }), - }; -} -async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, -// Allows this to be stubbed for tests -fetchFn = fetch) { - const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions); - return makeRequest(url, fetchOptions, fetchFn); -} -async function makeRequest(url, fetchOptions, fetchFn = fetch) { - let response; - try { - response = await fetchFn(url, fetchOptions); - } - catch (e) { - handleResponseError(e, url); - } - if (!response.ok) { - await handleResponseNotOk(response, url); - } - return response; -} -function handleResponseError(e, url) { - let err = e; - if (err.name === "AbortError") { - err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`); - err.stack = e.stack; - } - else if (!(e instanceof GoogleGenerativeAIFetchError || - e instanceof GoogleGenerativeAIRequestInputError)) { - err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`); - err.stack = e.stack; - } - throw err; -} -async function handleResponseNotOk(response, url) { - let message = ""; - let errorDetails; - try { - const json = await response.json(); - message = json.error.message; - if (json.error.details) { - message += ` ${JSON.stringify(json.error.details)}`; - errorDetails = json.error.details; - } - } - catch (e) { - // ignored - } - throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails); -} -/** - * Generates the request options to be passed to the fetch API. - * @param requestOptions - The user-defined request options. - * @returns The generated request options. - */ -function buildFetchOptions(requestOptions) { - const fetchOptions = {}; - if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) { - const controller = new AbortController(); - if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) { - setTimeout(() => controller.abort(), requestOptions.timeout); - } - if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) { - requestOptions.signal.addEventListener("abort", () => { - controller.abort(); - }); - } - fetchOptions.signal = controller.signal; - } - return fetchOptions; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Adds convenience helper methods to a response object, including stream - * chunks (as long as each chunk is a complete GenerateContentResponse JSON). - */ -function addHelpers(response) { - response.text = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + - `candidates. Returning text from the first candidate only. ` + - `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - return getText(response); - } - else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response); - } - return ""; - }; - /** - * TODO: remove at next major version - */ - response.functionCall = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + - `candidates. Returning function calls from the first candidate only. ` + - `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - console.warn(`response.functionCall() is deprecated. ` + - `Use response.functionCalls() instead.`); - return getFunctionCalls(response)[0]; - } - else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); - } - return undefined; - }; - response.functionCalls = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + - `candidates. Returning function calls from the first candidate only. ` + - `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - return getFunctionCalls(response); - } - else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); - } - return undefined; - }; - return response; -} -/** - * Returns all text found in all parts of first candidate. - */ -function getText(response) { - var _a, _b, _c, _d; - const textStrings = []; - if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) { - for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) { - if (part.text) { - textStrings.push(part.text); - } - if (part.executableCode) { - textStrings.push("\n```" + - part.executableCode.language + - "\n" + - part.executableCode.code + - "\n```\n"); - } - if (part.codeExecutionResult) { - textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n"); - } - } - } - if (textStrings.length > 0) { - return textStrings.join(""); - } - else { - return ""; - } -} -/** - * Returns functionCall of first candidate. - */ -function getFunctionCalls(response) { - var _a, _b, _c, _d; - const functionCalls = []; - if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) { - for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) { - if (part.functionCall) { - functionCalls.push(part.functionCall); - } - } - } - if (functionCalls.length > 0) { - return functionCalls; - } - else { - return undefined; - } -} -const badFinishReasons = [ - FinishReason.RECITATION, - FinishReason.SAFETY, - FinishReason.LANGUAGE, -]; -function hadBadFinishReason(candidate) { - return (!!candidate.finishReason && - badFinishReasons.includes(candidate.finishReason)); -} -function formatBlockErrorMessage(response) { - var _a, _b, _c; - let message = ""; - if ((!response.candidates || response.candidates.length === 0) && - response.promptFeedback) { - message += "Response was blocked"; - if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) { - message += ` due to ${response.promptFeedback.blockReason}`; - } - if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) { - message += `: ${response.promptFeedback.blockReasonMessage}`; - } - } - else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) { - const firstCandidate = response.candidates[0]; - if (hadBadFinishReason(firstCandidate)) { - message += `Candidate was blocked due to ${firstCandidate.finishReason}`; - if (firstCandidate.finishMessage) { - message += `: ${firstCandidate.finishMessage}`; - } - } - } - return message; -} - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol */ - - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/; -/** - * Process a response.body stream from the backend and return an - * iterator that provides one complete GenerateContentResponse at a time - * and a promise that resolves with a single aggregated - * GenerateContentResponse. - * - * @param response - Response from a fetch call - */ -function processStream(response) { - const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true })); - const responseStream = getResponseStream(inputStream); - const [stream1, stream2] = responseStream.tee(); - return { - stream: generateResponseSequence(stream1), - response: getResponsePromise(stream2), - }; -} -async function getResponsePromise(stream) { - const allResponses = []; - const reader = stream.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - return addHelpers(aggregateResponses(allResponses)); - } - allResponses.push(value); - } -} -function generateResponseSequence(stream) { - return __asyncGenerator(this, arguments, function* generateResponseSequence_1() { - const reader = stream.getReader(); - while (true) { - const { value, done } = yield __await(reader.read()); - if (done) { - break; - } - yield yield __await(addHelpers(value)); - } - }); -} -/** - * Reads a raw stream from the fetch response and join incomplete - * chunks, returning a new stream that provides a single complete - * GenerateContentResponse in each iteration. - */ -function getResponseStream(inputStream) { - const reader = inputStream.getReader(); - const stream = new ReadableStream({ - start(controller) { - let currentText = ""; - return pump(); - function pump() { - return reader - .read() - .then(({ value, done }) => { - if (done) { - if (currentText.trim()) { - controller.error(new GoogleGenerativeAIError("Failed to parse stream")); - return; - } - controller.close(); - return; - } - currentText += value; - let match = currentText.match(responseLineRE); - let parsedResponse; - while (match) { - try { - parsedResponse = JSON.parse(match[1]); - } - catch (e) { - controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`)); - return; - } - controller.enqueue(parsedResponse); - currentText = currentText.substring(match[0].length); - match = currentText.match(responseLineRE); - } - return pump(); - }) - .catch((e) => { - let err = e; - err.stack = e.stack; - if (err.name === "AbortError") { - err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream"); - } - else { - err = new GoogleGenerativeAIError("Error reading from the stream"); - } - throw err; - }); - } - }, - }); - return stream; -} -/** - * Aggregates an array of `GenerateContentResponse`s into a single - * GenerateContentResponse. - */ -function aggregateResponses(responses) { - const lastResponse = responses[responses.length - 1]; - const aggregatedResponse = { - promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback, - }; - for (const response of responses) { - if (response.candidates) { - let candidateIndex = 0; - for (const candidate of response.candidates) { - if (!aggregatedResponse.candidates) { - aggregatedResponse.candidates = []; - } - if (!aggregatedResponse.candidates[candidateIndex]) { - aggregatedResponse.candidates[candidateIndex] = { - index: candidateIndex, - }; - } - // Keep overwriting, the last one will be final - aggregatedResponse.candidates[candidateIndex].citationMetadata = - candidate.citationMetadata; - aggregatedResponse.candidates[candidateIndex].groundingMetadata = - candidate.groundingMetadata; - aggregatedResponse.candidates[candidateIndex].finishReason = - candidate.finishReason; - aggregatedResponse.candidates[candidateIndex].finishMessage = - candidate.finishMessage; - aggregatedResponse.candidates[candidateIndex].safetyRatings = - candidate.safetyRatings; - /** - * Candidates should always have content and parts, but this handles - * possible malformed responses. - */ - if (candidate.content && candidate.content.parts) { - if (!aggregatedResponse.candidates[candidateIndex].content) { - aggregatedResponse.candidates[candidateIndex].content = { - role: candidate.content.role || "user", - parts: [], - }; - } - const newPart = {}; - for (const part of candidate.content.parts) { - if (part.text) { - newPart.text = part.text; - } - if (part.functionCall) { - newPart.functionCall = part.functionCall; - } - if (part.executableCode) { - newPart.executableCode = part.executableCode; - } - if (part.codeExecutionResult) { - newPart.codeExecutionResult = part.codeExecutionResult; - } - if (Object.keys(newPart).length === 0) { - newPart.text = ""; - } - aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart); - } - } - } - candidateIndex++; - } - if (response.usageMetadata) { - aggregatedResponse.usageMetadata = response.usageMetadata; - } - } - return aggregatedResponse; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -async function generateContentStream(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, - /* stream */ true, JSON.stringify(params), requestOptions); - return processStream(response); -} -async function generateContent(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, - /* stream */ false, JSON.stringify(params), requestOptions); - const responseJson = await response.json(); - const enhancedResponse = addHelpers(responseJson); - return { - response: enhancedResponse, - }; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function formatSystemInstruction(input) { - // null or undefined - if (input == null) { - return undefined; - } - else if (typeof input === "string") { - return { role: "system", parts: [{ text: input }] }; - } - else if (input.text) { - return { role: "system", parts: [input] }; - } - else if (input.parts) { - if (!input.role) { - return { role: "system", parts: input.parts }; - } - else { - return input; - } - } -} -function formatNewContent(request) { - let newParts = []; - if (typeof request === "string") { - newParts = [{ text: request }]; - } - else { - for (const partOrString of request) { - if (typeof partOrString === "string") { - newParts.push({ text: partOrString }); - } - else { - newParts.push(partOrString); - } - } - } - return assignRoleToPartsAndValidateSendMessageRequest(newParts); -} -/** - * When multiple Part types (i.e. FunctionResponsePart and TextPart) are - * passed in a single Part array, we may need to assign different roles to each - * part. Currently only FunctionResponsePart requires a role other than 'user'. - * @private - * @param parts Array of parts to pass to the model - * @returns Array of content items - */ -function assignRoleToPartsAndValidateSendMessageRequest(parts) { - const userContent = { role: "user", parts: [] }; - const functionContent = { role: "function", parts: [] }; - let hasUserContent = false; - let hasFunctionContent = false; - for (const part of parts) { - if ("functionResponse" in part) { - functionContent.parts.push(part); - hasFunctionContent = true; - } - else { - userContent.parts.push(part); - hasUserContent = true; - } - } - if (hasUserContent && hasFunctionContent) { - throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."); - } - if (!hasUserContent && !hasFunctionContent) { - throw new GoogleGenerativeAIError("No content is provided for sending chat message."); - } - if (hasUserContent) { - return userContent; - } - return functionContent; -} -function formatCountTokensInput(params, modelParams) { - var _a; - let formattedGenerateContentRequest = { - model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model, - generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig, - safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings, - tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools, - toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig, - systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction, - cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name, - contents: [], - }; - const containsGenerateContentRequest = params.generateContentRequest != null; - if (params.contents) { - if (containsGenerateContentRequest) { - throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both."); - } - formattedGenerateContentRequest.contents = params.contents; - } - else if (containsGenerateContentRequest) { - formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest); - } - else { - // Array or string - const content = formatNewContent(params); - formattedGenerateContentRequest.contents = [content]; - } - return { generateContentRequest: formattedGenerateContentRequest }; -} -function formatGenerateContentInput(params) { - let formattedRequest; - if (params.contents) { - formattedRequest = params; - } - else { - // Array or string - const content = formatNewContent(params); - formattedRequest = { contents: [content] }; - } - if (params.systemInstruction) { - formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction); - } - return formattedRequest; -} -function formatEmbedContentInput(params) { - if (typeof params === "string" || Array.isArray(params)) { - const content = formatNewContent(params); - return { content }; - } - return params; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// https://ai.google.dev/api/rest/v1beta/Content#part -const VALID_PART_FIELDS = [ - "text", - "inlineData", - "functionCall", - "functionResponse", - "executableCode", - "codeExecutionResult", -]; -const VALID_PARTS_PER_ROLE = { - user: ["text", "inlineData"], - function: ["functionResponse"], - model: ["text", "functionCall", "executableCode", "codeExecutionResult"], - // System instructions shouldn't be in history anyway. - system: ["text"], -}; -function validateChatHistory(history) { - let prevContent = false; - for (const currContent of history) { - const { role, parts } = currContent; - if (!prevContent && role !== "user") { - throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`); - } - if (!POSSIBLE_ROLES.includes(role)) { - throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`); - } - if (!Array.isArray(parts)) { - throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts"); - } - if (parts.length === 0) { - throw new GoogleGenerativeAIError("Each Content should have at least one part"); - } - const countFields = { - text: 0, - inlineData: 0, - functionCall: 0, - functionResponse: 0, - fileData: 0, - executableCode: 0, - codeExecutionResult: 0, - }; - for (const part of parts) { - for (const key of VALID_PART_FIELDS) { - if (key in part) { - countFields[key] += 1; - } - } - } - const validParts = VALID_PARTS_PER_ROLE[role]; - for (const key of VALID_PART_FIELDS) { - if (!validParts.includes(key) && countFields[key] > 0) { - throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`); - } - } - prevContent = true; - } -} -/** - * Returns true if the response is valid (could be appended to the history), flase otherwise. - */ -function isValidResponse(response) { - var _a; - if (response.candidates === undefined || response.candidates.length === 0) { - return false; - } - const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; - if (content === undefined) { - return false; - } - if (content.parts === undefined || content.parts.length === 0) { - return false; - } - for (const part of content.parts) { - if (part === undefined || Object.keys(part).length === 0) { - return false; - } - if (part.text !== undefined && part.text === "") { - return false; - } - } - return true; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Do not log a message for this error. - */ -const SILENT_ERROR = "SILENT_ERROR"; +import { PRAnalyzerAgent } from './agents/pr-analyzer-agent.js'; +const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase(); +const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY; +const model = process.env.AI_MODEL; /** - * ChatSession class that enables sending chat messages and stores - * history of sent and received messages so far. - * - * @public + * Format agent analysis result for GitHub comment */ -class ChatSession { - constructor(apiKey, model, params, _requestOptions = {}) { - this.model = model; - this.params = params; - this._requestOptions = _requestOptions; - this._history = []; - this._sendPromise = Promise.resolve(); - this._apiKey = apiKey; - if (params === null || params === void 0 ? void 0 : params.history) { - validateChatHistory(params.history); - this._history = params.history; - } - } - /** - * Gets the chat history so far. Blocked prompts are not added to history. - * Blocked candidates are not added to history, nor are the prompts that - * generated them. - */ - async getHistory() { - await this._sendPromise; - return this._history; - } - /** - * Sends a chat message and receives a non-streaming - * {@link GenerateContentResult}. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async sendMessage(request, requestOptions = {}) { - var _a, _b, _c, _d, _e, _f; - await this._sendPromise; - const newContent = formatNewContent(request); - const generateContentRequest = { - safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, - generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, - tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, - toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig, - systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction, - cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent, - contents: [...this._history, newContent], - }; - const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - let finalResult; - // Add onto the chain. - this._sendPromise = this._sendPromise - .then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)) - .then((result) => { - var _a; - if (isValidResponse(result.response)) { - this._history.push(newContent); - const responseContent = Object.assign({ parts: [], - // Response seems to come back without a role set. - role: "model" }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content); - this._history.push(responseContent); - } - else { - const blockErrorMessage = formatBlockErrorMessage(result.response); - if (blockErrorMessage) { - console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); - } - } - finalResult = result; - }) - .catch((e) => { - // Resets _sendPromise to avoid subsequent calls failing and throw error. - this._sendPromise = Promise.resolve(); - throw e; - }); - await this._sendPromise; - return finalResult; +function formatAnalysisForGitHub(result) { + let output = ''; + // Summary + if (result.summary) { + output += `### 📋 Summary\n${result.summary}\n\n`; } - /** - * Sends a chat message and receives the response as a - * {@link GenerateContentStreamResult} containing an iterable stream - * and a response promise. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async sendMessageStream(request, requestOptions = {}) { - var _a, _b, _c, _d, _e, _f; - await this._sendPromise; - const newContent = formatNewContent(request); - const generateContentRequest = { - safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, - generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, - tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, - toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig, - systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction, - cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent, - contents: [...this._history, newContent], - }; - const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions); - // Add onto the chain. - this._sendPromise = this._sendPromise - .then(() => streamPromise) - // This must be handled to avoid unhandled rejection, but jump - // to the final catch block with a label to not log this error. - .catch((_ignored) => { - throw new Error(SILENT_ERROR); - }) - .then((streamResult) => streamResult.response) - .then((response) => { - if (isValidResponse(response)) { - this._history.push(newContent); - const responseContent = Object.assign({}, response.candidates[0].content); - // Response seems to come back without a role set. - if (!responseContent.role) { - responseContent.role = "model"; - } - this._history.push(responseContent); - } - else { - const blockErrorMessage = formatBlockErrorMessage(response); - if (blockErrorMessage) { - console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); - } - } - }) - .catch((e) => { - // Errors in streamPromise are already catchable by the user as - // streamPromise is returned. - // Avoid duplicating the error message in logs. - if (e.message !== SILENT_ERROR) { - // Users do not have access to _sendPromise to catch errors - // downstream from streamPromise, so they should not throw. - console.error(e); - } + // Risks + if (result.overallRisks && result.overallRisks.length > 0) { + output += `### ⚠️ Risks Identified\n`; + result.overallRisks.forEach((risk, i) => { + output += `${i + 1}. ${risk}\n`; }); - return streamPromise; - } -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -async function countTokens(apiKey, model, params, singleRequestOptions) { - const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions); - return response.json(); -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -async function embedContent(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); - return response.json(); -} -async function batchEmbedContents(apiKey, model, params, requestOptions) { - const requestsWithModel = params.requests.map((request) => { - return Object.assign(Object.assign({}, request), { model }); - }); - const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions); - return response.json(); -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class for generative model APIs. - * @public - */ -class GenerativeModel { - constructor(apiKey, modelParams, _requestOptions = {}) { - this.apiKey = apiKey; - this._requestOptions = _requestOptions; - if (modelParams.model.includes("/")) { - // Models may be named "models/model-name" or "tunedModels/model-name" - this.model = modelParams.model; - } - else { - // If path is not included, assume it's a non-tuned model. - this.model = `models/${modelParams.model}`; - } - this.generationConfig = modelParams.generationConfig || {}; - this.safetySettings = modelParams.safetySettings || []; - this.tools = modelParams.tools; - this.toolConfig = modelParams.toolConfig; - this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction); - this.cachedContent = modelParams.cachedContent; - } - /** - * Makes a single non-streaming call to the model - * and returns an object containing a single {@link GenerateContentResponse}. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async generateContent(request, requestOptions = {}) { - var _a; - const formattedParams = formatGenerateContentInput(request); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions); - } - /** - * Makes a single streaming call to the model and returns an object - * containing an iterable stream that iterates over all chunks in the - * streaming response as well as a promise that returns the final - * aggregated response. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async generateContentStream(request, requestOptions = {}) { - var _a; - const formattedParams = formatGenerateContentInput(request); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions); + output += '\n'; } - /** - * Gets a new {@link ChatSession} instance which can be used for - * multi-turn chats. - */ - startChat(startChatParams) { - var _a; - return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions); + // Complexity + if (result.overallComplexity) { + output += `### 📊 Complexity Score: ${result.overallComplexity}/5\n\n`; } - /** - * Counts the tokens in the provided request. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async countTokens(request, requestOptions = {}) { - const formattedParams = formatCountTokensInput(request, { - model: this.model, - generationConfig: this.generationConfig, - safetySettings: this.safetySettings, - tools: this.tools, - toolConfig: this.toolConfig, - systemInstruction: this.systemInstruction, - cachedContent: this.cachedContent, + // Recommendations + if (result.recommendations && result.recommendations.length > 0) { + output += `### 💡 Recommendations\n`; + result.recommendations.forEach((rec, i) => { + output += `${i + 1}. ${rec}\n`; }); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); - } - /** - * Embeds the provided content. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async embedContent(request, requestOptions = {}) { - const formattedParams = formatEmbedContentInput(request); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); - } - /** - * Embeds an array of {@link EmbedContentRequest}s. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) { - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions); - } -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Top-level class for this SDK - * @public - */ -class GoogleGenerativeAI { - constructor(apiKey) { - this.apiKey = apiKey; - } - /** - * Gets a {@link GenerativeModel} instance for the provided model name. - */ - getGenerativeModel(modelParams, requestOptions) { - if (!modelParams.model) { - throw new GoogleGenerativeAIError(`Must provide a model name. ` + - `Example: genai.getGenerativeModel({ model: 'my-model-name' })`); - } - return new GenerativeModel(this.apiKey, modelParams, requestOptions); + output += '\n'; } - /** - * Creates a {@link GenerativeModel} instance from provided content cache. - */ - getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) { - if (!cachedContent.name) { - throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field."); - } - if (!cachedContent.model) { - throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field."); - } - /** - * Not checking tools and toolConfig for now as it would require a deep - * equality comparison and isn't likely to be a common case. - */ - const disallowedDuplicates = ["model", "systemInstruction"]; - for (const key of disallowedDuplicates) { - if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && - cachedContent[key] && - (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) { - if (key === "model") { - const modelParamsComp = modelParams.model.startsWith("models/") - ? modelParams.model.replace("models/", "") - : modelParams.model; - const cachedContentComp = cachedContent.model.startsWith("models/") - ? cachedContent.model.replace("models/", "") - : cachedContent.model; - if (modelParamsComp === cachedContentComp) { - continue; - } + // File-level details (top 5 most complex) + if (result.fileAnalyses && result.fileAnalyses.size > 0) { + const files = Array.from(result.fileAnalyses.entries()); + const sortedFiles = files + .sort((a, b) => b[1].complexity - a[1].complexity) + .slice(0, 5); + if (sortedFiles.length > 0) { + output += `### 📁 Files of Interest\n`; + sortedFiles.forEach(([path, analysis]) => { + output += `- **${path}** (complexity: ${analysis.complexity}/5)\n`; + if (analysis.risks && analysis.risks.length > 0) { + output += ` - ⚠️ ${analysis.risks.join(', ')}\n`; } - throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` + - ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`); - } - } - const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent }); - return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions); - } -} - - -//# sourceMappingURL=index.mjs.map - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/tools.js - - - - - - -//#region src/utils/tools.ts -function convertToolsToGenAI(tools, extra) { - const genAITools = processTools(tools); - const toolConfig = createToolConfig(genAITools, extra); - return { - tools: genAITools, - toolConfig - }; -} -function processTools(tools) { - let functionDeclarationTools = []; - const genAITools = []; - tools.forEach((tool) => { - if (isLangChainTool(tool)) { - const [convertedTool] = convertToGenerativeAITools([tool]); - if (convertedTool.functionDeclarations) functionDeclarationTools.push(...convertedTool.functionDeclarations); - } else if (isOpenAITool(tool)) { - const { functionDeclarations } = convertOpenAIToolToGenAI(tool); - if (functionDeclarations) functionDeclarationTools.push(...functionDeclarations); - else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool"); - } else genAITools.push(tool); - }); - const genAIFunctionDeclaration = genAITools.find((t) => "functionDeclarations" in t); - if (genAIFunctionDeclaration) return genAITools.map((tool) => { - if (functionDeclarationTools?.length > 0 && "functionDeclarations" in tool) { - const newTool = { functionDeclarations: [...tool.functionDeclarations || [], ...functionDeclarationTools] }; - functionDeclarationTools = []; - return newTool; - } - return tool; - }); - return [...genAITools, ...functionDeclarationTools.length > 0 ? [{ functionDeclarations: functionDeclarationTools }] : []]; -} -function convertOpenAIToolToGenAI(tool) { - return { functionDeclarations: [{ - name: tool.function.name, - description: tool.function.description, - parameters: removeAdditionalProperties(tool.function.parameters) - }] }; -} -function createToolConfig(genAITools, extra) { - if (!genAITools.length || !extra) return void 0; - const { toolChoice, allowedFunctionNames } = extra; - const modeMap = { - any: FunctionCallingMode.ANY, - auto: FunctionCallingMode.AUTO, - none: FunctionCallingMode.NONE - }; - if (toolChoice && [ - "any", - "auto", - "none" - ].includes(toolChoice)) return { functionCallingConfig: { - mode: modeMap[toolChoice] ?? "MODE_UNSPECIFIED", - allowedFunctionNames - } }; - if (typeof toolChoice === "string" || allowedFunctionNames) return { functionCallingConfig: { - mode: FunctionCallingMode.ANY, - allowedFunctionNames: [...allowedFunctionNames ?? [], ...toolChoice && typeof toolChoice === "string" ? [toolChoice] : []] - } }; - return void 0; -} - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/chat_models.js - - - - - - - - - - - -//#region src/chat_models.ts -/** -* Google Generative AI chat model integration. -* -* Setup: -* Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`. -* -* ```bash -* npm install @langchain/google-genai -* export GOOGLE_API_KEY="your-api-key" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.withConfig`, call options should be passed via the first argument -* const llmWithArgsBound = llm.withConfig({ -* stop: ["\n"], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* stop: ["\n"], -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { ChatGoogleGenerativeAI } from '@langchain/google-genai'; -* -* const llm = new ChatGoogleGenerativeAI({ -* model: "gemini-1.5-flash", -* temperature: 0, -* maxRetries: 2, -* // apiKey: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n", -* "response_metadata": { -* "finishReason": "STOP", -* "index": 0, -* "safetyRatings": [ -* { -* "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", -* "probability": "NEGLIGIBLE" -* }, -* { -* "category": "HARM_CATEGORY_HATE_SPEECH", -* "probability": "NEGLIGIBLE" -* }, -* { -* "category": "HARM_CATEGORY_HARASSMENT", -* "probability": "NEGLIGIBLE" -* }, -* { -* "category": "HARM_CATEGORY_DANGEROUS_CONTENT", -* "probability": "NEGLIGIBLE" -* } -* ] -* }, -* "usage_metadata": { -* "input_tokens": 10, -* "output_tokens": 149, -* "total_tokens": 159 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "content": "There", -* "response_metadata": { -* "index": 0 -* } -* "usage_metadata": { -* "input_tokens": 10, -* "output_tokens": 1, -* "total_tokens": 11 -* } -* } -* AIMessageChunk { -* "content": " are a few ways to translate \"I love programming\" into French, depending on", -* } -* AIMessageChunk { -* "content": " the level of formality and nuance you want to convey:\n\n**Formal:**\n\n", -* } -* AIMessageChunk { -* "content": "* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This", -* } -* AIMessageChunk { -* "content": " is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More", -* } -* AIMessageChunk { -* "content": " specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and", -* } -* AIMessageChunk { -* "content": " your intended audience. \n", -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n", -* "usage_metadata": { -* "input_tokens": 10, -* "output_tokens": 277, -* "total_tokens": 287 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* type: 'tool_call' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: "Why don\\'t cats play poker?", -* punchline: "Why don\\'t cats play poker? Because they always have an ace up their sleeve!" -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 10, output_tokens: 149, total_tokens: 159 } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* finishReason: 'STOP', -* index: 0, -* safetyRatings: [ -* { -* category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', -* probability: 'NEGLIGIBLE' -* }, -* { -* category: 'HARM_CATEGORY_HATE_SPEECH', -* probability: 'NEGLIGIBLE' -* }, -* { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' }, -* { -* category: 'HARM_CATEGORY_DANGEROUS_CONTENT', -* probability: 'NEGLIGIBLE' -* } -* ] -* } -* ``` -*
-* -*
-* -*
-* Document Messages -* -* This example will show you how to pass documents such as PDFs to Google -* Generative AI through messages. -* -* ```typescript -* const pdfPath = "/Users/my_user/Downloads/invoice.pdf"; -* const pdfBase64 = await fs.readFile(pdfPath, "base64"); -* -* const response = await llm.invoke([ -* ["system", "Use the provided documents to answer the question"], -* [ -* "user", -* [ -* { -* type: "application/pdf", // If the `type` field includes a single slash (`/`), it will be treated as inline data. -* data: pdfBase64, -* }, -* { -* type: "text", -* text: "Summarize the contents of this PDF", -* }, -* ], -* ], -* ]); -* -* console.log(response.content); -* ``` -* -* ```txt -* This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025, -* and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC). -* The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022, -* expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is -* X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply. -* ``` -*
-* -*
-*/ -var ChatGoogleGenerativeAI = class extends BaseChatModel { - static lc_name() { - return "ChatGoogleGenerativeAI"; - } - lc_serializable = true; - get lc_secrets() { - return { apiKey: "GOOGLE_API_KEY" }; - } - lc_namespace = [ - "langchain", - "chat_models", - "google_genai" - ]; - get lc_aliases() { - return { apiKey: "google_api_key" }; - } - model; - temperature; - maxOutputTokens; - topP; - topK; - stopSequences = []; - safetySettings; - apiKey; - streaming = false; - json; - streamUsage = true; - convertSystemMessageToHumanContent; - client; - get _isMultimodalModel() { - return this.model.includes("vision") || this.model.startsWith("gemini-1.5") || this.model.startsWith("gemini-2") || this.model.startsWith("gemma-3-") && !this.model.startsWith("gemma-3-1b"); - } - constructor(fields) { - super(fields); - this.model = fields.model.replace(/^models\//, ""); - this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens; - if (this.maxOutputTokens && this.maxOutputTokens < 0) throw new Error("`maxOutputTokens` must be a positive integer"); - this.temperature = fields.temperature ?? this.temperature; - if (this.temperature && (this.temperature < 0 || this.temperature > 2)) throw new Error("`temperature` must be in the range of [0.0,2.0]"); - this.topP = fields.topP ?? this.topP; - if (this.topP && this.topP < 0) throw new Error("`topP` must be a positive integer"); - if (this.topP && this.topP > 1) throw new Error("`topP` must be below 1."); - this.topK = fields.topK ?? this.topK; - if (this.topK && this.topK < 0) throw new Error("`topK` must be a positive integer"); - this.stopSequences = fields.stopSequences ?? this.stopSequences; - this.apiKey = fields.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY"); - if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor"); - this.safetySettings = fields.safetySettings ?? this.safetySettings; - if (this.safetySettings && this.safetySettings.length > 0) { - const safetySettingsSet = new Set(this.safetySettings.map((s) => s.category)); - if (safetySettingsSet.size !== this.safetySettings.length) throw new Error("The categories in `safetySettings` array must be unique"); - } - this.streaming = fields.streaming ?? this.streaming; - this.json = fields.json; - this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ - model: this.model, - safetySettings: this.safetySettings, - generationConfig: { - stopSequences: this.stopSequences, - maxOutputTokens: this.maxOutputTokens, - temperature: this.temperature, - topP: this.topP, - topK: this.topK, - ...this.json ? { responseMimeType: "application/json" } : {} - } - }, { - apiVersion: fields.apiVersion, - baseUrl: fields.baseUrl - }); - this.streamUsage = fields.streamUsage ?? this.streamUsage; - } - useCachedContent(cachedContent, modelParams, requestOptions) { - if (!this.apiKey) return; - this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions); - } - get useSystemInstruction() { - return typeof this.convertSystemMessageToHumanContent === "boolean" ? !this.convertSystemMessageToHumanContent : this.computeUseSystemInstruction; - } - get computeUseSystemInstruction() { - if (this.model === "gemini-1.0-pro-001") return false; - else if (this.model.startsWith("gemini-pro-vision")) return false; - else if (this.model.startsWith("gemini-1.0-pro-vision")) return false; - else if (this.model === "gemini-pro") return false; - return true; - } - getLsParams(options) { - return { - ls_provider: "google_genai", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: this.client.generationConfig.temperature, - ls_max_tokens: this.client.generationConfig.maxOutputTokens, - ls_stop: options.stop - }; - } - _combineLLMOutput() { - return []; - } - _llmType() { - return "googlegenerativeai"; - } - bindTools(tools, kwargs) { - return this.withConfig({ - tools: convertToolsToGenAI(tools)?.tools, - ...kwargs - }); - } - invocationParams(options) { - const toolsAndConfig = options?.tools?.length ? convertToolsToGenAI(options.tools, { - toolChoice: options.tool_choice, - allowedFunctionNames: options.allowedFunctionNames - }) : void 0; - if (options?.responseSchema) { - this.client.generationConfig.responseSchema = options.responseSchema; - this.client.generationConfig.responseMimeType = "application/json"; - } else { - this.client.generationConfig.responseSchema = void 0; - this.client.generationConfig.responseMimeType = this.json ? "application/json" : void 0; - } - return { - ...toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {}, - ...toolsAndConfig?.toolConfig ? { toolConfig: toolsAndConfig.toolConfig } : {} - }; - } - async _generate(messages, options, runManager) { - const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction); - let actualPrompt = prompt; - if (prompt[0].role === "system") { - const [systemInstruction] = prompt; - this.client.systemInstruction = systemInstruction; - actualPrompt = prompt.slice(1); - } - const parameters = this.invocationParams(options); - if (this.streaming) { - const tokenUsage = {}; - const stream = this._streamResponseChunks(messages, options, runManager); - const finalChunks = {}; - for await (const chunk of stream) { - const index = chunk.generationInfo?.completion ?? 0; - if (finalChunks[index] === void 0) finalChunks[index] = chunk; - else finalChunks[index] = finalChunks[index].concat(chunk); - } - const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); - return { - generations, - llmOutput: { estimatedTokenUsage: tokenUsage } - }; - } - const res = await this.completionWithRetry({ - ...parameters, - contents: actualPrompt - }); - let usageMetadata; - if ("usageMetadata" in res.response) { - const genAIUsageMetadata = res.response.usageMetadata; - usageMetadata = { - input_tokens: genAIUsageMetadata.promptTokenCount ?? 0, - output_tokens: genAIUsageMetadata.candidatesTokenCount ?? 0, - total_tokens: genAIUsageMetadata.totalTokenCount ?? 0 - }; - } - const generationResult = mapGenerateContentResultToChatResult(res.response, { usageMetadata }); - if (generationResult.generations?.length > 0) await runManager?.handleLLMNewToken(generationResult.generations[0]?.text ?? ""); - return generationResult; - } - async *_streamResponseChunks(messages, options, runManager) { - const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction); - let actualPrompt = prompt; - if (prompt[0].role === "system") { - const [systemInstruction] = prompt; - this.client.systemInstruction = systemInstruction; - actualPrompt = prompt.slice(1); - } - const parameters = this.invocationParams(options); - const request = { - ...parameters, - contents: actualPrompt - }; - const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => { - const { stream: stream$1 } = await this.client.generateContentStream(request); - return stream$1; - }); - let usageMetadata; - let prevPromptTokenCount = 0; - let prevCandidatesTokenCount = 0; - let prevTotalTokenCount = 0; - let index = 0; - for await (const response of stream) { - if ("usageMetadata" in response && response.usageMetadata !== void 0 && this.streamUsage !== false && options.streamUsage !== false) { - usageMetadata = { - input_tokens: response.usageMetadata.promptTokenCount ?? 0, - output_tokens: response.usageMetadata.candidatesTokenCount ?? 0, - total_tokens: response.usageMetadata.totalTokenCount ?? 0 - }; - const newPromptTokenCount = response.usageMetadata.promptTokenCount ?? 0; - usageMetadata.input_tokens = Math.max(0, newPromptTokenCount - prevPromptTokenCount); - prevPromptTokenCount = newPromptTokenCount; - const newCandidatesTokenCount = response.usageMetadata.candidatesTokenCount ?? 0; - usageMetadata.output_tokens = Math.max(0, newCandidatesTokenCount - prevCandidatesTokenCount); - prevCandidatesTokenCount = newCandidatesTokenCount; - const newTotalTokenCount = response.usageMetadata.totalTokenCount ?? 0; - usageMetadata.total_tokens = Math.max(0, newTotalTokenCount - prevTotalTokenCount); - prevTotalTokenCount = newTotalTokenCount; - } - const chunk = convertResponseContentToChatGenerationChunk(response, { - usageMetadata, - index - }); - index += 1; - if (!chunk) continue; - yield chunk; - await runManager?.handleLLMNewToken(chunk.text ?? ""); - } - } - async completionWithRetry(request, options) { - return this.caller.callWithOptions({ signal: options?.signal }, async () => { - try { - return await this.client.generateContent(request); - } catch (e) { - if (e.message?.includes("400 Bad Request")) e.status = 400; - throw e; - } - }); - } - withStructuredOutput(outputSchema, config) { - const schema = outputSchema; - const name = config?.name; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") throw new Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`); - let llm; - let outputParser; - if (method === "functionCalling") { - let functionName = name ?? "extract"; - let tools; - if (isInteropZodSchema(schema)) { - const jsonSchema = schemaToGenerativeAIParameters(schema); - tools = [{ functionDeclarations: [{ - name: functionName, - description: jsonSchema.description ?? "A function available to call.", - parameters: jsonSchema - }] }]; - outputParser = new GoogleGenerativeAIToolsOutputParser({ - returnSingle: true, - keyName: functionName, - zodSchema: schema - }); - } else { - let geminiFunctionDefinition; - if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { - geminiFunctionDefinition = schema; - geminiFunctionDefinition.parameters = removeAdditionalProperties(schema.parameters); - functionName = schema.name; - } else geminiFunctionDefinition = { - name: functionName, - description: schema.description ?? "", - parameters: removeAdditionalProperties(schema) - }; - tools = [{ functionDeclarations: [geminiFunctionDefinition] }]; - outputParser = new GoogleGenerativeAIToolsOutputParser({ - returnSingle: true, - keyName: functionName - }); - } - llm = this.bindTools(tools).withConfig({ allowedFunctionNames: [functionName] }); - } else { - const jsonSchema = schemaToGenerativeAIParameters(schema); - llm = this.withConfig({ responseSchema: jsonSchema }); - outputParser = new JsonOutputParser(); - } - if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatGoogleGenerativeAIStructuredOutput" }); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); - } -}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/embeddings.js - - - - - -//#region src/embeddings.ts -/** -* Class that extends the Embeddings class and provides methods for -* generating embeddings using the Google Palm API. -* @example -* ```typescript -* const model = new GoogleGenerativeAIEmbeddings({ -* apiKey: "", -* modelName: "embedding-001", -* }); -* -* // Embed a single query -* const res = await model.embedQuery( -* "What would be a good company name for a company that makes colorful socks?" -* ); -* console.log({ res }); -* -* // Embed multiple documents -* const documentRes = await model.embedDocuments(["Hello world", "Bye bye"]); -* console.log({ documentRes }); -* ``` -*/ -var GoogleGenerativeAIEmbeddings = class extends Embeddings { - apiKey; - modelName = "embedding-001"; - model = "embedding-001"; - taskType; - title; - stripNewLines = true; - maxBatchSize = 100; - client; - constructor(fields) { - super(fields ?? {}); - this.modelName = fields?.model?.replace(/^models\//, "") ?? fields?.modelName?.replace(/^models\//, "") ?? this.modelName; - this.model = this.modelName; - this.taskType = fields?.taskType ?? this.taskType; - this.title = fields?.title ?? this.title; - if (this.title && this.taskType !== "RETRIEVAL_DOCUMENT") throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT"); - this.apiKey = fields?.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY"); - if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor"); - this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ model: this.model }, { baseUrl: fields?.baseUrl }); - } - _convertToContent(text) { - const cleanedText = this.stripNewLines ? text.replace(/\n/g, " ") : text; - return { - content: { - role: "user", - parts: [{ text: cleanedText }] - }, - taskType: this.taskType, - title: this.title - }; - } - async _embedQueryContent(text) { - const req = this._convertToContent(text); - const res = await this.client.embedContent(req); - return res.embedding.values ?? []; - } - async _embedDocumentsContent(documents) { - const batchEmbedChunks = chunkArray(documents, this.maxBatchSize); - const batchEmbedRequests = batchEmbedChunks.map((chunk) => ({ requests: chunk.map((doc) => this._convertToContent(doc)) })); - const responses = await Promise.allSettled(batchEmbedRequests.map((req) => this.client.batchEmbedContents(req))); - const embeddings = responses.flatMap((res, idx) => { - if (res.status === "fulfilled") return res.value.embeddings.map((e) => e.values || []); - else return Array(batchEmbedChunks[idx].length).fill([]); - }); - return embeddings; - } - /** - * Method that takes a document as input and returns a promise that - * resolves to an embedding for the document. It calls the _embedText - * method with the document as the input. - * @param document Document for which to generate an embedding. - * @returns Promise that resolves to an embedding for the input document. - */ - embedQuery(document) { - return this.caller.call(this._embedQueryContent.bind(this), document); - } - /** - * Method that takes an array of documents as input and returns a promise - * that resolves to a 2D array of embeddings for each document. It calls - * the _embedText method for each document in the array. - * @param documents Array of documents for which to generate embeddings. - * @returns Promise that resolves to a 2D array of embeddings for each input document. - */ - embedDocuments(documents) { - return this.caller.call(this._embedDocumentsContent.bind(this), documents); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/index.js - - - - -;// CONCATENATED MODULE: ./src/providers/google.provider.ts - -/** - * Google Gemini provider implementation - */ -class GoogleProvider { - name = 'google'; - apiKey; - constructor(apiKey) { - this.apiKey = apiKey || process.env.GOOGLE_API_KEY || ''; - } - isConfigured() { - return !!this.apiKey; - } - getDefaultModel() { - return 'gemini-pro'; - } - getChatModel(config = {}) { - if (!this.isConfigured()) { - throw new Error('Google API key is not configured'); - } - return new ChatGoogleGenerativeAI({ - apiKey: this.apiKey, - model: config.model || this.getDefaultModel(), - temperature: config.temperature ?? 0.2, - maxOutputTokens: config.maxTokens ?? 4000, - }); - } -} - -;// CONCATENATED MODULE: ./src/providers/provider.factory.ts - - - -/** - * Factory for creating LLM providers - */ -class ProviderFactory { - static providers = new Map(); - /** - * Get or create a provider instance - */ - static getProvider(providerName, apiKey) { - // Normalize provider names - const normalizedName = this.normalizeProviderName(providerName); - // Check if we already have an instance (unless a specific API key is provided) - if (!apiKey && this.providers.has(normalizedName)) { - return this.providers.get(normalizedName); - } - // Create new provider instance - let provider; - switch (normalizedName) { - case 'anthropic': - provider = new AnthropicProvider(apiKey); - break; - case 'openai': - provider = new OpenAIProvider(apiKey); - break; - case 'google': - provider = new GoogleProvider(apiKey); - break; - default: - throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`); - } - // Cache the provider if no specific API key was provided - if (!apiKey) { - this.providers.set(normalizedName, provider); - } - return provider; - } - /** - * Create a chat model with the specified options - */ - static createChatModel(options = {}) { - const providerName = options.provider || 'anthropic'; - const provider = this.getProvider(providerName, options.apiKey); - if (!provider.isConfigured()) { - throw new Error(`Provider ${providerName} is not configured. Please set the API key.`); - } - const config = { - model: options.model, - temperature: options.temperature, - maxTokens: options.maxTokens, - }; - return provider.getChatModel(config); - } - /** - * Get the default model for a provider - */ - static getDefaultModel(providerName) { - const provider = this.getProvider(providerName); - return provider.getDefaultModel(); - } - /** - * Check if a provider is configured - */ - static isProviderConfigured(providerName) { - try { - const provider = this.getProvider(providerName); - return provider.isConfigured(); - } - catch { - return false; - } - } - /** - * Normalize provider name (handle aliases) - */ - static normalizeProviderName(name) { - const normalized = name.toLowerCase(); - if (normalized === 'claude') - return 'anthropic'; - if (normalized === 'gemini') - return 'google'; - return normalized; - } - /** - * Get list of available providers - */ - static getAvailableProviders() { - return ['anthropic', 'openai', 'google']; - } -} - -;// CONCATENATED MODULE: ./src/providers/index.ts - - - - - - -;// CONCATENATED MODULE: ./src/agents/pr-analyzer-agent.ts -/** - * PR Analyzer Agent - * LangChain-based agent for intelligent PR analysis - */ - - - - - -/** - * PR Analysis Agent using LangChain and LangGraph - */ -class PRAnalyzerAgent extends BasePRAgentWorkflow { - constructor(options = {}) { - const model = ProviderFactory.createChatModel({ - provider: options.provider || 'anthropic', - apiKey: options.apiKey, - model: options.model, - temperature: options.temperature ?? 0.2, - maxTokens: options.maxTokens ?? 4000, - }); - super(model); - } - /** - * Get agent metadata - */ - getMetadata() { - return { - name: 'pr-analyzer', - version: '1.0.0', - description: 'AI-powered pull request analyzer using LangChain agent workflow', - capabilities: [ - 'file-level analysis', - 'risk detection', - 'complexity scoring', - 'intelligent recommendations', - 'self-refinement workflow', - ], - }; - } - /** - * Analyze a PR with full agent workflow - */ - async analyze(diff, title, mode, options) { - // Parse diff into files - const files = parseDiff(diff); - // Build arch-docs context if enabled - let archDocsContext = undefined; - if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { - const docs = parseAllArchDocs(options?.repoPath); - archDocsContext = buildArchDocsContext(docs, { title, files, diff }); - } - // Create context - const context = { - diff, - title, - files, - tokenBudget: 100000, - maxCost: 5.0, - mode: mode || { summary: true, risks: true, complexity: true }, - archDocs: archDocsContext, - }; - // Execute workflow - const result = await this.execute(context, { - skipSelfRefinement: files.length < 5 || diff.length < 10000, // Skip for small PRs - }); - return result; - } - /** - * Quick analysis without refinement - */ - async quickAnalyze(diff, title, options) { - const files = parseDiff(diff); - // Build arch-docs context if enabled - let archDocsContext = undefined; - if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { - const docs = parseAllArchDocs(options?.repoPath); - archDocsContext = buildArchDocsContext(docs, { title, files, diff }); - } - const context = { - diff, - title, - files, - tokenBudget: 50000, - maxCost: 2.0, - mode: { summary: true, risks: true, complexity: true }, - archDocs: archDocsContext, - }; - return this.execute(context, { - skipSelfRefinement: true, - }); - } - /** - * Analyze specific files only - */ - async analyzeFiles(diff, filePaths, options) { - const allFiles = parseDiff(diff); - const files = allFiles.filter(f => filePaths.includes(f.path)); - // Build arch-docs context if enabled - let archDocsContext = undefined; - if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { - const docs = parseAllArchDocs(options?.repoPath); - archDocsContext = buildArchDocsContext(docs, { files, diff }); + }); } - const context = { - diff, - files, - tokenBudget: 50000, - maxCost: 2.0, - mode: { summary: true, risks: true, complexity: true }, - archDocs: archDocsContext, - }; - return this.execute(context, { - skipSelfRefinement: true, - }); - } - /** - * Check if agent can execute with given context - */ - async canExecute(context) { - return context.files.length > 0 && context.diff.length > 0; } - /** - * Estimate tokens for this analysis - */ - async estimateTokens(context) { - const baseTokens = 2000; - const diffTokens = Math.ceil(context.diff.length / 4); // ~4 chars per token - const filesTokens = context.files.length * 100; - return baseTokens + diffTokens + filesTokens; - } -} -/** - * Factory function to create PR analyzer agent - */ -function createPRAnalyzerAgent(options = {}) { - return new PRAnalyzerAgent(options); -} -/** - * Legacy factory function for backward compatibility - * @deprecated Use PRAnalyzerAgent constructor with ProviderOptions instead - */ -function createPRAnalyzerAgentLegacy(apiKey, modelName) { - return new PRAnalyzerAgent({ - apiKey, - model: modelName, - provider: 'anthropic' - }); + return output; } - -;// CONCATENATED MODULE: ./src/action.ts - - - -async function run() { - try { - // Get provider configuration from environment - const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase(); - const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY; - const model = process.env.AI_MODEL; - const ghToken = process.env.GITHUB_TOKEN; - if (!apiKey) { - lib_core.setFailed('AI provider API key is required (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)'); - return; - } - if (!ghToken) { - lib_core.setFailed('GITHUB_TOKEN environment variable is required'); - return; - } - lib_core.info(`Using AI provider: ${provider}${model ? ` with model: ${model}` : ''}`); - const { context } = github; +export default (app) => { + app.log.info('🤖 PR Agent (LangChain) started'); + app.on(['pull_request.opened', 'pull_request.synchronize'], async (context) => { const { pull_request: pr, repository } = context.payload; - if (!pr) { - lib_core.setFailed('This action can only be run on pull request events'); - return; - } - lib_core.info(`Analyzing PR #${pr.number} in ${repository?.full_name}`); - // Get PR diffs - const diff = await getPRDiffs(context, ghToken); - if (!diff) { - lib_core.warning('No changes found in the pull request'); - return; - } - lib_core.info(`Diff size: ${diff.length} characters`); - if (!repository) { - lib_core.setFailed('Repository information not available'); - return; + app.log.info(`Analyzing PR #${pr.number} in ${repository.full_name}`); + try { + app.log.info('Getting PR diffs'); + const diff = await getPRDiffs(context); + if (!apiKey) { + throw new Error('AI provider API key is not set (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)'); + } + // Use LangChain agent for intelligent analysis + app.log.info(`Running LangChain agent analysis with ${provider}...`); + const agent = new PRAnalyzerAgent({ + provider: provider, + apiKey, + model, + }); + const result = await agent.analyze(diff, pr.title); + // Format the analysis for GitHub comment + const summary = formatAnalysisForGitHub(result); + await context.octokit.issues.createComment({ + owner: repository.owner.login, + repo: repository.name, + issue_number: pr.number, + body: `## 🤖 AI Analysis (LangChain Agent)\n\n${summary}` + }); + app.log.info(`Analysis posted for PR #${pr.number}`); } - // Use LangChain PRAnalyzerAgent - lib_core.info('Running LangChain agent analysis...'); - const agent = new PRAnalyzerAgent({ - provider, - apiKey, - model, - }); - // Analyze with the LangChain agent - lib_core.info('Parsing diff and analyzing...'); - const result = await agent.analyze(diff, pr.title); - lib_core.info(`Analysis complete: ${result.fileAnalyses.size} files analyzed`); - // Format the summary - let summary = ''; - if (result.summary) { - summary += `### Summary\n${result.summary}\n\n`; - } - if (result.overallRisks.length > 0) { - summary += `### Potential Risks\n`; - result.overallRisks.forEach((risk) => { - if (typeof risk === 'string') { - summary += `- ${risk}\n`; - } - else if (typeof risk === 'object' && risk.description) { - summary += `- **${risk.description}**\n`; - if (risk.archDocsReference) { - summary += ` - 📚 *From ${risk.archDocsReference.source}*: "${risk.archDocsReference.excerpt}"\n`; - summary += ` - *Reason*: ${risk.archDocsReference.reason}\n`; - } - } - }); - summary += '\n'; - } - else { - summary += `### Potential Risks\nNone\n\n`; - } - summary += `### Complexity: ${result.overallComplexity}/5\n`; - if (result.recommendations && result.recommendations.length > 0) { - summary += `\n### Recommendations\n`; - result.recommendations.forEach((rec) => { - summary += `- ${rec}\n`; - }); + catch (error) { + app.log.error('Error analyzing PR:', error); } - // Post comment - await postComment(pr.number, summary, repository, ghToken); - lib_core.info('Analysis complete!'); - } - catch (error) { - lib_core.setFailed(`Action failed with error: ${error}`); - } -} -async function getPRDiffs(context, ghToken) { + }); + // TODO: Re-implement code suggestions using the new agent's code suggestion tool + // The old code suggestion implementation has been removed + // To implement this feature: + // 1. Use the agent's createCodeSuggestionTool() from tools/pr-analysis-tools.ts + // 2. Call the agent with the tool to generate code fixes based on reviewer comments + // + // app.on(['pull_request_review_comment.created', 'pull_request_review_comment.edited'], async (context) => { + // // Implementation goes here + // }); +}; +async function getPRDiffs(context) { try { const { pull_request: pr, repository } = context.payload; - const octokit = github.getOctokit(ghToken); - const { data: files } = await octokit.rest.pulls.listFiles({ + const { data: files } = await context.octokit.pulls.listFiles({ owner: repository.owner.login, repo: repository.name, pull_number: pr.number }); - // Format as proper git diff that parseDiff expects - return files.map((f) => { - const status = f.status === 'added' ? 'new file mode 100644' : - f.status === 'removed' ? 'deleted file mode 100644' : ''; - const patch = f.patch || ''; - return `diff --git a/${f.filename} b/${f.filename} -${status ? status + '\n' : ''}--- ${f.status === 'added' ? '/dev/null' : 'a/' + f.filename} -+++ ${f.status === 'removed' ? '/dev/null' : 'b/' + f.filename} -${patch}`; - }).join('\n'); + const diff = files.map((f) => `--- ${f.filename}\n${f.patch}`).join('\n'); + return diff; } catch (error) { - lib_core.error('Error fetching PR diff:'); - lib_core.error(String(error)); + console.error('Error fetching PR diff:', error); throw new Error('Failed to fetch PR diff'); } } -async function postComment(prNumber, summary, repository, ghToken) { - try { - const octokit = github.getOctokit(ghToken); - await octokit.rest.issues.createComment({ - owner: repository.owner.login, - repo: repository.name, - issue_number: prNumber, - body: `## 🤖 AI Analysis (PR Agent by TechDebtGPT)\n\n${summary}` - }); - } - catch (error) { - lib_core.error('Error posting comment:'); - lib_core.error(String(error)); - throw new Error('Failed to post comment'); - } -} -run(); - - //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index 92dc7e3..427ec48 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC/FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC7DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC7DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3oBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AChHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AClIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AClIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AClIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjnEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AClIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACvJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxDA;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5iBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACRA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3DA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpBA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjBA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACXA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9NA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACRA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACr0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/IA;AACA;AACA;AACA;AACA;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1uEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5TA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACzgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChlBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnmEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACj7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1jBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACroBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACrRA;;;;;;;;ACAA;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC9SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACvMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChoBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AChCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACnOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACnMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AChCA;AACA;AACA;AACA;AACA;;;;ACJA;AACA;;;;;;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7WA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC/GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7CA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC1MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACzZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACvHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACvRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7vHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACPA;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AEn0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC1bA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AEjNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AE3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3gBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACjJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpjBA;AACA;AACA;AACA;AACA;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACprDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACz4BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACRA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5mHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACh1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACtCA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC3GA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjyBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/uDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC3RA;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5aA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC3vBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvCA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrDA;AACA;AACA;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5QA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACliBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/oCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACxCA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC7+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1GA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;;;AAGA;AAEA;AACA;AAGA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;;AAGA;;;;AAIA;;;;;;;;;;;;AAYA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AClXA;;;AAGA;AAEA;AACA;AAkBA;;AAEA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AAKA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AAIA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;;;AC1LA;;;AAGA;AAEA;AAeA;;AAEA;AACA;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AAKA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/PA;;;AAGA;AAEA;AACA;AAGA;AAOA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAWA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAGA;AACA;AACA;AAEA;AACA;;;AAGA;AACA;AACA;AACA;;;AAGA;;AAEA;;AAEA;;;;;;;AAOA;;;;;;;;;;;;AAYA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAGA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;;;;;;;;;AASA;;;AAGA;;;;AAIA;;;AAGA;;;;;;;;;;;;;;AAcA;;;;AAIA;;;AAGA;;;AAGA;;;;;;;;;AASA;;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;;;;;;;AAOA;;AAEA;;;AAGA;AACA;AACA;AACA;AACA;;;AAGA;;AAEA;;AAEA;;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;;;AAGA;;;AAGA;;AAEA;;;;;;;;;AASA;;AAEA;;;AAGA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;;;AChhCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjJA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1OA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;;ACFA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5FA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClCA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvMA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7kBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvyBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;;;ACFA;AAIA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpHA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChCA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;;ACHA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;;ACFA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvFA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChPA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxeA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjFA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9iBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnhBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxGA;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpBA;AAIA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC/BA;AACA;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/+CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3pBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjGA;AACA;AACA;;;ACFA;AAIA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClCA;AACA;AACA;AAaA;;AAEA;AACA;AACA;AAEA;;AAEA;AACA;AAIA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AAGA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;;;;ACvHA;AACA;AACA;AACA;AACA;;;ACJA;;;AAGA;AAEA;AAEA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AAMA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;;AAEA;AACA;AACA;AACA;AAEA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChLA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAEA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA","sources":[".././node_modules/@actions/core/lib/command.js",".././node_modules/@actions/core/lib/core.js",".././node_modules/@actions/core/lib/file-command.js",".././node_modules/@actions/core/lib/oidc-utils.js",".././node_modules/@actions/core/lib/path-utils.js",".././node_modules/@actions/core/lib/platform.js",".././node_modules/@actions/core/lib/summary.js",".././node_modules/@actions/core/lib/utils.js",".././node_modules/@actions/exec/lib/exec.js",".././node_modules/@actions/exec/lib/toolrunner.js",".././node_modules/@actions/github/lib/context.js",".././node_modules/@actions/github/lib/github.js",".././node_modules/@actions/github/lib/internal/utils.js",".././node_modules/@actions/github/lib/utils.js",".././node_modules/@actions/http-client/lib/auth.js",".././node_modules/@actions/http-client/lib/index.js",".././node_modules/@actions/http-client/lib/proxy.js",".././node_modules/@actions/io/lib/io-util.js",".././node_modules/@actions/io/lib/io.js",".././node_modules/@langchain/core/node_modules/ansi-styles/index.js",".././node_modules/@langchain/core/node_modules/camelcase/index.js",".././node_modules/@langchain/core/node_modules/uuid/dist/index.js",".././node_modules/@langchain/core/node_modules/uuid/dist/max.js",".././node_modules/@langchain/core/node_modules/uuid/dist/md5.js",".././node_modules/@langchain/core/node_modules/uuid/dist/native.js",".././node_modules/@langchain/core/node_modules/uuid/dist/nil.js",".././node_modules/@langchain/core/node_modules/uuid/dist/parse.js",".././node_modules/@langchain/core/node_modules/uuid/dist/regex.js",".././node_modules/@langchain/core/node_modules/uuid/dist/rng.js",".././node_modules/@langchain/core/node_modules/uuid/dist/sha1.js",".././node_modules/@langchain/core/node_modules/uuid/dist/stringify.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v1.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v1ToV6.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v3.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v35.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v4.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v5.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v6.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v6ToV1.js",".././node_modules/@langchain/core/node_modules/uuid/dist/v7.js",".././node_modules/@langchain/core/node_modules/uuid/dist/validate.js",".././node_modules/@langchain/core/node_modules/uuid/dist/version.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/index.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/max.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/md5.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/native.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/nil.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/parse.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/regex.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/rng.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/sha1.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/stringify.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v1.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v1ToV6.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v3.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v35.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v4.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v5.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v6.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v6ToV1.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/v7.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/validate.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/dist/version.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/index.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/max.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/md5.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/native.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/nil.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/parse.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/regex.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/rng.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/sha1.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/stringify.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v1.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v1ToV6.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v3.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v35.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v4.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v5.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v6.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v6ToV1.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/v7.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/validate.js",".././node_modules/@langchain/langgraph/node_modules/uuid/dist/version.js",".././node_modules/@octokit/auth-token/dist-node/index.js",".././node_modules/@octokit/core/dist-node/index.js",".././node_modules/@octokit/endpoint/dist-node/index.js",".././node_modules/@octokit/graphql/dist-node/index.js",".././node_modules/@octokit/plugin-paginate-rest/dist-node/index.js",".././node_modules/@octokit/plugin-rest-endpoint-methods/dist-node/index.js",".././node_modules/@octokit/request-error/dist-node/index.js",".././node_modules/@octokit/request/dist-node/index.js",".././node_modules/base64-js/index.js",".././node_modules/before-after-hook/index.js",".././node_modules/before-after-hook/lib/add.js",".././node_modules/before-after-hook/lib/register.js",".././node_modules/before-after-hook/lib/remove.js",".././node_modules/decamelize/index.js",".././node_modules/deprecation/dist-node/index.js",".././node_modules/eventemitter3/index.js",".././node_modules/langsmith/node_modules/uuid/dist/index.js",".././node_modules/langsmith/node_modules/uuid/dist/max.js",".././node_modules/langsmith/node_modules/uuid/dist/md5.js",".././node_modules/langsmith/node_modules/uuid/dist/native.js",".././node_modules/langsmith/node_modules/uuid/dist/nil.js",".././node_modules/langsmith/node_modules/uuid/dist/parse.js",".././node_modules/langsmith/node_modules/uuid/dist/regex.js",".././node_modules/langsmith/node_modules/uuid/dist/rng.js",".././node_modules/langsmith/node_modules/uuid/dist/sha1.js",".././node_modules/langsmith/node_modules/uuid/dist/stringify.js",".././node_modules/langsmith/node_modules/uuid/dist/v1.js",".././node_modules/langsmith/node_modules/uuid/dist/v1ToV6.js",".././node_modules/langsmith/node_modules/uuid/dist/v3.js",".././node_modules/langsmith/node_modules/uuid/dist/v35.js",".././node_modules/langsmith/node_modules/uuid/dist/v4.js",".././node_modules/langsmith/node_modules/uuid/dist/v5.js",".././node_modules/langsmith/node_modules/uuid/dist/v6.js",".././node_modules/langsmith/node_modules/uuid/dist/v6ToV1.js",".././node_modules/langsmith/node_modules/uuid/dist/v7.js",".././node_modules/langsmith/node_modules/uuid/dist/validate.js",".././node_modules/langsmith/node_modules/uuid/dist/version.js",".././node_modules/once/once.js",".././node_modules/p-finally/index.js",".././node_modules/p-queue/dist/index.js",".././node_modules/p-queue/dist/lower-bound.js",".././node_modules/p-queue/dist/priority-queue.js",".././node_modules/p-retry/index.js",".././node_modules/p-timeout/index.js",".././node_modules/retry/index.js",".././node_modules/retry/lib/retry.js",".././node_modules/retry/lib/retry_operation.js",".././node_modules/semver/classes/comparator.js",".././node_modules/semver/classes/range.js",".././node_modules/semver/classes/semver.js",".././node_modules/semver/functions/clean.js",".././node_modules/semver/functions/cmp.js",".././node_modules/semver/functions/coerce.js",".././node_modules/semver/functions/compare-build.js",".././node_modules/semver/functions/compare-loose.js",".././node_modules/semver/functions/compare.js",".././node_modules/semver/functions/diff.js",".././node_modules/semver/functions/eq.js",".././node_modules/semver/functions/gt.js",".././node_modules/semver/functions/gte.js",".././node_modules/semver/functions/inc.js",".././node_modules/semver/functions/lt.js",".././node_modules/semver/functions/lte.js",".././node_modules/semver/functions/major.js",".././node_modules/semver/functions/minor.js",".././node_modules/semver/functions/neq.js",".././node_modules/semver/functions/parse.js",".././node_modules/semver/functions/patch.js",".././node_modules/semver/functions/prerelease.js",".././node_modules/semver/functions/rcompare.js",".././node_modules/semver/functions/rsort.js",".././node_modules/semver/functions/satisfies.js",".././node_modules/semver/functions/sort.js",".././node_modules/semver/functions/valid.js",".././node_modules/semver/index.js",".././node_modules/semver/internal/constants.js",".././node_modules/semver/internal/debug.js",".././node_modules/semver/internal/identifiers.js",".././node_modules/semver/internal/lrucache.js",".././node_modules/semver/internal/parse-options.js",".././node_modules/semver/internal/re.js",".././node_modules/semver/ranges/gtr.js",".././node_modules/semver/ranges/intersects.js",".././node_modules/semver/ranges/ltr.js",".././node_modules/semver/ranges/max-satisfying.js",".././node_modules/semver/ranges/min-satisfying.js",".././node_modules/semver/ranges/min-version.js",".././node_modules/semver/ranges/outside.js",".././node_modules/semver/ranges/simplify.js",".././node_modules/semver/ranges/subset.js",".././node_modules/semver/ranges/to-comparators.js",".././node_modules/semver/ranges/valid.js",".././node_modules/tunnel/index.js",".././node_modules/tunnel/lib/tunnel.js",".././node_modules/undici/index.js",".././node_modules/undici/lib/agent.js",".././node_modules/undici/lib/api/abort-signal.js",".././node_modules/undici/lib/api/api-connect.js",".././node_modules/undici/lib/api/api-pipeline.js",".././node_modules/undici/lib/api/api-request.js",".././node_modules/undici/lib/api/api-stream.js",".././node_modules/undici/lib/api/api-upgrade.js",".././node_modules/undici/lib/api/index.js",".././node_modules/undici/lib/api/readable.js",".././node_modules/undici/lib/api/util.js",".././node_modules/undici/lib/balanced-pool.js",".././node_modules/undici/lib/cache/cache.js",".././node_modules/undici/lib/cache/cachestorage.js",".././node_modules/undici/lib/cache/symbols.js",".././node_modules/undici/lib/cache/util.js",".././node_modules/undici/lib/client.js",".././node_modules/undici/lib/compat/dispatcher-weakref.js",".././node_modules/undici/lib/cookies/constants.js",".././node_modules/undici/lib/cookies/index.js",".././node_modules/undici/lib/cookies/parse.js",".././node_modules/undici/lib/cookies/util.js",".././node_modules/undici/lib/core/connect.js",".././node_modules/undici/lib/core/constants.js",".././node_modules/undici/lib/core/errors.js",".././node_modules/undici/lib/core/request.js",".././node_modules/undici/lib/core/symbols.js",".././node_modules/undici/lib/core/util.js",".././node_modules/undici/lib/dispatcher-base.js",".././node_modules/undici/lib/dispatcher.js",".././node_modules/undici/lib/fetch/body.js",".././node_modules/undici/lib/fetch/constants.js",".././node_modules/undici/lib/fetch/dataURL.js",".././node_modules/undici/lib/fetch/file.js",".././node_modules/undici/lib/fetch/formdata.js",".././node_modules/undici/lib/fetch/global.js",".././node_modules/undici/lib/fetch/headers.js",".././node_modules/undici/lib/fetch/index.js",".././node_modules/undici/lib/fetch/request.js",".././node_modules/undici/lib/fetch/response.js",".././node_modules/undici/lib/fetch/symbols.js",".././node_modules/undici/lib/fetch/util.js",".././node_modules/undici/lib/fetch/webidl.js",".././node_modules/undici/lib/fileapi/encoding.js",".././node_modules/undici/lib/fileapi/filereader.js",".././node_modules/undici/lib/fileapi/progressevent.js",".././node_modules/undici/lib/fileapi/symbols.js",".././node_modules/undici/lib/fileapi/util.js",".././node_modules/undici/lib/global.js",".././node_modules/undici/lib/handler/DecoratorHandler.js",".././node_modules/undici/lib/handler/RedirectHandler.js",".././node_modules/undici/lib/handler/RetryHandler.js",".././node_modules/undici/lib/interceptor/redirectInterceptor.js",".././node_modules/undici/lib/llhttp/constants.js",".././node_modules/undici/lib/llhttp/llhttp-wasm.js",".././node_modules/undici/lib/llhttp/llhttp_simd-wasm.js",".././node_modules/undici/lib/llhttp/utils.js",".././node_modules/undici/lib/mock/mock-agent.js",".././node_modules/undici/lib/mock/mock-client.js",".././node_modules/undici/lib/mock/mock-errors.js",".././node_modules/undici/lib/mock/mock-interceptor.js",".././node_modules/undici/lib/mock/mock-pool.js",".././node_modules/undici/lib/mock/mock-symbols.js",".././node_modules/undici/lib/mock/mock-utils.js",".././node_modules/undici/lib/mock/pending-interceptors-formatter.js",".././node_modules/undici/lib/mock/pluralizer.js",".././node_modules/undici/lib/node/fixed-queue.js",".././node_modules/undici/lib/pool-base.js",".././node_modules/undici/lib/pool-stats.js",".././node_modules/undici/lib/pool.js",".././node_modules/undici/lib/proxy-agent.js",".././node_modules/undici/lib/timers.js",".././node_modules/undici/lib/websocket/connection.js",".././node_modules/undici/lib/websocket/constants.js",".././node_modules/undici/lib/websocket/events.js",".././node_modules/undici/lib/websocket/frame.js",".././node_modules/undici/lib/websocket/receiver.js",".././node_modules/undici/lib/websocket/symbols.js",".././node_modules/undici/lib/websocket/util.js",".././node_modules/undici/lib/websocket/websocket.js",".././node_modules/universal-user-agent/dist-node/index.js",".././node_modules/wrappy/wrappy.js","../external node-commonjs \"assert\"","../external node-commonjs \"async_hooks\"","../external node-commonjs \"buffer\"","../external node-commonjs \"child_process\"","../external node-commonjs \"console\"","../external node-commonjs \"crypto\"","../external node-commonjs \"diagnostics_channel\"","../external node-commonjs \"events\"","../external node-commonjs \"fs\"","../external node-commonjs \"http\"","../external node-commonjs \"http2\"","../external node-commonjs \"https\"","../external node-commonjs \"net\"","../external node-commonjs \"node:crypto\"","../external node-commonjs \"node:events\"","../external node-commonjs \"node:stream\"","../external node-commonjs \"node:util\"","../external node-commonjs \"os\"","../external node-commonjs \"path\"","../external node-commonjs \"perf_hooks\"","../external node-commonjs \"querystring\"","../external node-commonjs \"stream\"","../external node-commonjs \"stream/web\"","../external node-commonjs \"string_decoder\"","../external node-commonjs \"timers\"","../external node-commonjs \"tls\"","../external node-commonjs \"url\"","../external node-commonjs \"util\"","../external node-commonjs \"util/types\"","../external node-commonjs \"worker_threads\"","../external node-commonjs \"zlib\"",".././node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js",".././node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js",".././node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js",".././node_modules/@fastify/busboy/deps/streamsearch/sbmh.js",".././node_modules/@fastify/busboy/lib/main.js",".././node_modules/@fastify/busboy/lib/types/multipart.js",".././node_modules/@fastify/busboy/lib/types/urlencoded.js",".././node_modules/@fastify/busboy/lib/utils/Decoder.js",".././node_modules/@fastify/busboy/lib/utils/basename.js",".././node_modules/@fastify/busboy/lib/utils/decodeText.js",".././node_modules/@fastify/busboy/lib/utils/getLimit.js",".././node_modules/@fastify/busboy/lib/utils/parseParams.js","../webpack/bootstrap","../webpack/runtime/node module decorator","../webpack/runtime/compat",".././node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js",".././node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js",".././node_modules/@langchain/core/dist/load/map_keys.js",".././node_modules/@langchain/core/dist/load/serializable.js",".././node_modules/@langchain/core/dist/messages/content/data.js",".././node_modules/@langchain/core/dist/messages/block_translators/utils.js",".././node_modules/@langchain/core/dist/messages/block_translators/anthropic.js",".././node_modules/@langchain/core/dist/messages/block_translators/data.js",".././node_modules/@langchain/core/dist/messages/block_translators/openai.js",".././node_modules/@langchain/core/dist/messages/message.js",".././node_modules/@langchain/core/dist/messages/format.js",".././node_modules/@langchain/core/dist/messages/base.js",".././node_modules/@langchain/core/dist/messages/tool.js",".././node_modules/@langchain/core/dist/utils/json.js",".././node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js",".././node_modules/@langchain/core/dist/messages/block_translators/google_genai.js",".././node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js",".././node_modules/@langchain/core/dist/messages/block_translators/index.js",".././node_modules/@langchain/core/dist/messages/metadata.js",".././node_modules/@langchain/core/dist/messages/ai.js",".././node_modules/@langchain/core/dist/messages/chat.js",".././node_modules/@langchain/core/dist/messages/function.js",".././node_modules/@langchain/core/dist/messages/human.js",".././node_modules/@langchain/core/dist/messages/system.js",".././node_modules/@langchain/core/dist/errors/index.js",".././node_modules/@langchain/core/dist/tools/utils.js",".././node_modules/@langchain/core/dist/messages/modifier.js",".././node_modules/@langchain/core/dist/messages/utils.js",".././node_modules/@langchain/core/dist/utils/env.js",".././node_modules/@langchain/core/node_modules/uuid/wrapper.mjs",".././node_modules/@langchain/core/dist/callbacks/base.js",".././node_modules/langsmith/node_modules/uuid/wrapper.mjs",".././node_modules/langsmith/dist/experimental/otel/constants.js",".././node_modules/langsmith/dist/singletons/fetch.js",".././node_modules/langsmith/dist/utils/project.js",".././node_modules/langsmith/dist/index.js",".././node_modules/langsmith/dist/utils/env.js",".././node_modules/langsmith/dist/singletons/otel.js",".././node_modules/langsmith/dist/experimental/otel/translator.js",".././node_modules/langsmith/dist/utils/async_caller.js",".././node_modules/langsmith/dist/utils/messages.js",".././node_modules/langsmith/dist/utils/_uuid.js",".././node_modules/langsmith/dist/utils/warn.js",".././node_modules/langsmith/dist/utils/prompts.js",".././node_modules/langsmith/dist/utils/error.js",".././node_modules/langsmith/dist/utils/fast-safe-stringify/index.js",".././node_modules/langsmith/dist/client.js",".././node_modules/langsmith/dist/env.js",".././node_modules/langsmith/dist/singletons/constants.js",".././node_modules/langsmith/dist/run_trees.js",".././node_modules/langsmith/run_trees.js",".././node_modules/@langchain/core/dist/tracers/base.js",".././node_modules/@langchain/core/dist/tracers/console.js",".././node_modules/langsmith/index.js",".././node_modules/@langchain/core/dist/singletons/tracer.js",".././node_modules/langsmith/dist/singletons/traceable.js",".././node_modules/langsmith/singletons/traceable.js",".././node_modules/@langchain/core/dist/tracers/tracer_langchain.js",".././node_modules/@langchain/core/dist/singletons/callbacks.js",".././node_modules/@langchain/core/dist/callbacks/promises.js",".././node_modules/@langchain/core/dist/utils/callbacks.js",".././node_modules/@langchain/core/dist/singletons/async_local_storage/context.js",".././node_modules/@langchain/core/dist/callbacks/manager.js",".././node_modules/@langchain/core/dist/singletons/async_local_storage/index.js",".././node_modules/@langchain/core/dist/singletons/index.js","../external node-commonjs \"node:async_hooks\"",".././node_modules/@langchain/langgraph/dist/setup/async_local_storage.js",".././node_modules/@langchain/langgraph/dist/errors.js",".././node_modules/@langchain/langgraph-checkpoint/node_modules/uuid/wrapper.mjs",".././node_modules/@langchain/langgraph-checkpoint/dist/id.js",".././node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js",".././node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js",".././node_modules/@langchain/core/dist/load/import_constants.js",".././node_modules/@langchain/core/dist/agents.js",".././node_modules/@langchain/core/dist/runnables/config.js",".././node_modules/@langchain/core/dist/utils/signal.js",".././node_modules/@langchain/core/dist/utils/stream.js",".././node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js",".././node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js",".././node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js",".././node_modules/@langchain/core/dist/utils/fast-json-patch/index.js",".././node_modules/@langchain/core/dist/tracers/log_stream.js",".././node_modules/@langchain/core/dist/outputs.js",".././node_modules/@langchain/core/dist/utils/async_caller.js",".././node_modules/zod/v4/core/core.js",".././node_modules/zod/v4/core/util.js",".././node_modules/zod/v4/core/errors.js",".././node_modules/zod/v4/core/parse.js",".././node_modules/zod/v4/core/registries.js",".././node_modules/zod/v4/core/checks.js",".././node_modules/zod/v4/core/versions.js",".././node_modules/zod/v4/core/schemas.js",".././node_modules/zod/v4/core/api.js",".././node_modules/@langchain/core/dist/utils/types/zod.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/errorMessages.js",".././node_modules/zod/v3/helpers/util.js",".././node_modules/zod/v3/ZodError.js",".././node_modules/zod/v3/locales/en.js",".././node_modules/zod/v3/errors.js",".././node_modules/zod/v3/helpers/errorUtil.js",".././node_modules/zod/v3/helpers/parseUtil.js",".././node_modules/zod/v3/types.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/bigint.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/literal.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nullable.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/number.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js",".././node_modules/@langchain/core/dist/utils/zod-to-json-schema/index.js",".././node_modules/zod/v4/core/to-json-schema.js",".././node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js",".././node_modules/@cfworker/json-schema/dist/esm/pointer.js",".././node_modules/@cfworker/json-schema/dist/esm/dereference.js",".././node_modules/@cfworker/json-schema/dist/esm/format.js",".././node_modules/@cfworker/json-schema/dist/esm/types.js",".././node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js",".././node_modules/@cfworker/json-schema/dist/esm/validate.js",".././node_modules/@cfworker/json-schema/dist/esm/validator.js",".././node_modules/@cfworker/json-schema/dist/esm/index.js",".././node_modules/@langchain/core/dist/utils/json_schema.js",".././node_modules/@langchain/core/dist/runnables/utils.js",".././node_modules/@langchain/core/dist/runnables/graph_mermaid.js",".././node_modules/@langchain/core/dist/runnables/graph.js",".././node_modules/@langchain/core/dist/tracers/event_stream.js",".././node_modules/@langchain/core/dist/tracers/root_listener.js",".././node_modules/@langchain/core/dist/runnables/wrappers.js",".././node_modules/@langchain/core/dist/runnables/iter.js",".././node_modules/@langchain/core/dist/runnables/base.js",".././node_modules/@langchain/core/dist/messages/transformers.js",".././node_modules/@langchain/core/dist/messages/content/tools.js",".././node_modules/@langchain/core/dist/messages/content/multimodal.js",".././node_modules/@langchain/core/dist/messages/content/index.js",".././node_modules/@langchain/core/dist/messages/index.js",".././node_modules/@langchain/core/dist/chat_history.js",".././node_modules/@langchain/core/dist/embeddings.js",".././node_modules/@langchain/core/dist/index.js",".././node_modules/@langchain/core/dist/memory.js",".././node_modules/@langchain/core/dist/prompt_values.js",".././node_modules/@langchain/core/dist/stores.js",".././node_modules/@langchain/core/dist/retrievers/index.js",".././node_modules/@langchain/core/dist/vectorstores.js",".././node_modules/@langchain/core/dist/utils/js-sha256/hash.js",".././node_modules/@langchain/core/dist/utils/hash.js",".././node_modules/@langchain/core/dist/caches/base.js",".././node_modules/@langchain/core/dist/document_loaders/base.js",".././node_modules/@langchain/core/dist/document_loaders/langsmith.js",".././node_modules/@langchain/core/dist/documents/document.js",".././node_modules/@langchain/core/dist/documents/transformers.js",".././node_modules/@langchain/core/dist/documents/index.js",".././node_modules/@langchain/core/dist/example_selectors/base.js",".././node_modules/@langchain/core/dist/example_selectors/conditional.js",".././node_modules/@langchain/core/dist/example_selectors/length_based.js",".././node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js",".././node_modules/@langchain/core/dist/example_selectors/index.js",".././node_modules/@langchain/core/dist/indexing/record_manager.js",".././node_modules/@langchain/core/dist/indexing/base.js",".././node_modules/@langchain/core/dist/indexing/index.js",".././node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js",".././node_modules/js-tiktoken/dist/lite.js",".././node_modules/@langchain/core/dist/utils/tiktoken.js",".././node_modules/@langchain/core/dist/language_models/base.js",".././node_modules/@langchain/core/dist/runnables/passthrough.js",".././node_modules/@langchain/core/dist/language_models/utils.js",".././node_modules/@langchain/core/dist/language_models/chat_models.js",".././node_modules/@langchain/core/dist/language_models/llms.js",".././node_modules/@langchain/core/dist/runnables/router.js",".././node_modules/@langchain/core/dist/runnables/branch.js",".././node_modules/@langchain/core/dist/runnables/history.js",".././node_modules/@langchain/core/dist/runnables/index.js",".././node_modules/@langchain/core/dist/utils/json_patch.js",".././node_modules/@langchain/core/dist/output_parsers/base.js",".././node_modules/@langchain/core/dist/output_parsers/transform.js",".././node_modules/@langchain/core/dist/output_parsers/bytes.js",".././node_modules/@langchain/core/dist/output_parsers/list.js",".././node_modules/@langchain/core/dist/output_parsers/string.js",".././node_modules/@langchain/core/dist/output_parsers/structured.js",".././node_modules/@langchain/core/dist/output_parsers/json.js",".././node_modules/@langchain/core/dist/utils/sax-js/sax.js",".././node_modules/@langchain/core/dist/output_parsers/xml.js",".././node_modules/@langchain/core/dist/output_parsers/index.js",".././node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js",".././node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js",".././node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js",".././node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js",".././node_modules/@langchain/core/dist/prompts/base.js",".././node_modules/@langchain/core/dist/prompts/string.js",".././node_modules/mustache/mustache.mjs",".././node_modules/@langchain/core/dist/prompts/template.js",".././node_modules/@langchain/core/dist/prompts/prompt.js",".././node_modules/@langchain/core/dist/prompts/image.js",".././node_modules/@langchain/core/dist/prompts/dict.js",".././node_modules/@langchain/core/dist/prompts/chat.js",".././node_modules/@langchain/core/dist/prompts/few_shot.js",".././node_modules/@langchain/core/dist/prompts/pipeline.js",".././node_modules/@langchain/core/dist/prompts/structured.js",".././node_modules/@langchain/core/dist/prompts/index.js",".././node_modules/@langchain/core/dist/retrievers/document_compressors/base.js",".././node_modules/@langchain/core/dist/structured_query/ir.js",".././node_modules/@langchain/core/dist/structured_query/utils.js",".././node_modules/@langchain/core/dist/structured_query/base.js",".././node_modules/@langchain/core/dist/structured_query/functional.js",".././node_modules/@langchain/core/dist/structured_query/index.js",".././node_modules/@langchain/core/dist/tools/types.js",".././node_modules/@langchain/core/dist/tools/index.js",".././node_modules/@langchain/core/dist/tracers/run_collector.js",".././node_modules/@langchain/core/dist/types/stream.js",".././node_modules/@langchain/core/dist/utils/chunk_array.js",".././node_modules/@langchain/core/dist/utils/event_source_parse.js",".././node_modules/@langchain/core/dist/utils/function_calling.js",".././node_modules/@langchain/core/dist/utils/ml-distance/similarities.js",".././node_modules/@langchain/core/dist/utils/ml-distance/distances.js",".././node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js",".././node_modules/@langchain/core/dist/utils/math.js",".././node_modules/@langchain/core/dist/utils/testing/chat_models.js",".././node_modules/@langchain/core/dist/utils/testing/embeddings.js",".././node_modules/@langchain/core/dist/utils/testing/llms.js",".././node_modules/@langchain/core/dist/utils/testing/message_history.js",".././node_modules/@langchain/core/dist/utils/testing/output_parsers.js",".././node_modules/@langchain/core/dist/utils/testing/retrievers.js",".././node_modules/@langchain/core/dist/utils/testing/runnables.js",".././node_modules/@langchain/core/dist/utils/testing/tools.js",".././node_modules/@langchain/core/dist/utils/testing/tracers.js",".././node_modules/@langchain/core/dist/utils/testing/vectorstores.js",".././node_modules/@langchain/core/dist/utils/testing/index.js",".././node_modules/@langchain/core/dist/utils/types/index.js",".././node_modules/@langchain/core/dist/load/import_map.js",".././node_modules/@langchain/core/dist/load/index.js",".././node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js",".././node_modules/@langchain/langgraph-checkpoint/dist/base.js",".././node_modules/@langchain/langgraph-checkpoint/dist/memory.js",".././node_modules/@langchain/langgraph-checkpoint/dist/store/base.js",".././node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js",".././node_modules/@langchain/langgraph-checkpoint/dist/store/utils.js",".././node_modules/@langchain/langgraph-checkpoint/dist/store/memory.js",".././node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js",".././node_modules/@langchain/langgraph-checkpoint/dist/cache/memory.js",".././node_modules/@langchain/langgraph-checkpoint/dist/cache/index.js",".././node_modules/@langchain/langgraph-checkpoint/dist/index.js",".././node_modules/@langchain/langgraph/dist/channels/base.js",".././node_modules/@langchain/langgraph/dist/channels/binop.js",".././node_modules/@langchain/langgraph/dist/channels/last_value.js",".././node_modules/@langchain/langgraph/dist/graph/annotation.js",".././node_modules/@langchain/langgraph/dist/constants.js",".././node_modules/@langchain/langgraph/dist/pregel/utils/config.js",".././node_modules/@langchain/langgraph/dist/hash.js",".././node_modules/@langchain/langgraph/dist/interrupt.js",".././node_modules/@langchain/langgraph/dist/utils.js",".././node_modules/@langchain/langgraph/dist/pregel/write.js",".././node_modules/@langchain/langgraph/dist/pregel/read.js",".././node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js",".././node_modules/@langchain/langgraph/dist/pregel/io.js",".././node_modules/@langchain/langgraph/dist/pregel/utils/index.js",".././node_modules/@langchain/langgraph/dist/pregel/types.js",".././node_modules/@langchain/langgraph/dist/pregel/call.js",".././node_modules/@langchain/langgraph/dist/pregel/algo.js",".././node_modules/@langchain/langgraph/dist/pregel/debug.js",".././node_modules/@langchain/langgraph/dist/pregel/stream.js",".././node_modules/@langchain/langgraph/dist/pregel/loop.js",".././node_modules/@langchain/langgraph/dist/pregel/messages.js",".././node_modules/@langchain/langgraph/dist/pregel/retry.js",".././node_modules/@langchain/langgraph/dist/pregel/runner.js",".././node_modules/@langchain/langgraph/dist/pregel/validate.js",".././node_modules/@langchain/langgraph/dist/channels/topic.js",".././node_modules/@langchain/langgraph/dist/pregel/index.js",".././node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js",".././node_modules/zod/v4/classic/errors.js",".././node_modules/zod/v4/classic/parse.js",".././node_modules/zod/v4/classic/schemas.js",".././node_modules/@langchain/langgraph/node_modules/uuid/wrapper.mjs",".././node_modules/@langchain/langgraph/dist/graph/graph.js",".././node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js",".././node_modules/@langchain/langgraph/dist/graph/zod/meta.js",".././node_modules/@langchain/langgraph/dist/graph/state.js",".././node_modules/@langchain/langgraph/dist/graph/message.js",".././node_modules/@langchain/langgraph/dist/func/index.js",".././node_modules/@langchain/langgraph/dist/graph/messages_annotation.js",".././node_modules/@langchain/langgraph/dist/graph/index.js",".././node_modules/@langchain/langgraph/dist/channels/any_value.js",".././node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js",".././node_modules/@langchain/langgraph/dist/channels/index.js",".././node_modules/@langchain/langgraph/dist/web.js",".././node_modules/@langchain/langgraph/dist/writer.js",".././node_modules/@langchain/langgraph/dist/index.js",".././src/tools/pr-analysis-tools.ts",".././src/utils/arch-docs-parser.ts",".././src/utils/arch-docs-rag.ts",".././src/agents/base-pr-agent-workflow.ts",".././node_modules/@langchain/anthropic/dist/output_parsers.js",".././node_modules/@langchain/anthropic/dist/utils/tools.js",".././node_modules/@langchain/anthropic/dist/utils/content.js",".././node_modules/@langchain/anthropic/dist/utils/index.js",".././node_modules/@langchain/anthropic/dist/utils/standard.js",".././node_modules/@langchain/anthropic/dist/utils/message_inputs.js",".././node_modules/@langchain/anthropic/dist/utils/message_outputs.js",".././node_modules/@langchain/anthropic/dist/utils/errors.js",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/tslib.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/errors.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/error.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/version.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/shims.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/request-options.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/streaming.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/parse.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/api-promise.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/pagination.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/uploads.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/to-file.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/uploads.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/resource.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/headers.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/error.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/streaming.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/constants.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/completions.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/models.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/index.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/client.mjs",".././node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/index.mjs",".././node_modules/@langchain/anthropic/dist/chat_models.js",".././node_modules/@langchain/anthropic/dist/utils/prompts.js",".././node_modules/@langchain/anthropic/dist/index.js",".././src/providers/anthropic.provider.ts",".././node_modules/@langchain/openai/dist/utils/misc.js",".././node_modules/@langchain/openai/dist/utils/azure.js",".././node_modules/@langchain/openai/dist/utils/tools.js",".././node_modules/openai/internal/errors.mjs",".././node_modules/openai/core/error.mjs",".././node_modules/openai/error.mjs",".././node_modules/openai/lib/parser.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/Options.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/util.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs",".././node_modules/openai/_vendor/zod-to-json-schema/index.mjs",".././node_modules/openai/lib/ResponsesParser.mjs",".././node_modules/openai/lib/transform.mjs",".././node_modules/openai/helpers/zod.mjs",".././node_modules/@langchain/openai/dist/utils/output.js",".././node_modules/openai/internal/tslib.mjs",".././node_modules/openai/internal/utils/uuid.mjs",".././node_modules/openai/internal/utils/values.mjs",".././node_modules/openai/internal/utils/sleep.mjs",".././node_modules/openai/version.mjs",".././node_modules/openai/internal/detect-platform.mjs",".././node_modules/openai/internal/shims.mjs",".././node_modules/openai/internal/request-options.mjs",".././node_modules/openai/internal/qs/formats.mjs",".././node_modules/openai/internal/qs/utils.mjs",".././node_modules/openai/internal/qs/stringify.mjs",".././node_modules/openai/internal/qs/index.mjs",".././node_modules/openai/internal/utils/bytes.mjs",".././node_modules/openai/internal/decoders/line.mjs",".././node_modules/openai/internal/utils/log.mjs",".././node_modules/openai/core/streaming.mjs",".././node_modules/openai/internal/parse.mjs",".././node_modules/openai/core/api-promise.mjs",".././node_modules/openai/core/pagination.mjs",".././node_modules/openai/internal/uploads.mjs",".././node_modules/openai/internal/to-file.mjs",".././node_modules/openai/core/uploads.mjs",".././node_modules/openai/core/resource.mjs",".././node_modules/openai/internal/utils/path.mjs",".././node_modules/openai/resources/chat/completions/messages.mjs",".././node_modules/openai/lib/chatCompletionUtils.mjs",".././node_modules/openai/lib/EventStream.mjs",".././node_modules/openai/lib/RunnableFunction.mjs",".././node_modules/openai/lib/AbstractChatCompletionRunner.mjs",".././node_modules/openai/lib/ChatCompletionRunner.mjs",".././node_modules/openai/_vendor/partial-json-parser/parser.mjs",".././node_modules/openai/streaming.mjs",".././node_modules/openai/lib/ChatCompletionStream.mjs",".././node_modules/openai/lib/ChatCompletionStreamingRunner.mjs",".././node_modules/openai/resources/chat/completions/completions.mjs",".././node_modules/openai/resources/chat/chat.mjs",".././node_modules/openai/resources/chat/completions/index.mjs",".././node_modules/openai/resources/chat/index.mjs",".././node_modules/openai/internal/headers.mjs",".././node_modules/openai/resources/audio/speech.mjs",".././node_modules/openai/resources/audio/transcriptions.mjs",".././node_modules/openai/resources/audio/translations.mjs",".././node_modules/openai/resources/audio/audio.mjs",".././node_modules/openai/resources/batches.mjs",".././node_modules/openai/resources/beta/assistants.mjs",".././node_modules/openai/resources/beta/realtime/sessions.mjs",".././node_modules/openai/resources/beta/realtime/transcription-sessions.mjs",".././node_modules/openai/resources/beta/realtime/realtime.mjs",".././node_modules/openai/resources/beta/chatkit/sessions.mjs",".././node_modules/openai/resources/beta/chatkit/threads.mjs",".././node_modules/openai/resources/beta/chatkit/chatkit.mjs",".././node_modules/openai/resources/beta/threads/messages.mjs",".././node_modules/openai/resources/beta/threads/runs/steps.mjs",".././node_modules/openai/internal/utils/base64.mjs",".././node_modules/openai/internal/utils/env.mjs",".././node_modules/openai/internal/utils.mjs",".././node_modules/openai/lib/AssistantStream.mjs",".././node_modules/openai/resources/beta/threads/runs/runs.mjs",".././node_modules/openai/resources/beta/threads/threads.mjs",".././node_modules/openai/resources/beta/beta.mjs",".././node_modules/openai/resources/completions.mjs",".././node_modules/openai/resources/containers/files/content.mjs",".././node_modules/openai/resources/containers/files/files.mjs",".././node_modules/openai/resources/containers/containers.mjs",".././node_modules/openai/resources/conversations/items.mjs",".././node_modules/openai/resources/conversations/conversations.mjs",".././node_modules/openai/resources/embeddings.mjs",".././node_modules/openai/resources/evals/runs/output-items.mjs",".././node_modules/openai/resources/evals/runs/runs.mjs",".././node_modules/openai/resources/evals/evals.mjs",".././node_modules/openai/resources/files.mjs",".././node_modules/openai/resources/fine-tuning/methods.mjs",".././node_modules/openai/resources/fine-tuning/alpha/graders.mjs",".././node_modules/openai/resources/fine-tuning/alpha/alpha.mjs",".././node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs",".././node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs",".././node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs",".././node_modules/openai/resources/fine-tuning/jobs/jobs.mjs",".././node_modules/openai/resources/fine-tuning/fine-tuning.mjs",".././node_modules/openai/resources/graders/grader-models.mjs",".././node_modules/openai/resources/graders/graders.mjs",".././node_modules/openai/resources/images.mjs",".././node_modules/openai/resources/models.mjs",".././node_modules/openai/resources/moderations.mjs",".././node_modules/openai/resources/realtime/calls.mjs",".././node_modules/openai/resources/realtime/client-secrets.mjs",".././node_modules/openai/resources/realtime/realtime.mjs",".././node_modules/openai/lib/responses/ResponseStream.mjs",".././node_modules/openai/resources/responses/input-items.mjs",".././node_modules/openai/resources/responses/input-tokens.mjs",".././node_modules/openai/resources/responses/responses.mjs",".././node_modules/openai/resources/uploads/parts.mjs",".././node_modules/openai/resources/uploads/uploads.mjs",".././node_modules/openai/lib/Util.mjs",".././node_modules/openai/resources/vector-stores/file-batches.mjs",".././node_modules/openai/resources/vector-stores/files.mjs",".././node_modules/openai/resources/vector-stores/vector-stores.mjs",".././node_modules/openai/resources/videos.mjs",".././node_modules/openai/resources/webhooks.mjs",".././node_modules/openai/resources/index.mjs",".././node_modules/openai/client.mjs",".././node_modules/openai/azure.mjs",".././node_modules/openai/index.mjs",".././node_modules/@langchain/openai/dist/chat_models/base.js",".././node_modules/@langchain/openai/dist/utils/errors.js",".././node_modules/@langchain/openai/dist/utils/client.js",".././node_modules/@langchain/openai/dist/utils/standard.js",".././node_modules/@langchain/openai/dist/utils/message_inputs.js",".././node_modules/@langchain/openai/dist/chat_models/responses.js",".././node_modules/@langchain/openai/dist/chat_models/completions.js",".././node_modules/@langchain/openai/dist/chat_models/index.js",".././node_modules/@langchain/openai/dist/azure/chat_models/common.js",".././node_modules/@langchain/openai/dist/azure/chat_models/completions.js",".././node_modules/@langchain/openai/dist/azure/chat_models/responses.js",".././node_modules/@langchain/openai/dist/azure/chat_models/index.js",".././node_modules/@langchain/openai/dist/llms.js",".././node_modules/@langchain/openai/dist/azure/llms.js",".././node_modules/@langchain/openai/dist/embeddings.js",".././node_modules/@langchain/openai/dist/azure/embeddings.js",".././node_modules/@langchain/openai/dist/tools/dalle.js",".././node_modules/@langchain/openai/dist/tools/index.js",".././node_modules/@langchain/openai/dist/tools/custom.js",".././node_modules/@langchain/openai/dist/utils/prompts.js",".././node_modules/@langchain/openai/dist/index.js",".././src/providers/openai.provider.ts",".././node_modules/@langchain/google-genai/dist/utils/zod_to_genai_parameters.js",".././node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/native.js",".././node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/rng.js",".././node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/stringify.js",".././node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/v4.js",".././node_modules/@langchain/google-genai/dist/utils/common.js",".././node_modules/@langchain/google-genai/dist/output_parsers.js",".././node_modules/@google/generative-ai/dist/index.mjs",".././node_modules/@langchain/google-genai/dist/utils/tools.js",".././node_modules/@langchain/google-genai/dist/chat_models.js",".././node_modules/@langchain/google-genai/dist/embeddings.js",".././node_modules/@langchain/google-genai/dist/index.js",".././src/providers/google.provider.ts",".././src/providers/provider.factory.ts",".././src/providers/index.ts",".././src/agents/pr-analyzer-agent.ts",".././src/action.ts"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issue = exports.issueCommand = void 0;\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return (0, utils_1.toCommandValue)(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return (0, utils_1.toCommandValue)(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\nconst oidc_utils_1 = require(\"./oidc-utils\");\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode || (exports.ExitCode = ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = (0, utils_1.toCommandValue)(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val));\n }\n (0, command_1.issueCommand)('set-env', { name }, convertedVal);\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n (0, command_1.issueCommand)('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n (0, file_command_1.issueFileCommand)('PATH', inputPath);\n }\n else {\n (0, command_1.issueCommand)('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input.\n * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.\n * Returns an empty string if the value is not defined.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n if (options && options.trimWhitespace === false) {\n return val;\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Gets the values of an multiline input. Each value is also trimmed.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string[]\n *\n */\nfunction getMultilineInput(name, options) {\n const inputs = getInput(name, options)\n .split('\\n')\n .filter(x => x !== '');\n if (options && options.trimWhitespace === false) {\n return inputs;\n }\n return inputs.map(input => input.trim());\n}\nexports.getMultilineInput = getMultilineInput;\n/**\n * Gets the input value of the boolean type in the YAML 1.2 \"core schema\" specification.\n * Support boolean input list: `true | True | TRUE | false | False | FALSE` .\n * The return value is also in boolean type.\n * ref: https://yaml.org/spec/1.2/spec.html#id2804923\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns boolean\n */\nfunction getBooleanInput(name, options) {\n const trueValue = ['true', 'True', 'TRUE'];\n const falseValue = ['false', 'False', 'FALSE'];\n const val = getInput(name, options);\n if (trueValue.includes(val))\n return true;\n if (falseValue.includes(val))\n return false;\n throw new TypeError(`Input does not meet YAML 1.2 \"Core Schema\" specification: ${name}\\n` +\n `Support boolean input list: \\`true | True | TRUE | false | False | FALSE\\``);\n}\nexports.getBooleanInput = getBooleanInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n const filePath = process.env['GITHUB_OUTPUT'] || '';\n if (filePath) {\n return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value));\n }\n process.stdout.write(os.EOL);\n (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value));\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n (0, command_1.issue)('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n (0, command_1.issueCommand)('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction error(message, properties = {}) {\n (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds a warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction warning(message, properties = {}) {\n (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Adds a notice issue\n * @param message notice issue message. Errors will be converted to string via toString()\n * @param properties optional properties to add to the annotation.\n */\nfunction notice(message, properties = {}) {\n (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message);\n}\nexports.notice = notice;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n (0, command_1.issue)('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n (0, command_1.issue)('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n const filePath = process.env['GITHUB_STATE'] || '';\n if (filePath) {\n return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value));\n }\n (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value));\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\nfunction getIDToken(aud) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield oidc_utils_1.OidcClient.getIDToken(aud);\n });\n}\nexports.getIDToken = getIDToken;\n/**\n * Summary exports\n */\nvar summary_1 = require(\"./summary\");\nObject.defineProperty(exports, \"summary\", { enumerable: true, get: function () { return summary_1.summary; } });\n/**\n * @deprecated use core.summary\n */\nvar summary_2 = require(\"./summary\");\nObject.defineProperty(exports, \"markdownSummary\", { enumerable: true, get: function () { return summary_2.markdownSummary; } });\n/**\n * Path exports\n */\nvar path_utils_1 = require(\"./path-utils\");\nObject.defineProperty(exports, \"toPosixPath\", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });\nObject.defineProperty(exports, \"toWin32Path\", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });\nObject.defineProperty(exports, \"toPlatformPath\", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });\n/**\n * Platform utilities exports\n */\nexports.platform = __importStar(require(\"./platform\"));\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.prepareKeyValueMessage = exports.issueFileCommand = void 0;\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst crypto = __importStar(require(\"crypto\"));\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\nfunction issueFileCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueFileCommand = issueFileCommand;\nfunction prepareKeyValueMessage(key, value) {\n const delimiter = `ghadelimiter_${crypto.randomUUID()}`;\n const convertedValue = (0, utils_1.toCommandValue)(value);\n // These should realistically never happen, but just in case someone finds a\n // way to exploit uuid generation let's not allow keys or values that contain\n // the delimiter.\n if (key.includes(delimiter)) {\n throw new Error(`Unexpected input: name should not contain the delimiter \"${delimiter}\"`);\n }\n if (convertedValue.includes(delimiter)) {\n throw new Error(`Unexpected input: value should not contain the delimiter \"${delimiter}\"`);\n }\n return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;\n}\nexports.prepareKeyValueMessage = prepareKeyValueMessage;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OidcClient = void 0;\nconst http_client_1 = require(\"@actions/http-client\");\nconst auth_1 = require(\"@actions/http-client/lib/auth\");\nconst core_1 = require(\"./core\");\nclass OidcClient {\n static createHttpClient(allowRetry = true, maxRetry = 10) {\n const requestOptions = {\n allowRetries: allowRetry,\n maxRetries: maxRetry\n };\n return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);\n }\n static getRequestToken() {\n const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];\n if (!token) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');\n }\n return token;\n }\n static getIDTokenUrl() {\n const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];\n if (!runtimeUrl) {\n throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');\n }\n return runtimeUrl;\n }\n static getCall(id_token_url) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const httpclient = OidcClient.createHttpClient();\n const res = yield httpclient\n .getJson(id_token_url)\n .catch(error => {\n throw new Error(`Failed to get ID Token. \\n \n Error Code : ${error.statusCode}\\n \n Error Message: ${error.message}`);\n });\n const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;\n if (!id_token) {\n throw new Error('Response json body do not have ID Token field');\n }\n return id_token;\n });\n }\n static getIDToken(audience) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // New ID Token is requested from action service\n let id_token_url = OidcClient.getIDTokenUrl();\n if (audience) {\n const encodedAudience = encodeURIComponent(audience);\n id_token_url = `${id_token_url}&audience=${encodedAudience}`;\n }\n (0, core_1.debug)(`ID token url is ${id_token_url}`);\n const id_token = yield OidcClient.getCall(id_token_url);\n (0, core_1.setSecret)(id_token);\n return id_token;\n }\n catch (error) {\n throw new Error(`Error message: ${error.message}`);\n }\n });\n }\n}\nexports.OidcClient = OidcClient;\n//# sourceMappingURL=oidc-utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;\nconst path = __importStar(require(\"path\"));\n/**\n * toPosixPath converts the given path to the posix form. On Windows, \\\\ will be\n * replaced with /.\n *\n * @param pth. Path to transform.\n * @return string Posix path.\n */\nfunction toPosixPath(pth) {\n return pth.replace(/[\\\\]/g, '/');\n}\nexports.toPosixPath = toPosixPath;\n/**\n * toWin32Path converts the given path to the win32 form. On Linux, / will be\n * replaced with \\\\.\n *\n * @param pth. Path to transform.\n * @return string Win32 path.\n */\nfunction toWin32Path(pth) {\n return pth.replace(/[/]/g, '\\\\');\n}\nexports.toWin32Path = toWin32Path;\n/**\n * toPlatformPath converts the given path to a platform-specific path. It does\n * this by replacing instances of / and \\ with the platform-specific path\n * separator.\n *\n * @param pth The path to platformize.\n * @return string The platform-specific path.\n */\nfunction toPlatformPath(pth) {\n return pth.replace(/[/\\\\]/g, path.sep);\n}\nexports.toPlatformPath = toPlatformPath;\n//# sourceMappingURL=path-utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0;\nconst os_1 = __importDefault(require(\"os\"));\nconst exec = __importStar(require(\"@actions/exec\"));\nconst getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () {\n const { stdout: version } = yield exec.getExecOutput('powershell -command \"(Get-CimInstance -ClassName Win32_OperatingSystem).Version\"', undefined, {\n silent: true\n });\n const { stdout: name } = yield exec.getExecOutput('powershell -command \"(Get-CimInstance -ClassName Win32_OperatingSystem).Caption\"', undefined, {\n silent: true\n });\n return {\n name: name.trim(),\n version: version.trim()\n };\n});\nconst getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () {\n var _a, _b, _c, _d;\n const { stdout } = yield exec.getExecOutput('sw_vers', undefined, {\n silent: true\n });\n const version = (_b = (_a = stdout.match(/ProductVersion:\\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : '';\n const name = (_d = (_c = stdout.match(/ProductName:\\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : '';\n return {\n name,\n version\n };\n});\nconst getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () {\n const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], {\n silent: true\n });\n const [name, version] = stdout.trim().split('\\n');\n return {\n name,\n version\n };\n});\nexports.platform = os_1.default.platform();\nexports.arch = os_1.default.arch();\nexports.isWindows = exports.platform === 'win32';\nexports.isMacOS = exports.platform === 'darwin';\nexports.isLinux = exports.platform === 'linux';\nfunction getDetails() {\n return __awaiter(this, void 0, void 0, function* () {\n return Object.assign(Object.assign({}, (yield (exports.isWindows\n ? getWindowsInfo()\n : exports.isMacOS\n ? getMacOsInfo()\n : getLinuxInfo()))), { platform: exports.platform,\n arch: exports.arch,\n isWindows: exports.isWindows,\n isMacOS: exports.isMacOS,\n isLinux: exports.isLinux });\n });\n}\nexports.getDetails = getDetails;\n//# sourceMappingURL=platform.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;\nconst os_1 = require(\"os\");\nconst fs_1 = require(\"fs\");\nconst { access, appendFile, writeFile } = fs_1.promises;\nexports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';\nexports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';\nclass Summary {\n constructor() {\n this._buffer = '';\n }\n /**\n * Finds the summary file path from the environment, rejects if env var is not found or file does not exist\n * Also checks r/w permissions.\n *\n * @returns step summary file path\n */\n filePath() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._filePath) {\n return this._filePath;\n }\n const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];\n if (!pathFromEnv) {\n throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);\n }\n try {\n yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);\n }\n catch (_a) {\n throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);\n }\n this._filePath = pathFromEnv;\n return this._filePath;\n });\n }\n /**\n * Wraps content in an HTML tag, adding any HTML attributes\n *\n * @param {string} tag HTML tag to wrap\n * @param {string | null} content content within the tag\n * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add\n *\n * @returns {string} content wrapped in HTML element\n */\n wrap(tag, content, attrs = {}) {\n const htmlAttrs = Object.entries(attrs)\n .map(([key, value]) => ` ${key}=\"${value}\"`)\n .join('');\n if (!content) {\n return `<${tag}${htmlAttrs}>`;\n }\n return `<${tag}${htmlAttrs}>${content}`;\n }\n /**\n * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.\n *\n * @param {SummaryWriteOptions} [options] (optional) options for write operation\n *\n * @returns {Promise} summary instance\n */\n write(options) {\n return __awaiter(this, void 0, void 0, function* () {\n const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);\n const filePath = yield this.filePath();\n const writeFunc = overwrite ? writeFile : appendFile;\n yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });\n return this.emptyBuffer();\n });\n }\n /**\n * Clears the summary buffer and wipes the summary file\n *\n * @returns {Summary} summary instance\n */\n clear() {\n return __awaiter(this, void 0, void 0, function* () {\n return this.emptyBuffer().write({ overwrite: true });\n });\n }\n /**\n * Returns the current summary buffer as a string\n *\n * @returns {string} string of summary buffer\n */\n stringify() {\n return this._buffer;\n }\n /**\n * If the summary buffer is empty\n *\n * @returns {boolen} true if the buffer is empty\n */\n isEmptyBuffer() {\n return this._buffer.length === 0;\n }\n /**\n * Resets the summary buffer without writing to summary file\n *\n * @returns {Summary} summary instance\n */\n emptyBuffer() {\n this._buffer = '';\n return this;\n }\n /**\n * Adds raw text to the summary buffer\n *\n * @param {string} text content to add\n * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)\n *\n * @returns {Summary} summary instance\n */\n addRaw(text, addEOL = false) {\n this._buffer += text;\n return addEOL ? this.addEOL() : this;\n }\n /**\n * Adds the operating system-specific end-of-line marker to the buffer\n *\n * @returns {Summary} summary instance\n */\n addEOL() {\n return this.addRaw(os_1.EOL);\n }\n /**\n * Adds an HTML codeblock to the summary buffer\n *\n * @param {string} code content to render within fenced code block\n * @param {string} lang (optional) language to syntax highlight code\n *\n * @returns {Summary} summary instance\n */\n addCodeBlock(code, lang) {\n const attrs = Object.assign({}, (lang && { lang }));\n const element = this.wrap('pre', this.wrap('code', code), attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML list to the summary buffer\n *\n * @param {string[]} items list of items to render\n * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)\n *\n * @returns {Summary} summary instance\n */\n addList(items, ordered = false) {\n const tag = ordered ? 'ol' : 'ul';\n const listItems = items.map(item => this.wrap('li', item)).join('');\n const element = this.wrap(tag, listItems);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML table to the summary buffer\n *\n * @param {SummaryTableCell[]} rows table rows\n *\n * @returns {Summary} summary instance\n */\n addTable(rows) {\n const tableBody = rows\n .map(row => {\n const cells = row\n .map(cell => {\n if (typeof cell === 'string') {\n return this.wrap('td', cell);\n }\n const { header, data, colspan, rowspan } = cell;\n const tag = header ? 'th' : 'td';\n const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));\n return this.wrap(tag, data, attrs);\n })\n .join('');\n return this.wrap('tr', cells);\n })\n .join('');\n const element = this.wrap('table', tableBody);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds a collapsable HTML details element to the summary buffer\n *\n * @param {string} label text for the closed state\n * @param {string} content collapsable content\n *\n * @returns {Summary} summary instance\n */\n addDetails(label, content) {\n const element = this.wrap('details', this.wrap('summary', label) + content);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML image tag to the summary buffer\n *\n * @param {string} src path to the image you to embed\n * @param {string} alt text description of the image\n * @param {SummaryImageOptions} options (optional) addition image attributes\n *\n * @returns {Summary} summary instance\n */\n addImage(src, alt, options) {\n const { width, height } = options || {};\n const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));\n const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML section heading element\n *\n * @param {string} text heading text\n * @param {number | string} [level=1] (optional) the heading level, default: 1\n *\n * @returns {Summary} summary instance\n */\n addHeading(text, level) {\n const tag = `h${level}`;\n const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)\n ? tag\n : 'h1';\n const element = this.wrap(allowedTag, text);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML thematic break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addSeparator() {\n const element = this.wrap('hr', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML line break (
) to the summary buffer\n *\n * @returns {Summary} summary instance\n */\n addBreak() {\n const element = this.wrap('br', null);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML blockquote to the summary buffer\n *\n * @param {string} text quote text\n * @param {string} cite (optional) citation url\n *\n * @returns {Summary} summary instance\n */\n addQuote(text, cite) {\n const attrs = Object.assign({}, (cite && { cite }));\n const element = this.wrap('blockquote', text, attrs);\n return this.addRaw(element).addEOL();\n }\n /**\n * Adds an HTML anchor tag to the summary buffer\n *\n * @param {string} text link text/content\n * @param {string} href hyperlink\n *\n * @returns {Summary} summary instance\n */\n addLink(text, href) {\n const element = this.wrap('a', text, { href });\n return this.addRaw(element).addEOL();\n }\n}\nconst _summary = new Summary();\n/**\n * @deprecated use `core.summary`\n */\nexports.markdownSummary = _summary;\nexports.summary = _summary;\n//# sourceMappingURL=summary.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toCommandProperties = exports.toCommandValue = void 0;\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n/**\n *\n * @param annotationProperties\n * @returns The command properties to send with the actual annotation command\n * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646\n */\nfunction toCommandProperties(annotationProperties) {\n if (!Object.keys(annotationProperties).length) {\n return {};\n }\n return {\n title: annotationProperties.title,\n file: annotationProperties.file,\n line: annotationProperties.startLine,\n endLine: annotationProperties.endLine,\n col: annotationProperties.startColumn,\n endColumn: annotationProperties.endColumn\n };\n}\nexports.toCommandProperties = toCommandProperties;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getExecOutput = exports.exec = void 0;\nconst string_decoder_1 = require(\"string_decoder\");\nconst tr = __importStar(require(\"./toolrunner\"));\n/**\n * Exec a command.\n * Output will be streamed to the live console.\n * Returns promise with return code\n *\n * @param commandLine command to execute (can include additional args). Must be correctly escaped.\n * @param args optional arguments for tool. Escaping is handled by the lib.\n * @param options optional exec options. See ExecOptions\n * @returns Promise exit code\n */\nfunction exec(commandLine, args, options) {\n return __awaiter(this, void 0, void 0, function* () {\n const commandArgs = tr.argStringToArray(commandLine);\n if (commandArgs.length === 0) {\n throw new Error(`Parameter 'commandLine' cannot be null or empty.`);\n }\n // Path to tool to execute should be first arg\n const toolPath = commandArgs[0];\n args = commandArgs.slice(1).concat(args || []);\n const runner = new tr.ToolRunner(toolPath, args, options);\n return runner.exec();\n });\n}\nexports.exec = exec;\n/**\n * Exec a command and get the output.\n * Output will be streamed to the live console.\n * Returns promise with the exit code and collected stdout and stderr\n *\n * @param commandLine command to execute (can include additional args). Must be correctly escaped.\n * @param args optional arguments for tool. Escaping is handled by the lib.\n * @param options optional exec options. See ExecOptions\n * @returns Promise exit code, stdout, and stderr\n */\nfunction getExecOutput(commandLine, args, options) {\n var _a, _b;\n return __awaiter(this, void 0, void 0, function* () {\n let stdout = '';\n let stderr = '';\n //Using string decoder covers the case where a mult-byte character is split\n const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');\n const stderrDecoder = new string_decoder_1.StringDecoder('utf8');\n const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;\n const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;\n const stdErrListener = (data) => {\n stderr += stderrDecoder.write(data);\n if (originalStdErrListener) {\n originalStdErrListener(data);\n }\n };\n const stdOutListener = (data) => {\n stdout += stdoutDecoder.write(data);\n if (originalStdoutListener) {\n originalStdoutListener(data);\n }\n };\n const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener });\n const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners }));\n //flush any remaining characters\n stdout += stdoutDecoder.end();\n stderr += stderrDecoder.end();\n return {\n exitCode,\n stdout,\n stderr\n };\n });\n}\nexports.getExecOutput = getExecOutput;\n//# sourceMappingURL=exec.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.argStringToArray = exports.ToolRunner = void 0;\nconst os = __importStar(require(\"os\"));\nconst events = __importStar(require(\"events\"));\nconst child = __importStar(require(\"child_process\"));\nconst path = __importStar(require(\"path\"));\nconst io = __importStar(require(\"@actions/io\"));\nconst ioUtil = __importStar(require(\"@actions/io/lib/io-util\"));\nconst timers_1 = require(\"timers\");\n/* eslint-disable @typescript-eslint/unbound-method */\nconst IS_WINDOWS = process.platform === 'win32';\n/*\n * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.\n */\nclass ToolRunner extends events.EventEmitter {\n constructor(toolPath, args, options) {\n super();\n if (!toolPath) {\n throw new Error(\"Parameter 'toolPath' cannot be null or empty.\");\n }\n this.toolPath = toolPath;\n this.args = args || [];\n this.options = options || {};\n }\n _debug(message) {\n if (this.options.listeners && this.options.listeners.debug) {\n this.options.listeners.debug(message);\n }\n }\n _getCommandString(options, noPrefix) {\n const toolPath = this._getSpawnFileName();\n const args = this._getSpawnArgs(options);\n let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool\n if (IS_WINDOWS) {\n // Windows + cmd file\n if (this._isCmdFile()) {\n cmd += toolPath;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n // Windows + verbatim\n else if (options.windowsVerbatimArguments) {\n cmd += `\"${toolPath}\"`;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n // Windows (regular)\n else {\n cmd += this._windowsQuoteCmdArg(toolPath);\n for (const a of args) {\n cmd += ` ${this._windowsQuoteCmdArg(a)}`;\n }\n }\n }\n else {\n // OSX/Linux - this can likely be improved with some form of quoting.\n // creating processes on Unix is fundamentally different than Windows.\n // on Unix, execvp() takes an arg array.\n cmd += toolPath;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n return cmd;\n }\n _processLineBuffer(data, strBuffer, onLine) {\n try {\n let s = strBuffer + data.toString();\n let n = s.indexOf(os.EOL);\n while (n > -1) {\n const line = s.substring(0, n);\n onLine(line);\n // the rest of the string ...\n s = s.substring(n + os.EOL.length);\n n = s.indexOf(os.EOL);\n }\n return s;\n }\n catch (err) {\n // streaming lines to console is best effort. Don't fail a build.\n this._debug(`error processing line. Failed with error ${err}`);\n return '';\n }\n }\n _getSpawnFileName() {\n if (IS_WINDOWS) {\n if (this._isCmdFile()) {\n return process.env['COMSPEC'] || 'cmd.exe';\n }\n }\n return this.toolPath;\n }\n _getSpawnArgs(options) {\n if (IS_WINDOWS) {\n if (this._isCmdFile()) {\n let argline = `/D /S /C \"${this._windowsQuoteCmdArg(this.toolPath)}`;\n for (const a of this.args) {\n argline += ' ';\n argline += options.windowsVerbatimArguments\n ? a\n : this._windowsQuoteCmdArg(a);\n }\n argline += '\"';\n return [argline];\n }\n }\n return this.args;\n }\n _endsWith(str, end) {\n return str.endsWith(end);\n }\n _isCmdFile() {\n const upperToolPath = this.toolPath.toUpperCase();\n return (this._endsWith(upperToolPath, '.CMD') ||\n this._endsWith(upperToolPath, '.BAT'));\n }\n _windowsQuoteCmdArg(arg) {\n // for .exe, apply the normal quoting rules that libuv applies\n if (!this._isCmdFile()) {\n return this._uvQuoteCmdArg(arg);\n }\n // otherwise apply quoting rules specific to the cmd.exe command line parser.\n // the libuv rules are generic and are not designed specifically for cmd.exe\n // command line parser.\n //\n // for a detailed description of the cmd.exe command line parser, refer to\n // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912\n // need quotes for empty arg\n if (!arg) {\n return '\"\"';\n }\n // determine whether the arg needs to be quoted\n const cmdSpecialChars = [\n ' ',\n '\\t',\n '&',\n '(',\n ')',\n '[',\n ']',\n '{',\n '}',\n '^',\n '=',\n ';',\n '!',\n \"'\",\n '+',\n ',',\n '`',\n '~',\n '|',\n '<',\n '>',\n '\"'\n ];\n let needsQuotes = false;\n for (const char of arg) {\n if (cmdSpecialChars.some(x => x === char)) {\n needsQuotes = true;\n break;\n }\n }\n // short-circuit if quotes not needed\n if (!needsQuotes) {\n return arg;\n }\n // the following quoting rules are very similar to the rules that by libuv applies.\n //\n // 1) wrap the string in quotes\n //\n // 2) double-up quotes - i.e. \" => \"\"\n //\n // this is different from the libuv quoting rules. libuv replaces \" with \\\", which unfortunately\n // doesn't work well with a cmd.exe command line.\n //\n // note, replacing \" with \"\" also works well if the arg is passed to a downstream .NET console app.\n // for example, the command line:\n // foo.exe \"myarg:\"\"my val\"\"\"\n // is parsed by a .NET console app into an arg array:\n // [ \"myarg:\\\"my val\\\"\" ]\n // which is the same end result when applying libuv quoting rules. although the actual\n // command line from libuv quoting rules would look like:\n // foo.exe \"myarg:\\\"my val\\\"\"\n //\n // 3) double-up slashes that precede a quote,\n // e.g. hello \\world => \"hello \\world\"\n // hello\\\"world => \"hello\\\\\"\"world\"\n // hello\\\\\"world => \"hello\\\\\\\\\"\"world\"\n // hello world\\ => \"hello world\\\\\"\n //\n // technically this is not required for a cmd.exe command line, or the batch argument parser.\n // the reasons for including this as a .cmd quoting rule are:\n //\n // a) this is optimized for the scenario where the argument is passed from the .cmd file to an\n // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.\n //\n // b) it's what we've been doing previously (by deferring to node default behavior) and we\n // haven't heard any complaints about that aspect.\n //\n // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be\n // escaped when used on the command line directly - even though within a .cmd file % can be escaped\n // by using %%.\n //\n // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts\n // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.\n //\n // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would\n // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the\n // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args\n // to an external program.\n //\n // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.\n // % can be escaped within a .cmd file.\n let reverse = '\"';\n let quoteHit = true;\n for (let i = arg.length; i > 0; i--) {\n // walk the string in reverse\n reverse += arg[i - 1];\n if (quoteHit && arg[i - 1] === '\\\\') {\n reverse += '\\\\'; // double the slash\n }\n else if (arg[i - 1] === '\"') {\n quoteHit = true;\n reverse += '\"'; // double the quote\n }\n else {\n quoteHit = false;\n }\n }\n reverse += '\"';\n return reverse\n .split('')\n .reverse()\n .join('');\n }\n _uvQuoteCmdArg(arg) {\n // Tool runner wraps child_process.spawn() and needs to apply the same quoting as\n // Node in certain cases where the undocumented spawn option windowsVerbatimArguments\n // is used.\n //\n // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,\n // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),\n // pasting copyright notice from Node within this function:\n //\n // Copyright Joyent, Inc. and other Node contributors. All rights reserved.\n //\n // Permission is hereby granted, free of charge, to any person obtaining a copy\n // of this software and associated documentation files (the \"Software\"), to\n // deal in the Software without restriction, including without limitation the\n // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n // sell copies of the Software, and to permit persons to whom the Software is\n // furnished to do so, subject to the following conditions:\n //\n // The above copyright notice and this permission notice shall be included in\n // all copies or substantial portions of the Software.\n //\n // THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n // IN THE SOFTWARE.\n if (!arg) {\n // Need double quotation for empty argument\n return '\"\"';\n }\n if (!arg.includes(' ') && !arg.includes('\\t') && !arg.includes('\"')) {\n // No quotation needed\n return arg;\n }\n if (!arg.includes('\"') && !arg.includes('\\\\')) {\n // No embedded double quotes or backslashes, so I can just wrap\n // quote marks around the whole thing.\n return `\"${arg}\"`;\n }\n // Expected input/output:\n // input : hello\"world\n // output: \"hello\\\"world\"\n // input : hello\"\"world\n // output: \"hello\\\"\\\"world\"\n // input : hello\\world\n // output: hello\\world\n // input : hello\\\\world\n // output: hello\\\\world\n // input : hello\\\"world\n // output: \"hello\\\\\\\"world\"\n // input : hello\\\\\"world\n // output: \"hello\\\\\\\\\\\"world\"\n // input : hello world\\\n // output: \"hello world\\\\\" - note the comment in libuv actually reads \"hello world\\\"\n // but it appears the comment is wrong, it should be \"hello world\\\\\"\n let reverse = '\"';\n let quoteHit = true;\n for (let i = arg.length; i > 0; i--) {\n // walk the string in reverse\n reverse += arg[i - 1];\n if (quoteHit && arg[i - 1] === '\\\\') {\n reverse += '\\\\';\n }\n else if (arg[i - 1] === '\"') {\n quoteHit = true;\n reverse += '\\\\';\n }\n else {\n quoteHit = false;\n }\n }\n reverse += '\"';\n return reverse\n .split('')\n .reverse()\n .join('');\n }\n _cloneExecOptions(options) {\n options = options || {};\n const result = {\n cwd: options.cwd || process.cwd(),\n env: options.env || process.env,\n silent: options.silent || false,\n windowsVerbatimArguments: options.windowsVerbatimArguments || false,\n failOnStdErr: options.failOnStdErr || false,\n ignoreReturnCode: options.ignoreReturnCode || false,\n delay: options.delay || 10000\n };\n result.outStream = options.outStream || process.stdout;\n result.errStream = options.errStream || process.stderr;\n return result;\n }\n _getSpawnOptions(options, toolPath) {\n options = options || {};\n const result = {};\n result.cwd = options.cwd;\n result.env = options.env;\n result['windowsVerbatimArguments'] =\n options.windowsVerbatimArguments || this._isCmdFile();\n if (options.windowsVerbatimArguments) {\n result.argv0 = `\"${toolPath}\"`;\n }\n return result;\n }\n /**\n * Exec a tool.\n * Output will be streamed to the live console.\n * Returns promise with return code\n *\n * @param tool path to tool to exec\n * @param options optional exec options. See ExecOptions\n * @returns number\n */\n exec() {\n return __awaiter(this, void 0, void 0, function* () {\n // root the tool path if it is unrooted and contains relative pathing\n if (!ioUtil.isRooted(this.toolPath) &&\n (this.toolPath.includes('/') ||\n (IS_WINDOWS && this.toolPath.includes('\\\\')))) {\n // prefer options.cwd if it is specified, however options.cwd may also need to be rooted\n this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);\n }\n // if the tool is only a file name, then resolve it from the PATH\n // otherwise verify it exists (add extension on Windows if necessary)\n this.toolPath = yield io.which(this.toolPath, true);\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n this._debug(`exec tool: ${this.toolPath}`);\n this._debug('arguments:');\n for (const arg of this.args) {\n this._debug(` ${arg}`);\n }\n const optionsNonNull = this._cloneExecOptions(this.options);\n if (!optionsNonNull.silent && optionsNonNull.outStream) {\n optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);\n }\n const state = new ExecState(optionsNonNull, this.toolPath);\n state.on('debug', (message) => {\n this._debug(message);\n });\n if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) {\n return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));\n }\n const fileName = this._getSpawnFileName();\n const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));\n let stdbuffer = '';\n if (cp.stdout) {\n cp.stdout.on('data', (data) => {\n if (this.options.listeners && this.options.listeners.stdout) {\n this.options.listeners.stdout(data);\n }\n if (!optionsNonNull.silent && optionsNonNull.outStream) {\n optionsNonNull.outStream.write(data);\n }\n stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {\n if (this.options.listeners && this.options.listeners.stdline) {\n this.options.listeners.stdline(line);\n }\n });\n });\n }\n let errbuffer = '';\n if (cp.stderr) {\n cp.stderr.on('data', (data) => {\n state.processStderr = true;\n if (this.options.listeners && this.options.listeners.stderr) {\n this.options.listeners.stderr(data);\n }\n if (!optionsNonNull.silent &&\n optionsNonNull.errStream &&\n optionsNonNull.outStream) {\n const s = optionsNonNull.failOnStdErr\n ? optionsNonNull.errStream\n : optionsNonNull.outStream;\n s.write(data);\n }\n errbuffer = this._processLineBuffer(data, errbuffer, (line) => {\n if (this.options.listeners && this.options.listeners.errline) {\n this.options.listeners.errline(line);\n }\n });\n });\n }\n cp.on('error', (err) => {\n state.processError = err.message;\n state.processExited = true;\n state.processClosed = true;\n state.CheckComplete();\n });\n cp.on('exit', (code) => {\n state.processExitCode = code;\n state.processExited = true;\n this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);\n state.CheckComplete();\n });\n cp.on('close', (code) => {\n state.processExitCode = code;\n state.processExited = true;\n state.processClosed = true;\n this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);\n state.CheckComplete();\n });\n state.on('done', (error, exitCode) => {\n if (stdbuffer.length > 0) {\n this.emit('stdline', stdbuffer);\n }\n if (errbuffer.length > 0) {\n this.emit('errline', errbuffer);\n }\n cp.removeAllListeners();\n if (error) {\n reject(error);\n }\n else {\n resolve(exitCode);\n }\n });\n if (this.options.input) {\n if (!cp.stdin) {\n throw new Error('child process missing stdin');\n }\n cp.stdin.end(this.options.input);\n }\n }));\n });\n }\n}\nexports.ToolRunner = ToolRunner;\n/**\n * Convert an arg string to an array of args. Handles escaping\n *\n * @param argString string of arguments\n * @returns string[] array of arguments\n */\nfunction argStringToArray(argString) {\n const args = [];\n let inQuotes = false;\n let escaped = false;\n let arg = '';\n function append(c) {\n // we only escape double quotes.\n if (escaped && c !== '\"') {\n arg += '\\\\';\n }\n arg += c;\n escaped = false;\n }\n for (let i = 0; i < argString.length; i++) {\n const c = argString.charAt(i);\n if (c === '\"') {\n if (!escaped) {\n inQuotes = !inQuotes;\n }\n else {\n append(c);\n }\n continue;\n }\n if (c === '\\\\' && escaped) {\n append(c);\n continue;\n }\n if (c === '\\\\' && inQuotes) {\n escaped = true;\n continue;\n }\n if (c === ' ' && !inQuotes) {\n if (arg.length > 0) {\n args.push(arg);\n arg = '';\n }\n continue;\n }\n append(c);\n }\n if (arg.length > 0) {\n args.push(arg.trim());\n }\n return args;\n}\nexports.argStringToArray = argStringToArray;\nclass ExecState extends events.EventEmitter {\n constructor(options, toolPath) {\n super();\n this.processClosed = false; // tracks whether the process has exited and stdio is closed\n this.processError = '';\n this.processExitCode = 0;\n this.processExited = false; // tracks whether the process has exited\n this.processStderr = false; // tracks whether stderr was written to\n this.delay = 10000; // 10 seconds\n this.done = false;\n this.timeout = null;\n if (!toolPath) {\n throw new Error('toolPath must not be empty');\n }\n this.options = options;\n this.toolPath = toolPath;\n if (options.delay) {\n this.delay = options.delay;\n }\n }\n CheckComplete() {\n if (this.done) {\n return;\n }\n if (this.processClosed) {\n this._setResult();\n }\n else if (this.processExited) {\n this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this);\n }\n }\n _debug(message) {\n this.emit('debug', message);\n }\n _setResult() {\n // determine whether there is an error\n let error;\n if (this.processExited) {\n if (this.processError) {\n error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);\n }\n else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {\n error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);\n }\n else if (this.processStderr && this.options.failOnStdErr) {\n error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);\n }\n }\n // clear the timeout\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n this.done = true;\n this.emit('done', error, this.processExitCode);\n }\n static HandleTimeout(state) {\n if (state.done) {\n return;\n }\n if (!state.processClosed && state.processExited) {\n const message = `The STDIO streams did not close within ${state.delay /\n 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;\n state._debug(message);\n }\n state._setResult();\n }\n}\n//# sourceMappingURL=toolrunner.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Context = void 0;\nconst fs_1 = require(\"fs\");\nconst os_1 = require(\"os\");\nclass Context {\n /**\n * Hydrate the context from the environment\n */\n constructor() {\n var _a, _b, _c;\n this.payload = {};\n if (process.env.GITHUB_EVENT_PATH) {\n if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) {\n this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));\n }\n else {\n const path = process.env.GITHUB_EVENT_PATH;\n process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);\n }\n }\n this.eventName = process.env.GITHUB_EVENT_NAME;\n this.sha = process.env.GITHUB_SHA;\n this.ref = process.env.GITHUB_REF;\n this.workflow = process.env.GITHUB_WORKFLOW;\n this.action = process.env.GITHUB_ACTION;\n this.actor = process.env.GITHUB_ACTOR;\n this.job = process.env.GITHUB_JOB;\n this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10);\n this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);\n this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);\n this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`;\n this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`;\n this.graphqlUrl =\n (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`;\n }\n get issue() {\n const payload = this.payload;\n return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });\n }\n get repo() {\n if (process.env.GITHUB_REPOSITORY) {\n const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');\n return { owner, repo };\n }\n if (this.payload.repository) {\n return {\n owner: this.payload.repository.owner.login,\n repo: this.payload.repository.name\n };\n }\n throw new Error(\"context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'\");\n }\n}\nexports.Context = Context;\n//# sourceMappingURL=context.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokit = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst utils_1 = require(\"./utils\");\nexports.context = new Context.Context();\n/**\n * Returns a hydrated octokit ready to use for GitHub Actions\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokit(token, options, ...additionalPlugins) {\n const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins);\n return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options));\n}\nexports.getOctokit = getOctokit;\n//# sourceMappingURL=github.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0;\nconst httpClient = __importStar(require(\"@actions/http-client\"));\nconst undici_1 = require(\"undici\");\nfunction getAuthString(token, options) {\n if (!token && !options.auth) {\n throw new Error('Parameter token or opts.auth is required');\n }\n else if (token && options.auth) {\n throw new Error('Parameters token and opts.auth may not both be specified');\n }\n return typeof options.auth === 'string' ? options.auth : `token ${token}`;\n}\nexports.getAuthString = getAuthString;\nfunction getProxyAgent(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgent(destinationUrl);\n}\nexports.getProxyAgent = getProxyAgent;\nfunction getProxyAgentDispatcher(destinationUrl) {\n const hc = new httpClient.HttpClient();\n return hc.getAgentDispatcher(destinationUrl);\n}\nexports.getProxyAgentDispatcher = getProxyAgentDispatcher;\nfunction getProxyFetch(destinationUrl) {\n const httpDispatcher = getProxyAgentDispatcher(destinationUrl);\n const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () {\n return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));\n });\n return proxyFetch;\n}\nexports.getProxyFetch = getProxyFetch;\nfunction getApiBaseUrl() {\n return process.env['GITHUB_API_URL'] || 'https://api.github.com';\n}\nexports.getApiBaseUrl = getApiBaseUrl;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0;\nconst Context = __importStar(require(\"./context\"));\nconst Utils = __importStar(require(\"./internal/utils\"));\n// octokit + plugins\nconst core_1 = require(\"@octokit/core\");\nconst plugin_rest_endpoint_methods_1 = require(\"@octokit/plugin-rest-endpoint-methods\");\nconst plugin_paginate_rest_1 = require(\"@octokit/plugin-paginate-rest\");\nexports.context = new Context.Context();\nconst baseUrl = Utils.getApiBaseUrl();\nexports.defaults = {\n baseUrl,\n request: {\n agent: Utils.getProxyAgent(baseUrl),\n fetch: Utils.getProxyFetch(baseUrl)\n }\n};\nexports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults);\n/**\n * Convience function to correctly format Octokit Options to pass into the constructor.\n *\n * @param token the repo PAT or GITHUB_TOKEN\n * @param options other options to set\n */\nfunction getOctokitOptions(token, options) {\n const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller\n // Auth\n const auth = Utils.getAuthString(token, opts);\n if (auth) {\n opts.auth = auth;\n }\n return opts;\n}\nexports.getOctokitOptions = getOctokitOptions;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;\nclass BasicCredentialHandler {\n constructor(username, password) {\n this.username = username;\n this.password = password;\n }\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BasicCredentialHandler = BasicCredentialHandler;\nclass BearerCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Bearer ${this.token}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.BearerCredentialHandler = BearerCredentialHandler;\nclass PersonalAccessTokenCredentialHandler {\n constructor(token) {\n this.token = token;\n }\n // currently implements pre-authorization\n // TODO: support preAuth = false where it hooks on 401\n prepareRequest(options) {\n if (!options.headers) {\n throw Error('The request has no headers');\n }\n options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;\n }\n // This handler cannot handle 401\n canHandleAuthentication() {\n return false;\n }\n handleAuthentication() {\n return __awaiter(this, void 0, void 0, function* () {\n throw new Error('not implemented');\n });\n }\n}\nexports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;\n//# sourceMappingURL=auth.js.map","\"use strict\";\n/* eslint-disable @typescript-eslint/no-explicit-any */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;\nconst http = __importStar(require(\"http\"));\nconst https = __importStar(require(\"https\"));\nconst pm = __importStar(require(\"./proxy\"));\nconst tunnel = __importStar(require(\"tunnel\"));\nconst undici_1 = require(\"undici\");\nvar HttpCodes;\n(function (HttpCodes) {\n HttpCodes[HttpCodes[\"OK\"] = 200] = \"OK\";\n HttpCodes[HttpCodes[\"MultipleChoices\"] = 300] = \"MultipleChoices\";\n HttpCodes[HttpCodes[\"MovedPermanently\"] = 301] = \"MovedPermanently\";\n HttpCodes[HttpCodes[\"ResourceMoved\"] = 302] = \"ResourceMoved\";\n HttpCodes[HttpCodes[\"SeeOther\"] = 303] = \"SeeOther\";\n HttpCodes[HttpCodes[\"NotModified\"] = 304] = \"NotModified\";\n HttpCodes[HttpCodes[\"UseProxy\"] = 305] = \"UseProxy\";\n HttpCodes[HttpCodes[\"SwitchProxy\"] = 306] = \"SwitchProxy\";\n HttpCodes[HttpCodes[\"TemporaryRedirect\"] = 307] = \"TemporaryRedirect\";\n HttpCodes[HttpCodes[\"PermanentRedirect\"] = 308] = \"PermanentRedirect\";\n HttpCodes[HttpCodes[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpCodes[HttpCodes[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpCodes[HttpCodes[\"PaymentRequired\"] = 402] = \"PaymentRequired\";\n HttpCodes[HttpCodes[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpCodes[HttpCodes[\"NotFound\"] = 404] = \"NotFound\";\n HttpCodes[HttpCodes[\"MethodNotAllowed\"] = 405] = \"MethodNotAllowed\";\n HttpCodes[HttpCodes[\"NotAcceptable\"] = 406] = \"NotAcceptable\";\n HttpCodes[HttpCodes[\"ProxyAuthenticationRequired\"] = 407] = \"ProxyAuthenticationRequired\";\n HttpCodes[HttpCodes[\"RequestTimeout\"] = 408] = \"RequestTimeout\";\n HttpCodes[HttpCodes[\"Conflict\"] = 409] = \"Conflict\";\n HttpCodes[HttpCodes[\"Gone\"] = 410] = \"Gone\";\n HttpCodes[HttpCodes[\"TooManyRequests\"] = 429] = \"TooManyRequests\";\n HttpCodes[HttpCodes[\"InternalServerError\"] = 500] = \"InternalServerError\";\n HttpCodes[HttpCodes[\"NotImplemented\"] = 501] = \"NotImplemented\";\n HttpCodes[HttpCodes[\"BadGateway\"] = 502] = \"BadGateway\";\n HttpCodes[HttpCodes[\"ServiceUnavailable\"] = 503] = \"ServiceUnavailable\";\n HttpCodes[HttpCodes[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));\nvar Headers;\n(function (Headers) {\n Headers[\"Accept\"] = \"accept\";\n Headers[\"ContentType\"] = \"content-type\";\n})(Headers || (exports.Headers = Headers = {}));\nvar MediaTypes;\n(function (MediaTypes) {\n MediaTypes[\"ApplicationJson\"] = \"application/json\";\n})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));\n/**\n * Returns the proxy URL, depending upon the supplied url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\nfunction getProxyUrl(serverUrl) {\n const proxyUrl = pm.getProxyUrl(new URL(serverUrl));\n return proxyUrl ? proxyUrl.href : '';\n}\nexports.getProxyUrl = getProxyUrl;\nconst HttpRedirectCodes = [\n HttpCodes.MovedPermanently,\n HttpCodes.ResourceMoved,\n HttpCodes.SeeOther,\n HttpCodes.TemporaryRedirect,\n HttpCodes.PermanentRedirect\n];\nconst HttpResponseRetryCodes = [\n HttpCodes.BadGateway,\n HttpCodes.ServiceUnavailable,\n HttpCodes.GatewayTimeout\n];\nconst RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];\nconst ExponentialBackoffCeiling = 10;\nconst ExponentialBackoffTimeSlice = 5;\nclass HttpClientError extends Error {\n constructor(message, statusCode) {\n super(message);\n this.name = 'HttpClientError';\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, HttpClientError.prototype);\n }\n}\nexports.HttpClientError = HttpClientError;\nclass HttpClientResponse {\n constructor(message) {\n this.message = message;\n }\n readBody() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n let output = Buffer.alloc(0);\n this.message.on('data', (chunk) => {\n output = Buffer.concat([output, chunk]);\n });\n this.message.on('end', () => {\n resolve(output.toString());\n });\n }));\n });\n }\n readBodyBuffer() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n const chunks = [];\n this.message.on('data', (chunk) => {\n chunks.push(chunk);\n });\n this.message.on('end', () => {\n resolve(Buffer.concat(chunks));\n });\n }));\n });\n }\n}\nexports.HttpClientResponse = HttpClientResponse;\nfunction isHttps(requestUrl) {\n const parsedUrl = new URL(requestUrl);\n return parsedUrl.protocol === 'https:';\n}\nexports.isHttps = isHttps;\nclass HttpClient {\n constructor(userAgent, handlers, requestOptions) {\n this._ignoreSslError = false;\n this._allowRedirects = true;\n this._allowRedirectDowngrade = false;\n this._maxRedirects = 50;\n this._allowRetries = false;\n this._maxRetries = 1;\n this._keepAlive = false;\n this._disposed = false;\n this.userAgent = userAgent;\n this.handlers = handlers || [];\n this.requestOptions = requestOptions;\n if (requestOptions) {\n if (requestOptions.ignoreSslError != null) {\n this._ignoreSslError = requestOptions.ignoreSslError;\n }\n this._socketTimeout = requestOptions.socketTimeout;\n if (requestOptions.allowRedirects != null) {\n this._allowRedirects = requestOptions.allowRedirects;\n }\n if (requestOptions.allowRedirectDowngrade != null) {\n this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;\n }\n if (requestOptions.maxRedirects != null) {\n this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);\n }\n if (requestOptions.keepAlive != null) {\n this._keepAlive = requestOptions.keepAlive;\n }\n if (requestOptions.allowRetries != null) {\n this._allowRetries = requestOptions.allowRetries;\n }\n if (requestOptions.maxRetries != null) {\n this._maxRetries = requestOptions.maxRetries;\n }\n }\n }\n options(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});\n });\n }\n get(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('GET', requestUrl, null, additionalHeaders || {});\n });\n }\n del(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('DELETE', requestUrl, null, additionalHeaders || {});\n });\n }\n post(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('POST', requestUrl, data, additionalHeaders || {});\n });\n }\n patch(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PATCH', requestUrl, data, additionalHeaders || {});\n });\n }\n put(requestUrl, data, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('PUT', requestUrl, data, additionalHeaders || {});\n });\n }\n head(requestUrl, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request('HEAD', requestUrl, null, additionalHeaders || {});\n });\n }\n sendStream(verb, requestUrl, stream, additionalHeaders) {\n return __awaiter(this, void 0, void 0, function* () {\n return this.request(verb, requestUrl, stream, additionalHeaders);\n });\n }\n /**\n * Gets a typed object from an endpoint\n * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise\n */\n getJson(requestUrl, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n const res = yield this.get(requestUrl, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n postJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.post(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n putJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.put(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n patchJson(requestUrl, obj, additionalHeaders = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const data = JSON.stringify(obj, null, 2);\n additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);\n additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);\n const res = yield this.patch(requestUrl, data, additionalHeaders);\n return this._processResponse(res, this.requestOptions);\n });\n }\n /**\n * Makes a raw http request.\n * All other methods such as get, post, patch, and request ultimately call this.\n * Prefer get, del, post and patch\n */\n request(verb, requestUrl, data, headers) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._disposed) {\n throw new Error('Client has already been disposed.');\n }\n const parsedUrl = new URL(requestUrl);\n let info = this._prepareRequest(verb, parsedUrl, headers);\n // Only perform retries on reads since writes may not be idempotent.\n const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)\n ? this._maxRetries + 1\n : 1;\n let numTries = 0;\n let response;\n do {\n response = yield this.requestRaw(info, data);\n // Check if it's an authentication challenge\n if (response &&\n response.message &&\n response.message.statusCode === HttpCodes.Unauthorized) {\n let authenticationHandler;\n for (const handler of this.handlers) {\n if (handler.canHandleAuthentication(response)) {\n authenticationHandler = handler;\n break;\n }\n }\n if (authenticationHandler) {\n return authenticationHandler.handleAuthentication(this, info, data);\n }\n else {\n // We have received an unauthorized response but have no handlers to handle it.\n // Let the response return to the caller.\n return response;\n }\n }\n let redirectsRemaining = this._maxRedirects;\n while (response.message.statusCode &&\n HttpRedirectCodes.includes(response.message.statusCode) &&\n this._allowRedirects &&\n redirectsRemaining > 0) {\n const redirectUrl = response.message.headers['location'];\n if (!redirectUrl) {\n // if there's no location to redirect to, we won't\n break;\n }\n const parsedRedirectUrl = new URL(redirectUrl);\n if (parsedUrl.protocol === 'https:' &&\n parsedUrl.protocol !== parsedRedirectUrl.protocol &&\n !this._allowRedirectDowngrade) {\n throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');\n }\n // we need to finish reading the response before reassigning response\n // which will leak the open socket.\n yield response.readBody();\n // strip authorization header if redirected to a different hostname\n if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {\n for (const header in headers) {\n // header names are case insensitive\n if (header.toLowerCase() === 'authorization') {\n delete headers[header];\n }\n }\n }\n // let's make the request with the new redirectUrl\n info = this._prepareRequest(verb, parsedRedirectUrl, headers);\n response = yield this.requestRaw(info, data);\n redirectsRemaining--;\n }\n if (!response.message.statusCode ||\n !HttpResponseRetryCodes.includes(response.message.statusCode)) {\n // If not a retry code, return immediately instead of retrying\n return response;\n }\n numTries += 1;\n if (numTries < maxTries) {\n yield response.readBody();\n yield this._performExponentialBackoff(numTries);\n }\n } while (numTries < maxTries);\n return response;\n });\n }\n /**\n * Needs to be called if keepAlive is set to true in request options.\n */\n dispose() {\n if (this._agent) {\n this._agent.destroy();\n }\n this._disposed = true;\n }\n /**\n * Raw request.\n * @param info\n * @param data\n */\n requestRaw(info, data) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n function callbackForResult(err, res) {\n if (err) {\n reject(err);\n }\n else if (!res) {\n // If `err` is not passed, then `res` must be passed.\n reject(new Error('Unknown error'));\n }\n else {\n resolve(res);\n }\n }\n this.requestRawWithCallback(info, data, callbackForResult);\n });\n });\n }\n /**\n * Raw request with callback.\n * @param info\n * @param data\n * @param onResult\n */\n requestRawWithCallback(info, data, onResult) {\n if (typeof data === 'string') {\n if (!info.options.headers) {\n info.options.headers = {};\n }\n info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');\n }\n let callbackCalled = false;\n function handleResult(err, res) {\n if (!callbackCalled) {\n callbackCalled = true;\n onResult(err, res);\n }\n }\n const req = info.httpModule.request(info.options, (msg) => {\n const res = new HttpClientResponse(msg);\n handleResult(undefined, res);\n });\n let socket;\n req.on('socket', sock => {\n socket = sock;\n });\n // If we ever get disconnected, we want the socket to timeout eventually\n req.setTimeout(this._socketTimeout || 3 * 60000, () => {\n if (socket) {\n socket.end();\n }\n handleResult(new Error(`Request timeout: ${info.options.path}`));\n });\n req.on('error', function (err) {\n // err has statusCode property\n // res should have headers\n handleResult(err);\n });\n if (data && typeof data === 'string') {\n req.write(data, 'utf8');\n }\n if (data && typeof data !== 'string') {\n data.on('close', function () {\n req.end();\n });\n data.pipe(req);\n }\n else {\n req.end();\n }\n }\n /**\n * Gets an http agent. This function is useful when you need an http agent that handles\n * routing through a proxy server - depending upon the url and proxy environment variables.\n * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com\n */\n getAgent(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n return this._getAgent(parsedUrl);\n }\n getAgentDispatcher(serverUrl) {\n const parsedUrl = new URL(serverUrl);\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (!useProxy) {\n return;\n }\n return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);\n }\n _prepareRequest(method, requestUrl, headers) {\n const info = {};\n info.parsedUrl = requestUrl;\n const usingSsl = info.parsedUrl.protocol === 'https:';\n info.httpModule = usingSsl ? https : http;\n const defaultPort = usingSsl ? 443 : 80;\n info.options = {};\n info.options.host = info.parsedUrl.hostname;\n info.options.port = info.parsedUrl.port\n ? parseInt(info.parsedUrl.port)\n : defaultPort;\n info.options.path =\n (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');\n info.options.method = method;\n info.options.headers = this._mergeHeaders(headers);\n if (this.userAgent != null) {\n info.options.headers['user-agent'] = this.userAgent;\n }\n info.options.agent = this._getAgent(info.parsedUrl);\n // gives handlers an opportunity to participate\n if (this.handlers) {\n for (const handler of this.handlers) {\n handler.prepareRequest(info.options);\n }\n }\n return info;\n }\n _mergeHeaders(headers) {\n if (this.requestOptions && this.requestOptions.headers) {\n return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));\n }\n return lowercaseKeys(headers || {});\n }\n _getExistingOrDefaultHeader(additionalHeaders, header, _default) {\n let clientHeader;\n if (this.requestOptions && this.requestOptions.headers) {\n clientHeader = lowercaseKeys(this.requestOptions.headers)[header];\n }\n return additionalHeaders[header] || clientHeader || _default;\n }\n _getAgent(parsedUrl) {\n let agent;\n const proxyUrl = pm.getProxyUrl(parsedUrl);\n const useProxy = proxyUrl && proxyUrl.hostname;\n if (this._keepAlive && useProxy) {\n agent = this._proxyAgent;\n }\n if (!useProxy) {\n agent = this._agent;\n }\n // if agent is already assigned use that agent.\n if (agent) {\n return agent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n let maxSockets = 100;\n if (this.requestOptions) {\n maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;\n }\n // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.\n if (proxyUrl && proxyUrl.hostname) {\n const agentOptions = {\n maxSockets,\n keepAlive: this._keepAlive,\n proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {\n proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`\n })), { host: proxyUrl.hostname, port: proxyUrl.port })\n };\n let tunnelAgent;\n const overHttps = proxyUrl.protocol === 'https:';\n if (usingSsl) {\n tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;\n }\n else {\n tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;\n }\n agent = tunnelAgent(agentOptions);\n this._proxyAgent = agent;\n }\n // if tunneling agent isn't assigned create a new agent\n if (!agent) {\n const options = { keepAlive: this._keepAlive, maxSockets };\n agent = usingSsl ? new https.Agent(options) : new http.Agent(options);\n this._agent = agent;\n }\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n agent.options = Object.assign(agent.options || {}, {\n rejectUnauthorized: false\n });\n }\n return agent;\n }\n _getProxyAgentDispatcher(parsedUrl, proxyUrl) {\n let proxyAgent;\n if (this._keepAlive) {\n proxyAgent = this._proxyAgentDispatcher;\n }\n // if agent is already assigned use that agent.\n if (proxyAgent) {\n return proxyAgent;\n }\n const usingSsl = parsedUrl.protocol === 'https:';\n proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {\n token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}`\n })));\n this._proxyAgentDispatcher = proxyAgent;\n if (usingSsl && this._ignoreSslError) {\n // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process\n // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options\n // we have to cast it to any and change it directly\n proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {\n rejectUnauthorized: false\n });\n }\n return proxyAgent;\n }\n _performExponentialBackoff(retryNumber) {\n return __awaiter(this, void 0, void 0, function* () {\n retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);\n const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);\n return new Promise(resolve => setTimeout(() => resolve(), ms));\n });\n }\n _processResponse(res, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const statusCode = res.message.statusCode || 0;\n const response = {\n statusCode,\n result: null,\n headers: {}\n };\n // not found leads to null obj returned\n if (statusCode === HttpCodes.NotFound) {\n resolve(response);\n }\n // get the result from the body\n function dateTimeDeserializer(key, value) {\n if (typeof value === 'string') {\n const a = new Date(value);\n if (!isNaN(a.valueOf())) {\n return a;\n }\n }\n return value;\n }\n let obj;\n let contents;\n try {\n contents = yield res.readBody();\n if (contents && contents.length > 0) {\n if (options && options.deserializeDates) {\n obj = JSON.parse(contents, dateTimeDeserializer);\n }\n else {\n obj = JSON.parse(contents);\n }\n response.result = obj;\n }\n response.headers = res.message.headers;\n }\n catch (err) {\n // Invalid resource (contents not json); leaving result obj null\n }\n // note that 3xx redirects are handled by the http layer.\n if (statusCode > 299) {\n let msg;\n // if exception/error in body, attempt to get better error\n if (obj && obj.message) {\n msg = obj.message;\n }\n else if (contents && contents.length > 0) {\n // it may be the case that the exception is in the body message as string\n msg = contents;\n }\n else {\n msg = `Failed request: (${statusCode})`;\n }\n const err = new HttpClientError(msg, statusCode);\n err.result = response.result;\n reject(err);\n }\n else {\n resolve(response);\n }\n }));\n });\n }\n}\nexports.HttpClient = HttpClient;\nconst lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkBypass = exports.getProxyUrl = void 0;\nfunction getProxyUrl(reqUrl) {\n const usingSsl = reqUrl.protocol === 'https:';\n if (checkBypass(reqUrl)) {\n return undefined;\n }\n const proxyVar = (() => {\n if (usingSsl) {\n return process.env['https_proxy'] || process.env['HTTPS_PROXY'];\n }\n else {\n return process.env['http_proxy'] || process.env['HTTP_PROXY'];\n }\n })();\n if (proxyVar) {\n try {\n return new DecodedURL(proxyVar);\n }\n catch (_a) {\n if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))\n return new DecodedURL(`http://${proxyVar}`);\n }\n }\n else {\n return undefined;\n }\n}\nexports.getProxyUrl = getProxyUrl;\nfunction checkBypass(reqUrl) {\n if (!reqUrl.hostname) {\n return false;\n }\n const reqHost = reqUrl.hostname;\n if (isLoopbackAddress(reqHost)) {\n return true;\n }\n const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';\n if (!noProxy) {\n return false;\n }\n // Determine the request port\n let reqPort;\n if (reqUrl.port) {\n reqPort = Number(reqUrl.port);\n }\n else if (reqUrl.protocol === 'http:') {\n reqPort = 80;\n }\n else if (reqUrl.protocol === 'https:') {\n reqPort = 443;\n }\n // Format the request hostname and hostname with port\n const upperReqHosts = [reqUrl.hostname.toUpperCase()];\n if (typeof reqPort === 'number') {\n upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);\n }\n // Compare request host against noproxy\n for (const upperNoProxyItem of noProxy\n .split(',')\n .map(x => x.trim().toUpperCase())\n .filter(x => x)) {\n if (upperNoProxyItem === '*' ||\n upperReqHosts.some(x => x === upperNoProxyItem ||\n x.endsWith(`.${upperNoProxyItem}`) ||\n (upperNoProxyItem.startsWith('.') &&\n x.endsWith(`${upperNoProxyItem}`)))) {\n return true;\n }\n }\n return false;\n}\nexports.checkBypass = checkBypass;\nfunction isLoopbackAddress(host) {\n const hostLower = host.toLowerCase();\n return (hostLower === 'localhost' ||\n hostLower.startsWith('127.') ||\n hostLower.startsWith('[::1]') ||\n hostLower.startsWith('[0:0:0:0:0:0:0:1]'));\n}\nclass DecodedURL extends URL {\n constructor(url, base) {\n super(url, base);\n this._decodedUsername = decodeURIComponent(super.username);\n this._decodedPassword = decodeURIComponent(super.password);\n }\n get username() {\n return this._decodedUsername;\n }\n get password() {\n return this._decodedPassword;\n }\n}\n//# sourceMappingURL=proxy.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0;\nconst fs = __importStar(require(\"fs\"));\nconst path = __importStar(require(\"path\"));\n_a = fs.promises\n// export const {open} = 'fs'\n, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;\n// export const {open} = 'fs'\nexports.IS_WINDOWS = process.platform === 'win32';\n// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691\nexports.UV_FS_O_EXLOCK = 0x10000000;\nexports.READONLY = fs.constants.O_RDONLY;\nfunction exists(fsPath) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n yield exports.stat(fsPath);\n }\n catch (err) {\n if (err.code === 'ENOENT') {\n return false;\n }\n throw err;\n }\n return true;\n });\n}\nexports.exists = exists;\nfunction isDirectory(fsPath, useStat = false) {\n return __awaiter(this, void 0, void 0, function* () {\n const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);\n return stats.isDirectory();\n });\n}\nexports.isDirectory = isDirectory;\n/**\n * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:\n * \\, \\hello, \\\\hello\\share, C:, and C:\\hello (and corresponding alternate separator cases).\n */\nfunction isRooted(p) {\n p = normalizeSeparators(p);\n if (!p) {\n throw new Error('isRooted() parameter \"p\" cannot be empty');\n }\n if (exports.IS_WINDOWS) {\n return (p.startsWith('\\\\') || /^[A-Z]:/i.test(p) // e.g. \\ or \\hello or \\\\hello\n ); // e.g. C: or C:\\hello\n }\n return p.startsWith('/');\n}\nexports.isRooted = isRooted;\n/**\n * Best effort attempt to determine whether a file exists and is executable.\n * @param filePath file path to check\n * @param extensions additional file extensions to try\n * @return if file exists and is executable, returns the file path. otherwise empty string.\n */\nfunction tryGetExecutablePath(filePath, extensions) {\n return __awaiter(this, void 0, void 0, function* () {\n let stats = undefined;\n try {\n // test file exists\n stats = yield exports.stat(filePath);\n }\n catch (err) {\n if (err.code !== 'ENOENT') {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);\n }\n }\n if (stats && stats.isFile()) {\n if (exports.IS_WINDOWS) {\n // on Windows, test for valid extension\n const upperExt = path.extname(filePath).toUpperCase();\n if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {\n return filePath;\n }\n }\n else {\n if (isUnixExecutable(stats)) {\n return filePath;\n }\n }\n }\n // try each extension\n const originalFilePath = filePath;\n for (const extension of extensions) {\n filePath = originalFilePath + extension;\n stats = undefined;\n try {\n stats = yield exports.stat(filePath);\n }\n catch (err) {\n if (err.code !== 'ENOENT') {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);\n }\n }\n if (stats && stats.isFile()) {\n if (exports.IS_WINDOWS) {\n // preserve the case of the actual file (since an extension was appended)\n try {\n const directory = path.dirname(filePath);\n const upperName = path.basename(filePath).toUpperCase();\n for (const actualName of yield exports.readdir(directory)) {\n if (upperName === actualName.toUpperCase()) {\n filePath = path.join(directory, actualName);\n break;\n }\n }\n }\n catch (err) {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);\n }\n return filePath;\n }\n else {\n if (isUnixExecutable(stats)) {\n return filePath;\n }\n }\n }\n }\n return '';\n });\n}\nexports.tryGetExecutablePath = tryGetExecutablePath;\nfunction normalizeSeparators(p) {\n p = p || '';\n if (exports.IS_WINDOWS) {\n // convert slashes on Windows\n p = p.replace(/\\//g, '\\\\');\n // remove redundant slashes\n return p.replace(/\\\\\\\\+/g, '\\\\');\n }\n // remove redundant slashes\n return p.replace(/\\/\\/+/g, '/');\n}\n// on Mac/Linux, test the execute bit\n// R W X R W X R W X\n// 256 128 64 32 16 8 4 2 1\nfunction isUnixExecutable(stats) {\n return ((stats.mode & 1) > 0 ||\n ((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||\n ((stats.mode & 64) > 0 && stats.uid === process.getuid()));\n}\n// Get the path of cmd.exe in windows\nfunction getCmdPath() {\n var _a;\n return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;\n}\nexports.getCmdPath = getCmdPath;\n//# sourceMappingURL=io-util.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0;\nconst assert_1 = require(\"assert\");\nconst path = __importStar(require(\"path\"));\nconst ioUtil = __importStar(require(\"./io-util\"));\n/**\n * Copies a file or folder.\n * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js\n *\n * @param source source path\n * @param dest destination path\n * @param options optional. See CopyOptions.\n */\nfunction cp(source, dest, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const { force, recursive, copySourceDirectory } = readCopyOptions(options);\n const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;\n // Dest is an existing file, but not forcing\n if (destStat && destStat.isFile() && !force) {\n return;\n }\n // If dest is an existing directory, should copy inside.\n const newDest = destStat && destStat.isDirectory() && copySourceDirectory\n ? path.join(dest, path.basename(source))\n : dest;\n if (!(yield ioUtil.exists(source))) {\n throw new Error(`no such file or directory: ${source}`);\n }\n const sourceStat = yield ioUtil.stat(source);\n if (sourceStat.isDirectory()) {\n if (!recursive) {\n throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);\n }\n else {\n yield cpDirRecursive(source, newDest, 0, force);\n }\n }\n else {\n if (path.relative(source, newDest) === '') {\n // a file cannot be copied to itself\n throw new Error(`'${newDest}' and '${source}' are the same file`);\n }\n yield copyFile(source, newDest, force);\n }\n });\n}\nexports.cp = cp;\n/**\n * Moves a path.\n *\n * @param source source path\n * @param dest destination path\n * @param options optional. See MoveOptions.\n */\nfunction mv(source, dest, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (yield ioUtil.exists(dest)) {\n let destExists = true;\n if (yield ioUtil.isDirectory(dest)) {\n // If dest is directory copy src into dest\n dest = path.join(dest, path.basename(source));\n destExists = yield ioUtil.exists(dest);\n }\n if (destExists) {\n if (options.force == null || options.force) {\n yield rmRF(dest);\n }\n else {\n throw new Error('Destination already exists');\n }\n }\n }\n yield mkdirP(path.dirname(dest));\n yield ioUtil.rename(source, dest);\n });\n}\nexports.mv = mv;\n/**\n * Remove a path recursively with force\n *\n * @param inputPath path to remove\n */\nfunction rmRF(inputPath) {\n return __awaiter(this, void 0, void 0, function* () {\n if (ioUtil.IS_WINDOWS) {\n // Check for invalid characters\n // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file\n if (/[*\"<>|]/.test(inputPath)) {\n throw new Error('File path must not contain `*`, `\"`, `<`, `>` or `|` on Windows');\n }\n }\n try {\n // note if path does not exist, error is silent\n yield ioUtil.rm(inputPath, {\n force: true,\n maxRetries: 3,\n recursive: true,\n retryDelay: 300\n });\n }\n catch (err) {\n throw new Error(`File was unable to be removed ${err}`);\n }\n });\n}\nexports.rmRF = rmRF;\n/**\n * Make a directory. Creates the full path with folders in between\n * Will throw if it fails\n *\n * @param fsPath path to create\n * @returns Promise\n */\nfunction mkdirP(fsPath) {\n return __awaiter(this, void 0, void 0, function* () {\n assert_1.ok(fsPath, 'a path argument must be provided');\n yield ioUtil.mkdir(fsPath, { recursive: true });\n });\n}\nexports.mkdirP = mkdirP;\n/**\n * Returns path of a tool had the tool actually been invoked. Resolves via paths.\n * If you check and the tool does not exist, it will throw.\n *\n * @param tool name of the tool\n * @param check whether to check if tool exists\n * @returns Promise path to tool\n */\nfunction which(tool, check) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!tool) {\n throw new Error(\"parameter 'tool' is required\");\n }\n // recursive when check=true\n if (check) {\n const result = yield which(tool, false);\n if (!result) {\n if (ioUtil.IS_WINDOWS) {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);\n }\n else {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);\n }\n }\n return result;\n }\n const matches = yield findInPath(tool);\n if (matches && matches.length > 0) {\n return matches[0];\n }\n return '';\n });\n}\nexports.which = which;\n/**\n * Returns a list of all occurrences of the given tool on the system path.\n *\n * @returns Promise the paths of the tool\n */\nfunction findInPath(tool) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!tool) {\n throw new Error(\"parameter 'tool' is required\");\n }\n // build the list of extensions to try\n const extensions = [];\n if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) {\n for (const extension of process.env['PATHEXT'].split(path.delimiter)) {\n if (extension) {\n extensions.push(extension);\n }\n }\n }\n // if it's rooted, return it if exists. otherwise return empty.\n if (ioUtil.isRooted(tool)) {\n const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);\n if (filePath) {\n return [filePath];\n }\n return [];\n }\n // if any path separators, return empty\n if (tool.includes(path.sep)) {\n return [];\n }\n // build the list of directories\n //\n // Note, technically \"where\" checks the current directory on Windows. From a toolkit perspective,\n // it feels like we should not do this. Checking the current directory seems like more of a use\n // case of a shell, and the which() function exposed by the toolkit should strive for consistency\n // across platforms.\n const directories = [];\n if (process.env.PATH) {\n for (const p of process.env.PATH.split(path.delimiter)) {\n if (p) {\n directories.push(p);\n }\n }\n }\n // find all matches\n const matches = [];\n for (const directory of directories) {\n const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions);\n if (filePath) {\n matches.push(filePath);\n }\n }\n return matches;\n });\n}\nexports.findInPath = findInPath;\nfunction readCopyOptions(options) {\n const force = options.force == null ? true : options.force;\n const recursive = Boolean(options.recursive);\n const copySourceDirectory = options.copySourceDirectory == null\n ? true\n : Boolean(options.copySourceDirectory);\n return { force, recursive, copySourceDirectory };\n}\nfunction cpDirRecursive(sourceDir, destDir, currentDepth, force) {\n return __awaiter(this, void 0, void 0, function* () {\n // Ensure there is not a run away recursive copy\n if (currentDepth >= 255)\n return;\n currentDepth++;\n yield mkdirP(destDir);\n const files = yield ioUtil.readdir(sourceDir);\n for (const fileName of files) {\n const srcFile = `${sourceDir}/${fileName}`;\n const destFile = `${destDir}/${fileName}`;\n const srcFileStat = yield ioUtil.lstat(srcFile);\n if (srcFileStat.isDirectory()) {\n // Recurse\n yield cpDirRecursive(srcFile, destFile, currentDepth, force);\n }\n else {\n yield copyFile(srcFile, destFile, force);\n }\n }\n // Change the mode for the newly created directory\n yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);\n });\n}\n// Buffered file copy\nfunction copyFile(srcFile, destFile, force) {\n return __awaiter(this, void 0, void 0, function* () {\n if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {\n // unlink/re-link it\n try {\n yield ioUtil.lstat(destFile);\n yield ioUtil.unlink(destFile);\n }\n catch (e) {\n // Try to override file permission\n if (e.code === 'EPERM') {\n yield ioUtil.chmod(destFile, '0666');\n yield ioUtil.unlink(destFile);\n }\n // other errors = it doesn't exist, no work to do\n }\n // Copy over symlink\n const symlinkFull = yield ioUtil.readlink(srcFile);\n yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);\n }\n else if (!(yield ioUtil.exists(destFile)) || force) {\n yield ioUtil.copyFile(srcFile, destFile);\n }\n });\n}\n//# sourceMappingURL=io.js.map","'use strict';\n\nconst ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\toverline: [53, 55],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\n\t\t\t// Bright color\n\t\t\tblackBright: [90, 39],\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Alias bright black as gray (and grey)\n\tstyles.color.gray = styles.color.blackBright;\n\tstyles.bgColor.bgGray = styles.bgColor.bgBlackBright;\n\tstyles.color.grey = styles.color.blackBright;\n\tstyles.bgColor.bgGrey = styles.bgColor.bgBlackBright;\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue: (red, green, blue) => {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16 +\n\t\t\t\t\t(36 * Math.round(red / 255 * 5)) +\n\t\t\t\t\t(6 * Math.round(green / 255 * 5)) +\n\t\t\t\t\tMath.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue: hex => {\n\t\t\t\tconst matches = /(?[a-f\\d]{6}|[a-f\\d]{3})/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet {colorString} = matches.groups;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = colorString.split('').map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false\n\t\t}\n\t});\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n","'use strict';\n\nconst UPPERCASE = /[\\p{Lu}]/u;\nconst LOWERCASE = /[\\p{Ll}]/u;\nconst LEADING_CAPITAL = /^[\\p{Lu}](?![\\p{Lu}])/gu;\nconst IDENTIFIER = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst SEPARATORS = /[_.\\- ]+/;\n\nconst LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);\nconst SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');\nconst NUMBERS_AND_IDENTIFIER = new RegExp('\\\\d+' + IDENTIFIER.source, 'gu');\n\nconst preserveCamelCase = (string, toLowerCase, toUpperCase) => {\n\tlet isLastCharLower = false;\n\tlet isLastCharUpper = false;\n\tlet isLastLastCharUpper = false;\n\n\tfor (let i = 0; i < string.length; i++) {\n\t\tconst character = string[i];\n\n\t\tif (isLastCharLower && UPPERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i) + '-' + string.slice(i);\n\t\t\tisLastCharLower = false;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = true;\n\t\t\ti++;\n\t\t} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i - 1) + '-' + string.slice(i - 1);\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = false;\n\t\t\tisLastCharLower = true;\n\t\t} else {\n\t\t\tisLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;\n\t\t}\n\t}\n\n\treturn string;\n};\n\nconst preserveConsecutiveUppercase = (input, toLowerCase) => {\n\tLEADING_CAPITAL.lastIndex = 0;\n\n\treturn input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1));\n};\n\nconst postProcess = (input, toUpperCase) => {\n\tSEPARATORS_AND_IDENTIFIER.lastIndex = 0;\n\tNUMBERS_AND_IDENTIFIER.lastIndex = 0;\n\n\treturn input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier))\n\t\t.replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));\n};\n\nconst camelCase = (input, options) => {\n\tif (!(typeof input === 'string' || Array.isArray(input))) {\n\t\tthrow new TypeError('Expected the input to be `string | string[]`');\n\t}\n\n\toptions = {\n\t\tpascalCase: false,\n\t\tpreserveConsecutiveUppercase: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(input)) {\n\t\tinput = input.map(x => x.trim())\n\t\t\t.filter(x => x.length)\n\t\t\t.join('-');\n\t} else {\n\t\tinput = input.trim();\n\t}\n\n\tif (input.length === 0) {\n\t\treturn '';\n\t}\n\n\tconst toLowerCase = options.locale === false ?\n\t\tstring => string.toLowerCase() :\n\t\tstring => string.toLocaleLowerCase(options.locale);\n\tconst toUpperCase = options.locale === false ?\n\t\tstring => string.toUpperCase() :\n\t\tstring => string.toLocaleUpperCase(options.locale);\n\n\tif (input.length === 1) {\n\t\treturn options.pascalCase ? toUpperCase(input) : toLowerCase(input);\n\t}\n\n\tconst hasUpperCase = input !== toLowerCase(input);\n\n\tif (hasUpperCase) {\n\t\tinput = preserveCamelCase(input, toLowerCase, toUpperCase);\n\t}\n\n\tinput = input.replace(LEADING_SEPARATORS, '');\n\n\tif (options.preserveConsecutiveUppercase) {\n\t\tinput = preserveConsecutiveUppercase(input, toLowerCase);\n\t} else {\n\t\tinput = toLowerCase(input);\n\t}\n\n\tif (options.pascalCase) {\n\t\tinput = toUpperCase(input.charAt(0)) + input.slice(1);\n\t}\n\n\treturn postProcess(input, toUpperCase);\n};\n\nmodule.exports = camelCase;\n// TODO: Remove this for the next major release\nmodule.exports.default = camelCase;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"MAX\", {\n enumerable: true,\n get: function () {\n return _max.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v1ToV6\", {\n enumerable: true,\n get: function () {\n return _v1ToV.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"v6\", {\n enumerable: true,\n get: function () {\n return _v5.default;\n }\n});\nObject.defineProperty(exports, \"v6ToV1\", {\n enumerable: true,\n get: function () {\n return _v6ToV.default;\n }\n});\nObject.defineProperty(exports, \"v7\", {\n enumerable: true,\n get: function () {\n return _v6.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nvar _max = _interopRequireDefault(require(\"./max.js\"));\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\nvar _v5 = _interopRequireDefault(require(\"./v6.js\"));\nvar _v6ToV = _interopRequireDefault(require(\"./v6ToV1.js\"));\nvar _v6 = _interopRequireDefault(require(\"./v7.js\"));\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nvar _version = _interopRequireDefault(require(\"./version.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('md5').update(bytes).digest();\n}\nvar _default = exports.default = md5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nvar _default = exports.default = {\n randomUUID: _nodeCrypto.default.randomUUID\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = '00000000-0000-0000-0000-000000000000';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n const arr = new Uint8Array(16);\n\n // Parse ########-....-....-....-............\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff;\n\n // Parse ........-####-....-....-............\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff;\n\n // Parse ........-....-####-....-............\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff;\n\n // Parse ........-....-....-####-............\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff;\n\n // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\nvar _default = exports.default = parse;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\nlet poolPtr = rnds8Pool.length;\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _nodeCrypto.default.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('sha1').update(bytes).digest();\n}\nvar _default = exports.default = sha1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nvar _default = exports.default = stringify;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nlet _nodeId;\nlet _clockseq;\n\n// Previous uuid creation time\nlet _lastMSecs = 0;\nlet _lastNSecs = 0;\n\n// See https://github.com/uuidjs/uuid for API details\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node;\n let clockseq = options.clockseq;\n\n // v1 only: Use cached `node` and `clockseq` values\n if (!options._v6) {\n if (!node) {\n node = _nodeId;\n }\n if (clockseq == null) {\n clockseq = _clockseq;\n }\n }\n\n // Handle cases where we need entropy. We do this lazily to minimize issues\n // related to insufficient system entropy. See #189\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n // Randomize node\n if (node == null) {\n node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n\n // v1 only: cache node value for reuse\n if (!_nodeId && !options._v6) {\n // per RFC4122 4.5: Set MAC multicast bit (v1 only)\n node[0] |= 0x01; // Set multicast bit\n\n _nodeId = node;\n }\n }\n\n // Randomize clockseq\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n if (_clockseq === undefined && !options._v6) {\n _clockseq = clockseq;\n }\n }\n }\n\n // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is\n // handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n let msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v1ToV6;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v1 UUID to a v6 UUID\n *\n * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6\n * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v1ToV6(uuid) {\n const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v6Bytes = _v1ToV6(v1Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes;\n}\n\n// Do the field transformation needed for v1 -> v6\nfunction _v1ToV6(v1Bytes, randomize = false) {\n return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = exports.default = v3;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\nvar _stringify = require(\"./stringify.js\");\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n return bytes;\n}\nconst DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nconst URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n }\n\n // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n }\n\n // Function#name is not settable on some platforms (#270)\n try {\n generateUUID.name = name;\n } catch (err) {}\n\n // For CommonJS default export support\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _native = _interopRequireDefault(require(\"./native.js\"));\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || _rng.default)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(rnds);\n}\nvar _default = exports.default = v4;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = exports.default = v5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6;\nvar _stringify = require(\"./stringify.js\");\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n *\n * @param {object} options\n * @param {Uint8Array=} buf\n * @param {number=} offset\n * @returns\n */\nfunction v6(options = {}, buf, offset = 0) {\n // v6 is v1 with different field layout, so we start with a v1 UUID, albeit\n // with slightly different behavior around how the clock_seq and node fields\n // are randomized, which is why we call v1 with _v6: true.\n let bytes = (0, _v.default)({\n ...options,\n _v6: true\n }, new Uint8Array(16));\n\n // Reorder the fields to v6 layout.\n bytes = (0, _v1ToV.default)(bytes);\n\n // Return as a byte array if requested\n if (buf) {\n for (let i = 0; i < 16; i++) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6ToV1;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v6 UUID to a v1 UUID\n *\n * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6\n * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v6ToV1(uuid) {\n const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v1Bytes = _v6ToV1(v6Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes;\n}\n\n// Do the field transformation needed for v6 -> v1\nfunction _v6ToV1(v6Bytes) {\n return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * UUID V7 - Unix Epoch time-based UUID\n *\n * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This\n * implementation of V7 is based on the accepted, though not yet approved,\n * revisions.\n *\n * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique\n * IDentifiers (UUIDs)\n\n *\n * Sample V7 value:\n * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value\n *\n * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref:\n * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1\n *\n * 0 1 2 3 0 1 2 3 4 5 6\n * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms | ver | seq_hi |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * |var| seq_low | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n *\n * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit\n * seq_low, and randomly initialized upon timestamp change. 31 bit counter size\n * was selected as any bitwise operations in node are done as _signed_ 32 bit\n * ints. we exclude the sign bit.\n */\n\nlet _seqLow = null;\nlet _seqHigh = null;\nlet _msecs = 0;\nfunction v7(options, buf, offset) {\n options = options || {};\n\n // initialize buffer and pointer\n let i = buf && offset || 0;\n const b = buf || new Uint8Array(16);\n\n // rnds is Uint8Array(16) filled with random bytes\n const rnds = options.random || (options.rng || _rng.default)();\n\n // milliseconds since unix epoch, 1970-01-01 00:00\n const msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // seq is user provided 31 bit counter\n let seq = options.seq !== undefined ? options.seq : null;\n\n // initialize local seq high/low parts\n let seqHigh = _seqHigh;\n let seqLow = _seqLow;\n\n // check if clock has advanced and user has not provided msecs\n if (msecs > _msecs && options.msecs === undefined) {\n _msecs = msecs;\n\n // unless user provided seq, reset seq parts\n if (seq !== null) {\n seqHigh = null;\n seqLow = null;\n }\n }\n\n // if we have a user provided seq\n if (seq !== null) {\n // trim provided seq to 31 bits of value, avoiding overflow\n if (seq > 0x7fffffff) {\n seq = 0x7fffffff;\n }\n\n // split provided seq into high/low parts\n seqHigh = seq >>> 19 & 0xfff;\n seqLow = seq & 0x7ffff;\n }\n\n // randomly initialize seq\n if (seqHigh === null || seqLow === null) {\n seqHigh = rnds[6] & 0x7f;\n seqHigh = seqHigh << 8 | rnds[7];\n seqLow = rnds[8] & 0x3f; // pad for var\n seqLow = seqLow << 8 | rnds[9];\n seqLow = seqLow << 5 | rnds[10] >>> 3;\n }\n\n // increment seq if within msecs window\n if (msecs + 10000 > _msecs && seq === null) {\n if (++seqLow > 0x7ffff) {\n seqLow = 0;\n if (++seqHigh > 0xfff) {\n seqHigh = 0;\n\n // increment internal _msecs. this allows us to continue incrementing\n // while staying monotonic. Note, once we hit 10k milliseconds beyond system\n // clock, we will reset breaking monotonicity (after (2^31)*10000 generations)\n _msecs++;\n }\n }\n } else {\n // resetting; we have advanced more than\n // 10k milliseconds beyond system clock\n _msecs = msecs;\n }\n _seqHigh = seqHigh;\n _seqLow = seqLow;\n\n // [bytes 0-5] 48 bits of local timestamp\n b[i++] = _msecs / 0x10000000000 & 0xff;\n b[i++] = _msecs / 0x100000000 & 0xff;\n b[i++] = _msecs / 0x1000000 & 0xff;\n b[i++] = _msecs / 0x10000 & 0xff;\n b[i++] = _msecs / 0x100 & 0xff;\n b[i++] = _msecs & 0xff;\n\n // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi\n b[i++] = seqHigh >>> 4 & 0x0f | 0x70;\n\n // [byte 7] remaining 8 bits of seq_hi\n b[i++] = seqHigh & 0xff;\n\n // [byte 8] - variant (2 bits), first 6 bits seq_low\n b[i++] = seqLow >>> 13 & 0x3f | 0x80;\n\n // [byte 9] 8 bits seq_low\n b[i++] = seqLow >>> 5 & 0xff;\n\n // [byte 10] remaining 5 bits seq_low, 3 bits random\n b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07;\n\n // [bytes 11-15] always random\n b[i++] = rnds[11];\n b[i++] = rnds[12];\n b[i++] = rnds[13];\n b[i++] = rnds[14];\n b[i++] = rnds[15];\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v7;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\nvar _default = exports.default = validate;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n return parseInt(uuid.slice(14, 15), 16);\n}\nvar _default = exports.default = version;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"MAX\", {\n enumerable: true,\n get: function () {\n return _max.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v1ToV6\", {\n enumerable: true,\n get: function () {\n return _v1ToV.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"v6\", {\n enumerable: true,\n get: function () {\n return _v5.default;\n }\n});\nObject.defineProperty(exports, \"v6ToV1\", {\n enumerable: true,\n get: function () {\n return _v6ToV.default;\n }\n});\nObject.defineProperty(exports, \"v7\", {\n enumerable: true,\n get: function () {\n return _v6.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nvar _max = _interopRequireDefault(require(\"./max.js\"));\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\nvar _v5 = _interopRequireDefault(require(\"./v6.js\"));\nvar _v6ToV = _interopRequireDefault(require(\"./v6ToV1.js\"));\nvar _v6 = _interopRequireDefault(require(\"./v7.js\"));\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nvar _version = _interopRequireDefault(require(\"./version.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('md5').update(bytes).digest();\n}\nvar _default = exports.default = md5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nvar _default = exports.default = {\n randomUUID: _nodeCrypto.default.randomUUID\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = '00000000-0000-0000-0000-000000000000';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n const arr = new Uint8Array(16);\n\n // Parse ########-....-....-....-............\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff;\n\n // Parse ........-####-....-....-............\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff;\n\n // Parse ........-....-####-....-............\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff;\n\n // Parse ........-....-....-####-............\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff;\n\n // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\nvar _default = exports.default = parse;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\nlet poolPtr = rnds8Pool.length;\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _nodeCrypto.default.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('sha1').update(bytes).digest();\n}\nvar _default = exports.default = sha1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nvar _default = exports.default = stringify;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nlet _nodeId;\nlet _clockseq;\n\n// Previous uuid creation time\nlet _lastMSecs = 0;\nlet _lastNSecs = 0;\n\n// See https://github.com/uuidjs/uuid for API details\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node;\n let clockseq = options.clockseq;\n\n // v1 only: Use cached `node` and `clockseq` values\n if (!options._v6) {\n if (!node) {\n node = _nodeId;\n }\n if (clockseq == null) {\n clockseq = _clockseq;\n }\n }\n\n // Handle cases where we need entropy. We do this lazily to minimize issues\n // related to insufficient system entropy. See #189\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n // Randomize node\n if (node == null) {\n node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n\n // v1 only: cache node value for reuse\n if (!_nodeId && !options._v6) {\n // per RFC4122 4.5: Set MAC multicast bit (v1 only)\n node[0] |= 0x01; // Set multicast bit\n\n _nodeId = node;\n }\n }\n\n // Randomize clockseq\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n if (_clockseq === undefined && !options._v6) {\n _clockseq = clockseq;\n }\n }\n }\n\n // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is\n // handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n let msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v1ToV6;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v1 UUID to a v6 UUID\n *\n * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6\n * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v1ToV6(uuid) {\n const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v6Bytes = _v1ToV6(v1Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes;\n}\n\n// Do the field transformation needed for v1 -> v6\nfunction _v1ToV6(v1Bytes, randomize = false) {\n return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = exports.default = v3;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\nvar _stringify = require(\"./stringify.js\");\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n return bytes;\n}\nconst DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nconst URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n }\n\n // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n }\n\n // Function#name is not settable on some platforms (#270)\n try {\n generateUUID.name = name;\n } catch (err) {}\n\n // For CommonJS default export support\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _native = _interopRequireDefault(require(\"./native.js\"));\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || _rng.default)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(rnds);\n}\nvar _default = exports.default = v4;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = exports.default = v5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6;\nvar _stringify = require(\"./stringify.js\");\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n *\n * @param {object} options\n * @param {Uint8Array=} buf\n * @param {number=} offset\n * @returns\n */\nfunction v6(options = {}, buf, offset = 0) {\n // v6 is v1 with different field layout, so we start with a v1 UUID, albeit\n // with slightly different behavior around how the clock_seq and node fields\n // are randomized, which is why we call v1 with _v6: true.\n let bytes = (0, _v.default)({\n ...options,\n _v6: true\n }, new Uint8Array(16));\n\n // Reorder the fields to v6 layout.\n bytes = (0, _v1ToV.default)(bytes);\n\n // Return as a byte array if requested\n if (buf) {\n for (let i = 0; i < 16; i++) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6ToV1;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v6 UUID to a v1 UUID\n *\n * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6\n * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v6ToV1(uuid) {\n const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v1Bytes = _v6ToV1(v6Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes;\n}\n\n// Do the field transformation needed for v6 -> v1\nfunction _v6ToV1(v6Bytes) {\n return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * UUID V7 - Unix Epoch time-based UUID\n *\n * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This\n * implementation of V7 is based on the accepted, though not yet approved,\n * revisions.\n *\n * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique\n * IDentifiers (UUIDs)\n\n *\n * Sample V7 value:\n * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value\n *\n * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref:\n * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1\n *\n * 0 1 2 3 0 1 2 3 4 5 6\n * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms | ver | seq_hi |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * |var| seq_low | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n *\n * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit\n * seq_low, and randomly initialized upon timestamp change. 31 bit counter size\n * was selected as any bitwise operations in node are done as _signed_ 32 bit\n * ints. we exclude the sign bit.\n */\n\nlet _seqLow = null;\nlet _seqHigh = null;\nlet _msecs = 0;\nfunction v7(options, buf, offset) {\n options = options || {};\n\n // initialize buffer and pointer\n let i = buf && offset || 0;\n const b = buf || new Uint8Array(16);\n\n // rnds is Uint8Array(16) filled with random bytes\n const rnds = options.random || (options.rng || _rng.default)();\n\n // milliseconds since unix epoch, 1970-01-01 00:00\n const msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // seq is user provided 31 bit counter\n let seq = options.seq !== undefined ? options.seq : null;\n\n // initialize local seq high/low parts\n let seqHigh = _seqHigh;\n let seqLow = _seqLow;\n\n // check if clock has advanced and user has not provided msecs\n if (msecs > _msecs && options.msecs === undefined) {\n _msecs = msecs;\n\n // unless user provided seq, reset seq parts\n if (seq !== null) {\n seqHigh = null;\n seqLow = null;\n }\n }\n\n // if we have a user provided seq\n if (seq !== null) {\n // trim provided seq to 31 bits of value, avoiding overflow\n if (seq > 0x7fffffff) {\n seq = 0x7fffffff;\n }\n\n // split provided seq into high/low parts\n seqHigh = seq >>> 19 & 0xfff;\n seqLow = seq & 0x7ffff;\n }\n\n // randomly initialize seq\n if (seqHigh === null || seqLow === null) {\n seqHigh = rnds[6] & 0x7f;\n seqHigh = seqHigh << 8 | rnds[7];\n seqLow = rnds[8] & 0x3f; // pad for var\n seqLow = seqLow << 8 | rnds[9];\n seqLow = seqLow << 5 | rnds[10] >>> 3;\n }\n\n // increment seq if within msecs window\n if (msecs + 10000 > _msecs && seq === null) {\n if (++seqLow > 0x7ffff) {\n seqLow = 0;\n if (++seqHigh > 0xfff) {\n seqHigh = 0;\n\n // increment internal _msecs. this allows us to continue incrementing\n // while staying monotonic. Note, once we hit 10k milliseconds beyond system\n // clock, we will reset breaking monotonicity (after (2^31)*10000 generations)\n _msecs++;\n }\n }\n } else {\n // resetting; we have advanced more than\n // 10k milliseconds beyond system clock\n _msecs = msecs;\n }\n _seqHigh = seqHigh;\n _seqLow = seqLow;\n\n // [bytes 0-5] 48 bits of local timestamp\n b[i++] = _msecs / 0x10000000000 & 0xff;\n b[i++] = _msecs / 0x100000000 & 0xff;\n b[i++] = _msecs / 0x1000000 & 0xff;\n b[i++] = _msecs / 0x10000 & 0xff;\n b[i++] = _msecs / 0x100 & 0xff;\n b[i++] = _msecs & 0xff;\n\n // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi\n b[i++] = seqHigh >>> 4 & 0x0f | 0x70;\n\n // [byte 7] remaining 8 bits of seq_hi\n b[i++] = seqHigh & 0xff;\n\n // [byte 8] - variant (2 bits), first 6 bits seq_low\n b[i++] = seqLow >>> 13 & 0x3f | 0x80;\n\n // [byte 9] 8 bits seq_low\n b[i++] = seqLow >>> 5 & 0xff;\n\n // [byte 10] remaining 5 bits seq_low, 3 bits random\n b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07;\n\n // [bytes 11-15] always random\n b[i++] = rnds[11];\n b[i++] = rnds[12];\n b[i++] = rnds[13];\n b[i++] = rnds[14];\n b[i++] = rnds[15];\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v7;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\nvar _default = exports.default = validate;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n return parseInt(uuid.slice(14, 15), 16);\n}\nvar _default = exports.default = version;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"MAX\", {\n enumerable: true,\n get: function () {\n return _max.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v1ToV6\", {\n enumerable: true,\n get: function () {\n return _v1ToV.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"v6\", {\n enumerable: true,\n get: function () {\n return _v5.default;\n }\n});\nObject.defineProperty(exports, \"v6ToV1\", {\n enumerable: true,\n get: function () {\n return _v6ToV.default;\n }\n});\nObject.defineProperty(exports, \"v7\", {\n enumerable: true,\n get: function () {\n return _v6.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nvar _max = _interopRequireDefault(require(\"./max.js\"));\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\nvar _v5 = _interopRequireDefault(require(\"./v6.js\"));\nvar _v6ToV = _interopRequireDefault(require(\"./v6ToV1.js\"));\nvar _v6 = _interopRequireDefault(require(\"./v7.js\"));\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nvar _version = _interopRequireDefault(require(\"./version.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('md5').update(bytes).digest();\n}\nvar _default = exports.default = md5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nvar _default = exports.default = {\n randomUUID: _nodeCrypto.default.randomUUID\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = '00000000-0000-0000-0000-000000000000';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n const arr = new Uint8Array(16);\n\n // Parse ########-....-....-....-............\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff;\n\n // Parse ........-####-....-....-............\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff;\n\n // Parse ........-....-####-....-............\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff;\n\n // Parse ........-....-....-####-............\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff;\n\n // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\nvar _default = exports.default = parse;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\nlet poolPtr = rnds8Pool.length;\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _nodeCrypto.default.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('sha1').update(bytes).digest();\n}\nvar _default = exports.default = sha1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nvar _default = exports.default = stringify;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nlet _nodeId;\nlet _clockseq;\n\n// Previous uuid creation time\nlet _lastMSecs = 0;\nlet _lastNSecs = 0;\n\n// See https://github.com/uuidjs/uuid for API details\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node;\n let clockseq = options.clockseq;\n\n // v1 only: Use cached `node` and `clockseq` values\n if (!options._v6) {\n if (!node) {\n node = _nodeId;\n }\n if (clockseq == null) {\n clockseq = _clockseq;\n }\n }\n\n // Handle cases where we need entropy. We do this lazily to minimize issues\n // related to insufficient system entropy. See #189\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n // Randomize node\n if (node == null) {\n node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n\n // v1 only: cache node value for reuse\n if (!_nodeId && !options._v6) {\n // per RFC4122 4.5: Set MAC multicast bit (v1 only)\n node[0] |= 0x01; // Set multicast bit\n\n _nodeId = node;\n }\n }\n\n // Randomize clockseq\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n if (_clockseq === undefined && !options._v6) {\n _clockseq = clockseq;\n }\n }\n }\n\n // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is\n // handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n let msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v1ToV6;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v1 UUID to a v6 UUID\n *\n * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6\n * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v1ToV6(uuid) {\n const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v6Bytes = _v1ToV6(v1Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes;\n}\n\n// Do the field transformation needed for v1 -> v6\nfunction _v1ToV6(v1Bytes, randomize = false) {\n return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = exports.default = v3;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\nvar _stringify = require(\"./stringify.js\");\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n return bytes;\n}\nconst DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nconst URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n }\n\n // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n }\n\n // Function#name is not settable on some platforms (#270)\n try {\n generateUUID.name = name;\n } catch (err) {}\n\n // For CommonJS default export support\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _native = _interopRequireDefault(require(\"./native.js\"));\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || _rng.default)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(rnds);\n}\nvar _default = exports.default = v4;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = exports.default = v5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6;\nvar _stringify = require(\"./stringify.js\");\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n *\n * @param {object} options\n * @param {Uint8Array=} buf\n * @param {number=} offset\n * @returns\n */\nfunction v6(options = {}, buf, offset = 0) {\n // v6 is v1 with different field layout, so we start with a v1 UUID, albeit\n // with slightly different behavior around how the clock_seq and node fields\n // are randomized, which is why we call v1 with _v6: true.\n let bytes = (0, _v.default)({\n ...options,\n _v6: true\n }, new Uint8Array(16));\n\n // Reorder the fields to v6 layout.\n bytes = (0, _v1ToV.default)(bytes);\n\n // Return as a byte array if requested\n if (buf) {\n for (let i = 0; i < 16; i++) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6ToV1;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v6 UUID to a v1 UUID\n *\n * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6\n * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v6ToV1(uuid) {\n const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v1Bytes = _v6ToV1(v6Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes;\n}\n\n// Do the field transformation needed for v6 -> v1\nfunction _v6ToV1(v6Bytes) {\n return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * UUID V7 - Unix Epoch time-based UUID\n *\n * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This\n * implementation of V7 is based on the accepted, though not yet approved,\n * revisions.\n *\n * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique\n * IDentifiers (UUIDs)\n\n *\n * Sample V7 value:\n * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value\n *\n * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref:\n * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1\n *\n * 0 1 2 3 0 1 2 3 4 5 6\n * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms | ver | seq_hi |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * |var| seq_low | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n *\n * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit\n * seq_low, and randomly initialized upon timestamp change. 31 bit counter size\n * was selected as any bitwise operations in node are done as _signed_ 32 bit\n * ints. we exclude the sign bit.\n */\n\nlet _seqLow = null;\nlet _seqHigh = null;\nlet _msecs = 0;\nfunction v7(options, buf, offset) {\n options = options || {};\n\n // initialize buffer and pointer\n let i = buf && offset || 0;\n const b = buf || new Uint8Array(16);\n\n // rnds is Uint8Array(16) filled with random bytes\n const rnds = options.random || (options.rng || _rng.default)();\n\n // milliseconds since unix epoch, 1970-01-01 00:00\n const msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // seq is user provided 31 bit counter\n let seq = options.seq !== undefined ? options.seq : null;\n\n // initialize local seq high/low parts\n let seqHigh = _seqHigh;\n let seqLow = _seqLow;\n\n // check if clock has advanced and user has not provided msecs\n if (msecs > _msecs && options.msecs === undefined) {\n _msecs = msecs;\n\n // unless user provided seq, reset seq parts\n if (seq !== null) {\n seqHigh = null;\n seqLow = null;\n }\n }\n\n // if we have a user provided seq\n if (seq !== null) {\n // trim provided seq to 31 bits of value, avoiding overflow\n if (seq > 0x7fffffff) {\n seq = 0x7fffffff;\n }\n\n // split provided seq into high/low parts\n seqHigh = seq >>> 19 & 0xfff;\n seqLow = seq & 0x7ffff;\n }\n\n // randomly initialize seq\n if (seqHigh === null || seqLow === null) {\n seqHigh = rnds[6] & 0x7f;\n seqHigh = seqHigh << 8 | rnds[7];\n seqLow = rnds[8] & 0x3f; // pad for var\n seqLow = seqLow << 8 | rnds[9];\n seqLow = seqLow << 5 | rnds[10] >>> 3;\n }\n\n // increment seq if within msecs window\n if (msecs + 10000 > _msecs && seq === null) {\n if (++seqLow > 0x7ffff) {\n seqLow = 0;\n if (++seqHigh > 0xfff) {\n seqHigh = 0;\n\n // increment internal _msecs. this allows us to continue incrementing\n // while staying monotonic. Note, once we hit 10k milliseconds beyond system\n // clock, we will reset breaking monotonicity (after (2^31)*10000 generations)\n _msecs++;\n }\n }\n } else {\n // resetting; we have advanced more than\n // 10k milliseconds beyond system clock\n _msecs = msecs;\n }\n _seqHigh = seqHigh;\n _seqLow = seqLow;\n\n // [bytes 0-5] 48 bits of local timestamp\n b[i++] = _msecs / 0x10000000000 & 0xff;\n b[i++] = _msecs / 0x100000000 & 0xff;\n b[i++] = _msecs / 0x1000000 & 0xff;\n b[i++] = _msecs / 0x10000 & 0xff;\n b[i++] = _msecs / 0x100 & 0xff;\n b[i++] = _msecs & 0xff;\n\n // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi\n b[i++] = seqHigh >>> 4 & 0x0f | 0x70;\n\n // [byte 7] remaining 8 bits of seq_hi\n b[i++] = seqHigh & 0xff;\n\n // [byte 8] - variant (2 bits), first 6 bits seq_low\n b[i++] = seqLow >>> 13 & 0x3f | 0x80;\n\n // [byte 9] 8 bits seq_low\n b[i++] = seqLow >>> 5 & 0xff;\n\n // [byte 10] remaining 5 bits seq_low, 3 bits random\n b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07;\n\n // [bytes 11-15] always random\n b[i++] = rnds[11];\n b[i++] = rnds[12];\n b[i++] = rnds[13];\n b[i++] = rnds[14];\n b[i++] = rnds[15];\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v7;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\nvar _default = exports.default = validate;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n return parseInt(uuid.slice(14, 15), 16);\n}\nvar _default = exports.default = version;","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n createTokenAuth: () => createTokenAuth\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/auth.js\nvar REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nvar REGEX_IS_INSTALLATION = /^ghs_/;\nvar REGEX_IS_USER_TO_SERVER = /^ghu_/;\nasync function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp ? \"app\" : isInstallation ? \"installation\" : isUserToServer ? \"user-to-server\" : \"oauth\";\n return {\n type: \"token\",\n token,\n tokenType\n };\n}\n\n// pkg/dist-src/with-authorization-prefix.js\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n\n// pkg/dist-src/hook.js\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(\n route,\n parameters\n );\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\n// pkg/dist-src/index.js\nvar createTokenAuth = function createTokenAuth2(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\n \"[@octokit/auth-token] Token passed to createTokenAuth is not a string\"\n );\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n createTokenAuth\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar index_exports = {};\n__export(index_exports, {\n Octokit: () => Octokit\n});\nmodule.exports = __toCommonJS(index_exports);\nvar import_universal_user_agent = require(\"universal-user-agent\");\nvar import_before_after_hook = require(\"before-after-hook\");\nvar import_request = require(\"@octokit/request\");\nvar import_graphql = require(\"@octokit/graphql\");\nvar import_auth_token = require(\"@octokit/auth-token\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"5.2.2\";\n\n// pkg/dist-src/index.js\nvar noop = () => {\n};\nvar consoleWarn = console.warn.bind(console);\nvar consoleError = console.error.bind(console);\nfunction createLogger(logger = {}) {\n if (typeof logger.debug !== \"function\") {\n logger.debug = noop;\n }\n if (typeof logger.info !== \"function\") {\n logger.info = noop;\n }\n if (typeof logger.warn !== \"function\") {\n logger.warn = consoleWarn;\n }\n if (typeof logger.error !== \"function\") {\n logger.error = consoleError;\n }\n return logger;\n}\nvar userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;\nvar Octokit = class {\n static {\n this.VERSION = VERSION;\n }\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n super(\n Object.assign(\n {},\n defaults,\n options,\n options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null\n )\n );\n }\n };\n return OctokitWithDefaults;\n }\n static {\n this.plugins = [];\n }\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n static plugin(...newPlugins) {\n const currentPlugins = this.plugins;\n const NewOctokit = class extends this {\n static {\n this.plugins = currentPlugins.concat(\n newPlugins.filter((plugin) => !currentPlugins.includes(plugin))\n );\n }\n };\n return NewOctokit;\n }\n constructor(options = {}) {\n const hook = new import_before_after_hook.Collection();\n const requestDefaults = {\n baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n // @ts-ignore internal usage only, no need to type\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n };\n requestDefaults.headers[\"user-agent\"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n this.request = import_request.request.defaults(requestDefaults);\n this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults);\n this.log = createLogger(options.log);\n this.hook = hook;\n if (!options.authStrategy) {\n if (!options.auth) {\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n const auth = (0, import_auth_token.createTokenAuth)(options.auth);\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const { authStrategy, ...otherOptions } = options;\n const auth = authStrategy(\n Object.assign(\n {\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n },\n options.auth\n )\n );\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n const classConstructor = this.constructor;\n for (let i = 0; i < classConstructor.plugins.length; ++i) {\n Object.assign(this, classConstructor.plugins[i](this, options));\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n Octokit\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n endpoint: () => endpoint\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/defaults.js\nvar import_universal_user_agent = require(\"universal-user-agent\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"9.0.6\";\n\n// pkg/dist-src/defaults.js\nvar userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;\nvar DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\"\n }\n};\n\n// pkg/dist-src/util/lowercase-keys.js\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\n// pkg/dist-src/util/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null)\n return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\")\n return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null)\n return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/util/merge-deep.js\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach((key) => {\n if (isPlainObject(options[key])) {\n if (!(key in defaults))\n Object.assign(result, { [key]: options[key] });\n else\n result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, { [key]: options[key] });\n }\n });\n return result;\n}\n\n// pkg/dist-src/util/remove-undefined-properties.js\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === void 0) {\n delete obj[key];\n }\n }\n return obj;\n}\n\n// pkg/dist-src/merge.js\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? { method, url } : { url: method }, options);\n } else {\n options = Object.assign({}, route);\n }\n options.headers = lowercaseKeys(options.headers);\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options);\n if (options.url === \"/graphql\") {\n if (defaults && defaults.mediaType.previews?.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(\n (preview) => !mergedOptions.mediaType.previews.includes(preview)\n ).concat(mergedOptions.mediaType.previews);\n }\n mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, \"\"));\n }\n return mergedOptions;\n}\n\n// pkg/dist-src/util/add-query-parameters.js\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n if (names.length === 0) {\n return url;\n }\n return url + separator + names.map((name) => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\n// pkg/dist-src/util/extract-url-variable-names.js\nvar urlVariableRegex = /\\{[^{}}]+\\}/g;\nfunction removeNonChars(variableName) {\n return variableName.replace(/(?:^\\W+)|(?:(? a.concat(b), []);\n}\n\n// pkg/dist-src/util/omit.js\nfunction omit(object, keysToOmit) {\n const result = { __proto__: null };\n for (const key of Object.keys(object)) {\n if (keysToOmit.indexOf(key) === -1) {\n result[key] = object[key];\n }\n }\n return result;\n}\n\n// pkg/dist-src/util/url-template.js\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n return part;\n }).join(\"\");\n}\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\nfunction isDefined(value) {\n return value !== void 0 && value !== null;\n}\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\nfunction getValues(context, operator, key, modifier) {\n var value = context[key], result = [];\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n value = value.toString();\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n result.push(\n encodeValue(operator, value, isKeyOperator(operator) ? key : \"\")\n );\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n result.push(\n encodeValue(operator, value2, isKeyOperator(operator) ? key : \"\")\n );\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n tmp.push(encodeValue(operator, value2));\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n return result;\n}\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n template = template.replace(\n /\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g,\n function(_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n expression.split(/,/g).forEach(function(variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n if (operator && operator !== \"+\") {\n var separator = \",\";\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n }\n );\n if (template === \"/\") {\n return template;\n } else {\n return template.replace(/\\/$/, \"\");\n }\n}\n\n// pkg/dist-src/parse.js\nfunction parse(options) {\n let method = options.method.toUpperCase();\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"mediaType\"\n ]);\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n headers.accept = headers.accept.split(/,/).map(\n (format) => format.replace(\n /application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/,\n `application/vnd$1$2.${options.mediaType.format}`\n )\n ).join(\",\");\n }\n if (url.endsWith(\"/graphql\")) {\n if (options.mediaType.previews?.length) {\n const previewsFromAcceptHeader = headers.accept.match(/(? {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n }\n }\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n }\n }\n }\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n }\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n }\n return Object.assign(\n { method, url, headers },\n typeof body !== \"undefined\" ? { body } : null,\n options.request ? { request: options.request } : null\n );\n}\n\n// pkg/dist-src/endpoint-with-defaults.js\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS2 = merge(oldDefaults, newDefaults);\n const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);\n return Object.assign(endpoint2, {\n DEFAULTS: DEFAULTS2,\n defaults: withDefaults.bind(null, DEFAULTS2),\n merge: merge.bind(null, DEFAULTS2),\n parse\n });\n}\n\n// pkg/dist-src/index.js\nvar endpoint = withDefaults(null, DEFAULTS);\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n endpoint\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar index_exports = {};\n__export(index_exports, {\n GraphqlResponseError: () => GraphqlResponseError,\n graphql: () => graphql2,\n withCustomRequest: () => withCustomRequest\n});\nmodule.exports = __toCommonJS(index_exports);\nvar import_request3 = require(\"@octokit/request\");\nvar import_universal_user_agent = require(\"universal-user-agent\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"7.1.1\";\n\n// pkg/dist-src/with-defaults.js\nvar import_request2 = require(\"@octokit/request\");\n\n// pkg/dist-src/graphql.js\nvar import_request = require(\"@octokit/request\");\n\n// pkg/dist-src/error.js\nfunction _buildMessageForResponseErrors(data) {\n return `Request failed due to following response errors:\n` + data.errors.map((e) => ` - ${e.message}`).join(\"\\n\");\n}\nvar GraphqlResponseError = class extends Error {\n constructor(request2, headers, response) {\n super(_buildMessageForResponseErrors(response));\n this.request = request2;\n this.headers = headers;\n this.response = response;\n this.name = \"GraphqlResponseError\";\n this.errors = response.errors;\n this.data = response.data;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n};\n\n// pkg/dist-src/graphql.js\nvar NON_VARIABLE_OPTIONS = [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"query\",\n \"mediaType\"\n];\nvar FORBIDDEN_VARIABLE_OPTIONS = [\"query\", \"method\", \"url\"];\nvar GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request2, query, options) {\n if (options) {\n if (typeof query === \"string\" && \"query\" in options) {\n return Promise.reject(\n new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`)\n );\n }\n for (const key in options) {\n if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;\n return Promise.reject(\n new Error(\n `[@octokit/graphql] \"${key}\" cannot be used as variable name`\n )\n );\n }\n }\n const parsedOptions = typeof query === \"string\" ? Object.assign({ query }, options) : query;\n const requestOptions = Object.keys(\n parsedOptions\n ).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n if (!result.variables) {\n result.variables = {};\n }\n result.variables[key] = parsedOptions[key];\n return result;\n }, {});\n const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n return request2(requestOptions).then((response) => {\n if (response.data.errors) {\n const headers = {};\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n throw new GraphqlResponseError(\n requestOptions,\n headers,\n response.data\n );\n }\n return response.data.data;\n });\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(request2, newDefaults) {\n const newRequest = request2.defaults(newDefaults);\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: newRequest.endpoint\n });\n}\n\n// pkg/dist-src/index.js\nvar graphql2 = withDefaults(import_request3.request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n GraphqlResponseError,\n graphql,\n withCustomRequest\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n composePaginateRest: () => composePaginateRest,\n isPaginatingEndpoint: () => isPaginatingEndpoint,\n paginateRest: () => paginateRest,\n paginatingEndpoints: () => paginatingEndpoints\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/version.js\nvar VERSION = \"9.2.2\";\n\n// pkg/dist-src/normalize-paginated-list-response.js\nfunction normalizePaginatedListResponse(response) {\n if (!response.data) {\n return {\n ...response,\n data: []\n };\n }\n const responseNeedsNormalization = \"total_count\" in response.data && !(\"url\" in response.data);\n if (!responseNeedsNormalization)\n return response;\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n response.data.total_count = totalCount;\n return response;\n}\n\n// pkg/dist-src/iterator.js\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (!url)\n return { done: true };\n try {\n const response = await requestMethod({ method, url, headers });\n const normalizedResponse = normalizePaginatedListResponse(response);\n url = ((normalizedResponse.headers.link || \"\").match(\n /<([^<>]+)>;\\s*rel=\"next\"/\n ) || [])[1];\n return { value: normalizedResponse };\n } catch (error) {\n if (error.status !== 409)\n throw error;\n url = \"\";\n return {\n value: {\n status: 200,\n headers: {},\n data: []\n }\n };\n }\n }\n })\n };\n}\n\n// pkg/dist-src/paginate.js\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = void 0;\n }\n return gather(\n octokit,\n [],\n iterator(octokit, route, parameters)[Symbol.asyncIterator](),\n mapFn\n );\n}\nfunction gather(octokit, results, iterator2, mapFn) {\n return iterator2.next().then((result) => {\n if (result.done) {\n return results;\n }\n let earlyExit = false;\n function done() {\n earlyExit = true;\n }\n results = results.concat(\n mapFn ? mapFn(result.value, done) : result.value.data\n );\n if (earlyExit) {\n return results;\n }\n return gather(octokit, results, iterator2, mapFn);\n });\n}\n\n// pkg/dist-src/compose-paginate.js\nvar composePaginateRest = Object.assign(paginate, {\n iterator\n});\n\n// pkg/dist-src/generated/paginating-endpoints.js\nvar paginatingEndpoints = [\n \"GET /advisories\",\n \"GET /app/hook/deliveries\",\n \"GET /app/installation-requests\",\n \"GET /app/installations\",\n \"GET /assignments/{assignment_id}/accepted_assignments\",\n \"GET /classrooms\",\n \"GET /classrooms/{classroom_id}/assignments\",\n \"GET /enterprises/{enterprise}/dependabot/alerts\",\n \"GET /enterprises/{enterprise}/secret-scanning/alerts\",\n \"GET /events\",\n \"GET /gists\",\n \"GET /gists/public\",\n \"GET /gists/starred\",\n \"GET /gists/{gist_id}/comments\",\n \"GET /gists/{gist_id}/commits\",\n \"GET /gists/{gist_id}/forks\",\n \"GET /installation/repositories\",\n \"GET /issues\",\n \"GET /licenses\",\n \"GET /marketplace_listing/plans\",\n \"GET /marketplace_listing/plans/{plan_id}/accounts\",\n \"GET /marketplace_listing/stubbed/plans\",\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\",\n \"GET /networks/{owner}/{repo}/events\",\n \"GET /notifications\",\n \"GET /organizations\",\n \"GET /orgs/{org}/actions/cache/usage-by-repository\",\n \"GET /orgs/{org}/actions/permissions/repositories\",\n \"GET /orgs/{org}/actions/runners\",\n \"GET /orgs/{org}/actions/secrets\",\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/actions/variables\",\n \"GET /orgs/{org}/actions/variables/{name}/repositories\",\n \"GET /orgs/{org}/blocks\",\n \"GET /orgs/{org}/code-scanning/alerts\",\n \"GET /orgs/{org}/codespaces\",\n \"GET /orgs/{org}/codespaces/secrets\",\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/copilot/billing/seats\",\n \"GET /orgs/{org}/dependabot/alerts\",\n \"GET /orgs/{org}/dependabot/secrets\",\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/events\",\n \"GET /orgs/{org}/failed_invitations\",\n \"GET /orgs/{org}/hooks\",\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries\",\n \"GET /orgs/{org}/installations\",\n \"GET /orgs/{org}/invitations\",\n \"GET /orgs/{org}/invitations/{invitation_id}/teams\",\n \"GET /orgs/{org}/issues\",\n \"GET /orgs/{org}/members\",\n \"GET /orgs/{org}/members/{username}/codespaces\",\n \"GET /orgs/{org}/migrations\",\n \"GET /orgs/{org}/migrations/{migration_id}/repositories\",\n \"GET /orgs/{org}/organization-roles/{role_id}/teams\",\n \"GET /orgs/{org}/organization-roles/{role_id}/users\",\n \"GET /orgs/{org}/outside_collaborators\",\n \"GET /orgs/{org}/packages\",\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n \"GET /orgs/{org}/personal-access-token-requests\",\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\",\n \"GET /orgs/{org}/personal-access-tokens\",\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\",\n \"GET /orgs/{org}/projects\",\n \"GET /orgs/{org}/properties/values\",\n \"GET /orgs/{org}/public_members\",\n \"GET /orgs/{org}/repos\",\n \"GET /orgs/{org}/rulesets\",\n \"GET /orgs/{org}/rulesets/rule-suites\",\n \"GET /orgs/{org}/secret-scanning/alerts\",\n \"GET /orgs/{org}/security-advisories\",\n \"GET /orgs/{org}/teams\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/invitations\",\n \"GET /orgs/{org}/teams/{team_slug}/members\",\n \"GET /orgs/{org}/teams/{team_slug}/projects\",\n \"GET /orgs/{org}/teams/{team_slug}/repos\",\n \"GET /orgs/{org}/teams/{team_slug}/teams\",\n \"GET /projects/columns/{column_id}/cards\",\n \"GET /projects/{project_id}/collaborators\",\n \"GET /projects/{project_id}/columns\",\n \"GET /repos/{owner}/{repo}/actions/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/caches\",\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\",\n \"GET /repos/{owner}/{repo}/actions/organization-variables\",\n \"GET /repos/{owner}/{repo}/actions/runners\",\n \"GET /repos/{owner}/{repo}/actions/runs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/secrets\",\n \"GET /repos/{owner}/{repo}/actions/variables\",\n \"GET /repos/{owner}/{repo}/actions/workflows\",\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\",\n \"GET /repos/{owner}/{repo}/activity\",\n \"GET /repos/{owner}/{repo}/assignees\",\n \"GET /repos/{owner}/{repo}/branches\",\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\",\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n \"GET /repos/{owner}/{repo}/code-scanning/analyses\",\n \"GET /repos/{owner}/{repo}/codespaces\",\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\",\n \"GET /repos/{owner}/{repo}/codespaces/secrets\",\n \"GET /repos/{owner}/{repo}/collaborators\",\n \"GET /repos/{owner}/{repo}/comments\",\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/commits\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/status\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\",\n \"GET /repos/{owner}/{repo}/contributors\",\n \"GET /repos/{owner}/{repo}/dependabot/alerts\",\n \"GET /repos/{owner}/{repo}/dependabot/secrets\",\n \"GET /repos/{owner}/{repo}/deployments\",\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n \"GET /repos/{owner}/{repo}/environments\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\",\n \"GET /repos/{owner}/{repo}/events\",\n \"GET /repos/{owner}/{repo}/forks\",\n \"GET /repos/{owner}/{repo}/hooks\",\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\",\n \"GET /repos/{owner}/{repo}/invitations\",\n \"GET /repos/{owner}/{repo}/issues\",\n \"GET /repos/{owner}/{repo}/issues/comments\",\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\",\n \"GET /repos/{owner}/{repo}/keys\",\n \"GET /repos/{owner}/{repo}/labels\",\n \"GET /repos/{owner}/{repo}/milestones\",\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\",\n \"GET /repos/{owner}/{repo}/notifications\",\n \"GET /repos/{owner}/{repo}/pages/builds\",\n \"GET /repos/{owner}/{repo}/projects\",\n \"GET /repos/{owner}/{repo}/pulls\",\n \"GET /repos/{owner}/{repo}/pulls/comments\",\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\",\n \"GET /repos/{owner}/{repo}/releases\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n \"GET /repos/{owner}/{repo}/rules/branches/{branch}\",\n \"GET /repos/{owner}/{repo}/rulesets\",\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\",\n \"GET /repos/{owner}/{repo}/security-advisories\",\n \"GET /repos/{owner}/{repo}/stargazers\",\n \"GET /repos/{owner}/{repo}/subscribers\",\n \"GET /repos/{owner}/{repo}/tags\",\n \"GET /repos/{owner}/{repo}/teams\",\n \"GET /repos/{owner}/{repo}/topics\",\n \"GET /repositories\",\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets\",\n \"GET /repositories/{repository_id}/environments/{environment_name}/variables\",\n \"GET /search/code\",\n \"GET /search/commits\",\n \"GET /search/issues\",\n \"GET /search/labels\",\n \"GET /search/repositories\",\n \"GET /search/topics\",\n \"GET /search/users\",\n \"GET /teams/{team_id}/discussions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/reactions\",\n \"GET /teams/{team_id}/invitations\",\n \"GET /teams/{team_id}/members\",\n \"GET /teams/{team_id}/projects\",\n \"GET /teams/{team_id}/repos\",\n \"GET /teams/{team_id}/teams\",\n \"GET /user/blocks\",\n \"GET /user/codespaces\",\n \"GET /user/codespaces/secrets\",\n \"GET /user/emails\",\n \"GET /user/followers\",\n \"GET /user/following\",\n \"GET /user/gpg_keys\",\n \"GET /user/installations\",\n \"GET /user/installations/{installation_id}/repositories\",\n \"GET /user/issues\",\n \"GET /user/keys\",\n \"GET /user/marketplace_purchases\",\n \"GET /user/marketplace_purchases/stubbed\",\n \"GET /user/memberships/orgs\",\n \"GET /user/migrations\",\n \"GET /user/migrations/{migration_id}/repositories\",\n \"GET /user/orgs\",\n \"GET /user/packages\",\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n \"GET /user/public_emails\",\n \"GET /user/repos\",\n \"GET /user/repository_invitations\",\n \"GET /user/social_accounts\",\n \"GET /user/ssh_signing_keys\",\n \"GET /user/starred\",\n \"GET /user/subscriptions\",\n \"GET /user/teams\",\n \"GET /users\",\n \"GET /users/{username}/events\",\n \"GET /users/{username}/events/orgs/{org}\",\n \"GET /users/{username}/events/public\",\n \"GET /users/{username}/followers\",\n \"GET /users/{username}/following\",\n \"GET /users/{username}/gists\",\n \"GET /users/{username}/gpg_keys\",\n \"GET /users/{username}/keys\",\n \"GET /users/{username}/orgs\",\n \"GET /users/{username}/packages\",\n \"GET /users/{username}/projects\",\n \"GET /users/{username}/received_events\",\n \"GET /users/{username}/received_events/public\",\n \"GET /users/{username}/repos\",\n \"GET /users/{username}/social_accounts\",\n \"GET /users/{username}/ssh_signing_keys\",\n \"GET /users/{username}/starred\",\n \"GET /users/{username}/subscriptions\"\n];\n\n// pkg/dist-src/paginating-endpoints.js\nfunction isPaginatingEndpoint(arg) {\n if (typeof arg === \"string\") {\n return paginatingEndpoints.includes(arg);\n } else {\n return false;\n }\n}\n\n// pkg/dist-src/index.js\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n composePaginateRest,\n isPaginatingEndpoint,\n paginateRest,\n paginatingEndpoints\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n legacyRestEndpointMethods: () => legacyRestEndpointMethods,\n restEndpointMethods: () => restEndpointMethods\n});\nmodule.exports = __toCommonJS(dist_src_exports);\n\n// pkg/dist-src/version.js\nvar VERSION = \"10.4.1\";\n\n// pkg/dist-src/generated/endpoints.js\nvar Endpoints = {\n actions: {\n addCustomLabelsToSelfHostedRunnerForOrg: [\n \"POST /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n addCustomLabelsToSelfHostedRunnerForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n addSelectedRepoToOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\"\n ],\n approveWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve\"\n ],\n cancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\"\n ],\n createEnvironmentVariable: [\n \"POST /repositories/{repository_id}/environments/{environment_name}/variables\"\n ],\n createOrUpdateEnvironmentSecret: [\n \"PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"\n ],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\"\n ],\n createOrgVariable: [\"POST /orgs/{org}/actions/variables\"],\n createRegistrationTokenForOrg: [\n \"POST /orgs/{org}/actions/runners/registration-token\"\n ],\n createRegistrationTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/registration-token\"\n ],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/remove-token\"\n ],\n createRepoVariable: [\"POST /repos/{owner}/{repo}/actions/variables\"],\n createWorkflowDispatch: [\n \"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\"\n ],\n deleteActionsCacheById: [\n \"DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}\"\n ],\n deleteActionsCacheByKey: [\n \"DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}\"\n ],\n deleteArtifact: [\n \"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"\n ],\n deleteEnvironmentSecret: [\n \"DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"\n ],\n deleteEnvironmentVariable: [\n \"DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}\"\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteOrgVariable: [\"DELETE /orgs/{org}/actions/variables/{name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\"\n ],\n deleteRepoVariable: [\n \"DELETE /repos/{owner}/{repo}/actions/variables/{name}\"\n ],\n deleteSelfHostedRunnerFromOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}\"\n ],\n deleteSelfHostedRunnerFromRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\"\n ],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\n \"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"\n ],\n disableSelectedRepositoryGithubActionsOrganization: [\n \"DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}\"\n ],\n disableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable\"\n ],\n downloadArtifact: [\n \"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\"\n ],\n downloadJobLogsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\"\n ],\n downloadWorkflowRunAttemptLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs\"\n ],\n downloadWorkflowRunLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\"\n ],\n enableSelectedRepositoryGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories/{repository_id}\"\n ],\n enableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable\"\n ],\n forceCancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel\"\n ],\n generateRunnerJitconfigForOrg: [\n \"POST /orgs/{org}/actions/runners/generate-jitconfig\"\n ],\n generateRunnerJitconfigForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig\"\n ],\n getActionsCacheList: [\"GET /repos/{owner}/{repo}/actions/caches\"],\n getActionsCacheUsage: [\"GET /repos/{owner}/{repo}/actions/cache/usage\"],\n getActionsCacheUsageByRepoForOrg: [\n \"GET /orgs/{org}/actions/cache/usage-by-repository\"\n ],\n getActionsCacheUsageForOrg: [\"GET /orgs/{org}/actions/cache/usage\"],\n getAllowedActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/selected-actions\"\n ],\n getAllowedActionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/selected-actions\"\n ],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getCustomOidcSubClaimForRepo: [\n \"GET /repos/{owner}/{repo}/actions/oidc/customization/sub\"\n ],\n getEnvironmentPublicKey: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key\"\n ],\n getEnvironmentSecret: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}\"\n ],\n getEnvironmentVariable: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}\"\n ],\n getGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/workflow\"\n ],\n getGithubActionsDefaultWorkflowPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/workflow\"\n ],\n getGithubActionsPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions\"\n ],\n getGithubActionsPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions\"\n ],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getOrgVariable: [\"GET /orgs/{org}/actions/variables/{name}\"],\n getPendingDeploymentsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\"\n ],\n getRepoPermissions: [\n \"GET /repos/{owner}/{repo}/actions/permissions\",\n {},\n { renamed: [\"actions\", \"getGithubActionsPermissionsRepository\"] }\n ],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getRepoVariable: [\"GET /repos/{owner}/{repo}/actions/variables/{name}\"],\n getReviewsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals\"\n ],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\"\n ],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowAccessToRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/access\"\n ],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}\"\n ],\n getWorkflowRunUsage: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\"\n ],\n getWorkflowUsage: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\"\n ],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listEnvironmentSecrets: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/secrets\"\n ],\n listEnvironmentVariables: [\n \"GET /repositories/{repository_id}/environments/{environment_name}/variables\"\n ],\n listJobsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\"\n ],\n listJobsForWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\"\n ],\n listLabelsForSelfHostedRunnerForOrg: [\n \"GET /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n listLabelsForSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listOrgVariables: [\"GET /orgs/{org}/actions/variables\"],\n listRepoOrganizationSecrets: [\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\"\n ],\n listRepoOrganizationVariables: [\n \"GET /repos/{owner}/{repo}/actions/organization-variables\"\n ],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoVariables: [\"GET /repos/{owner}/{repo}/actions/variables\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/downloads\"\n ],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\"\n ],\n listSelectedReposForOrgVariable: [\n \"GET /orgs/{org}/actions/variables/{name}/repositories\"\n ],\n listSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/repositories\"\n ],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\"\n ],\n listWorkflowRuns: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\"\n ],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunJobForWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun\"\n ],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n reRunWorkflowFailedJobs: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs\"\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n removeCustomLabelFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}\"\n ],\n removeCustomLabelFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}\"\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n removeSelectedRepoFromOrgVariable: [\n \"DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\"\n ],\n reviewCustomGatesForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule\"\n ],\n reviewPendingDeploymentsForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\"\n ],\n setAllowedActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/selected-actions\"\n ],\n setAllowedActionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/selected-actions\"\n ],\n setCustomLabelsForSelfHostedRunnerForOrg: [\n \"PUT /orgs/{org}/actions/runners/{runner_id}/labels\"\n ],\n setCustomLabelsForSelfHostedRunnerForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\"\n ],\n setCustomOidcSubClaimForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/oidc/customization/sub\"\n ],\n setGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/workflow\"\n ],\n setGithubActionsDefaultWorkflowPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/workflow\"\n ],\n setGithubActionsPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions\"\n ],\n setGithubActionsPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions\"\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\"\n ],\n setSelectedReposForOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories\"\n ],\n setSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories\"\n ],\n setWorkflowAccessToRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/access\"\n ],\n updateEnvironmentVariable: [\n \"PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}\"\n ],\n updateOrgVariable: [\"PATCH /orgs/{org}/actions/variables/{name}\"],\n updateRepoVariable: [\n \"PATCH /repos/{owner}/{repo}/actions/variables/{name}\"\n ]\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\n \"DELETE /notifications/threads/{thread_id}/subscription\"\n ],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\n \"GET /notifications/threads/{thread_id}/subscription\"\n ],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\n \"GET /users/{username}/events/orgs/{org}\"\n ],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\n \"GET /users/{username}/received_events/public\"\n ],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/notifications\"\n ],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsDone: [\"DELETE /notifications/threads/{thread_id}\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\n \"PUT /notifications/threads/{thread_id}/subscription\"\n ],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"]\n },\n apps: {\n addRepoToInstallation: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"addRepoToInstallationForAuthenticatedUser\"] }\n ],\n addRepoToInstallationForAuthenticatedUser: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\"\n ],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\n \"POST /app/installations/{installation_id}/access_tokens\"\n ],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\n \"GET /marketplace_listing/accounts/{account_id}\"\n ],\n getSubscriptionPlanForAccountStubbed: [\n \"GET /marketplace_listing/stubbed/accounts/{account_id}\"\n ],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n getWebhookConfigForApp: [\"GET /app/hook/config\"],\n getWebhookDelivery: [\"GET /app/hook/deliveries/{delivery_id}\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\"\n ],\n listInstallationReposForAuthenticatedUser: [\n \"GET /user/installations/{installation_id}/repositories\"\n ],\n listInstallationRequestsForAuthenticatedApp: [\n \"GET /app/installation-requests\"\n ],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\n \"GET /user/marketplace_purchases/stubbed\"\n ],\n listWebhookDeliveries: [\"GET /app/hook/deliveries\"],\n redeliverWebhookDelivery: [\n \"POST /app/hook/deliveries/{delivery_id}/attempts\"\n ],\n removeRepoFromInstallation: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"removeRepoFromInstallationForAuthenticatedUser\"] }\n ],\n removeRepoFromInstallationForAuthenticatedUser: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\"\n ],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n scopeToken: [\"POST /applications/{client_id}/token/scoped\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\n \"DELETE /app/installations/{installation_id}/suspended\"\n ],\n updateWebhookConfigForApp: [\"PATCH /app/hook/config\"]\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\n \"GET /users/{username}/settings/billing/actions\"\n ],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\n \"GET /users/{username}/settings/billing/packages\"\n ],\n getSharedStorageBillingOrg: [\n \"GET /orgs/{org}/settings/billing/shared-storage\"\n ],\n getSharedStorageBillingUser: [\n \"GET /users/{username}/settings/billing/shared-storage\"\n ]\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\"],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\"],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\"],\n listAnnotations: [\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\"\n ],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\"],\n listForSuite: [\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\"\n ],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\"],\n rerequestRun: [\n \"POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest\"\n ],\n rerequestSuite: [\n \"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\"\n ],\n setSuitesPreferences: [\n \"PATCH /repos/{owner}/{repo}/check-suites/preferences\"\n ],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\"]\n },\n codeScanning: {\n deleteAnalysis: [\n \"DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}\"\n ],\n getAlert: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\",\n {},\n { renamedParameters: { alert_id: \"alert_number\" } }\n ],\n getAnalysis: [\n \"GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}\"\n ],\n getCodeqlDatabase: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}\"\n ],\n getDefaultSetup: [\"GET /repos/{owner}/{repo}/code-scanning/default-setup\"],\n getSarif: [\"GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}\"],\n listAlertInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\"\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/code-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"],\n listAlertsInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n {},\n { renamed: [\"codeScanning\", \"listAlertInstances\"] }\n ],\n listCodeqlDatabases: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases\"\n ],\n listRecentAnalyses: [\"GET /repos/{owner}/{repo}/code-scanning/analyses\"],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\"\n ],\n updateDefaultSetup: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/default-setup\"\n ],\n uploadSarif: [\"POST /repos/{owner}/{repo}/code-scanning/sarifs\"]\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\"],\n getConductCode: [\"GET /codes_of_conduct/{key}\"]\n },\n codespaces: {\n addRepositoryForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n checkPermissionsForDevcontainer: [\n \"GET /repos/{owner}/{repo}/codespaces/permissions_check\"\n ],\n codespaceMachinesForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/machines\"\n ],\n createForAuthenticatedUser: [\"POST /user/codespaces\"],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}\"\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\"\n ],\n createOrUpdateSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}\"\n ],\n createWithPrForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces\"\n ],\n createWithRepoForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/codespaces\"\n ],\n deleteForAuthenticatedUser: [\"DELETE /user/codespaces/{codespace_name}\"],\n deleteFromOrganization: [\n \"DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}\"\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/codespaces/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\"\n ],\n deleteSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}\"\n ],\n exportForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/exports\"\n ],\n getCodespacesForUserInOrg: [\n \"GET /orgs/{org}/members/{username}/codespaces\"\n ],\n getExportDetailsForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/exports/{export_id}\"\n ],\n getForAuthenticatedUser: [\"GET /user/codespaces/{codespace_name}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/codespaces/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/codespaces/secrets/{secret_name}\"],\n getPublicKeyForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/public-key\"\n ],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/public-key\"\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\"\n ],\n getSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}\"\n ],\n listDevcontainersInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\"\n ],\n listForAuthenticatedUser: [\"GET /user/codespaces\"],\n listInOrganization: [\n \"GET /orgs/{org}/codespaces\",\n {},\n { renamedParameters: { org_id: \"org\" } }\n ],\n listInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces\"\n ],\n listOrgSecrets: [\"GET /orgs/{org}/codespaces/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/codespaces/secrets\"],\n listRepositoriesForSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}/repositories\"\n ],\n listSecretsForAuthenticatedUser: [\"GET /user/codespaces/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\"\n ],\n preFlightWithRepoForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/new\"\n ],\n publishForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/publish\"\n ],\n removeRepositoryForSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n repoMachinesForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/machines\"\n ],\n setRepositoriesForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories\"\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories\"\n ],\n startForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/start\"],\n stopForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/stop\"],\n stopInOrganization: [\n \"POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop\"\n ],\n updateForAuthenticatedUser: [\"PATCH /user/codespaces/{codespace_name}\"]\n },\n copilot: {\n addCopilotSeatsForTeams: [\n \"POST /orgs/{org}/copilot/billing/selected_teams\"\n ],\n addCopilotSeatsForUsers: [\n \"POST /orgs/{org}/copilot/billing/selected_users\"\n ],\n cancelCopilotSeatAssignmentForTeams: [\n \"DELETE /orgs/{org}/copilot/billing/selected_teams\"\n ],\n cancelCopilotSeatAssignmentForUsers: [\n \"DELETE /orgs/{org}/copilot/billing/selected_users\"\n ],\n getCopilotOrganizationDetails: [\"GET /orgs/{org}/copilot/billing\"],\n getCopilotSeatDetailsForUser: [\n \"GET /orgs/{org}/members/{username}/copilot\"\n ],\n listCopilotSeats: [\"GET /orgs/{org}/copilot/billing/seats\"]\n },\n dependabot: {\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}\"\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\"\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/dependabot/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\"\n ],\n getAlert: [\"GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/dependabot/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/dependabot/secrets/{secret_name}\"],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/public-key\"\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\"\n ],\n listAlertsForEnterprise: [\n \"GET /enterprises/{enterprise}/dependabot/alerts\"\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/dependabot/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/dependabot/alerts\"],\n listOrgSecrets: [\"GET /orgs/{org}/dependabot/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/dependabot/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\"\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\"\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories\"\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\"\n ]\n },\n dependencyGraph: {\n createRepositorySnapshot: [\n \"POST /repos/{owner}/{repo}/dependency-graph/snapshots\"\n ],\n diffRange: [\n \"GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}\"\n ],\n exportSbom: [\"GET /repos/{owner}/{repo}/dependency-graph/sbom\"]\n },\n emojis: { get: [\"GET /emojis\"] },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"]\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"]\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"]\n },\n interactions: {\n getRestrictionsForAuthenticatedUser: [\"GET /user/interaction-limits\"],\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\"],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\"],\n getRestrictionsForYourPublicRepos: [\n \"GET /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"getRestrictionsForAuthenticatedUser\"] }\n ],\n removeRestrictionsForAuthenticatedUser: [\"DELETE /user/interaction-limits\"],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\"],\n removeRestrictionsForRepo: [\n \"DELETE /repos/{owner}/{repo}/interaction-limits\"\n ],\n removeRestrictionsForYourPublicRepos: [\n \"DELETE /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"removeRestrictionsForAuthenticatedUser\"] }\n ],\n setRestrictionsForAuthenticatedUser: [\"PUT /user/interaction-limits\"],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\"],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\"],\n setRestrictionsForYourPublicRepos: [\n \"PUT /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"setRestrictionsForAuthenticatedUser\"] }\n ]\n },\n issues: {\n addAssignees: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\"\n ],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n checkUserCanBeAssignedToIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}\"\n ],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\"\n ],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\"\n ],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\n \"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\"\n ],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\"\n ],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\"\n ],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\"\n ],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\"\n ],\n removeAssignees: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\"\n ],\n removeLabel: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\"\n ],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\n \"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\"\n ]\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"]\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\n \"POST /markdown/raw\",\n { headers: { \"content-type\": \"text/plain; charset=utf-8\" } }\n ]\n },\n meta: {\n get: [\"GET /meta\"],\n getAllVersions: [\"GET /versions\"],\n getOctocat: [\"GET /octocat\"],\n getZen: [\"GET /zen\"],\n root: [\"GET /\"]\n },\n migrations: {\n cancelImport: [\n \"DELETE /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import\"\n }\n ],\n deleteArchiveForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/archive\"\n ],\n deleteArchiveForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/archive\"\n ],\n downloadArchiveForOrg: [\n \"GET /orgs/{org}/migrations/{migration_id}/archive\"\n ],\n getArchiveForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/archive\"\n ],\n getCommitAuthors: [\n \"GET /repos/{owner}/{repo}/import/authors\",\n {},\n {\n deprecated: \"octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors\"\n }\n ],\n getImportStatus: [\n \"GET /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status\"\n }\n ],\n getLargeFiles: [\n \"GET /repos/{owner}/{repo}/import/large_files\",\n {},\n {\n deprecated: \"octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files\"\n }\n ],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\"],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\"],\n listForAuthenticatedUser: [\"GET /user/migrations\"],\n listForOrg: [\"GET /orgs/{org}/migrations\"],\n listReposForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/repositories\"\n ],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\"],\n listReposForUser: [\n \"GET /user/migrations/{migration_id}/repositories\",\n {},\n { renamed: [\"migrations\", \"listReposForAuthenticatedUser\"] }\n ],\n mapCommitAuthor: [\n \"PATCH /repos/{owner}/{repo}/import/authors/{author_id}\",\n {},\n {\n deprecated: \"octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author\"\n }\n ],\n setLfsPreference: [\n \"PATCH /repos/{owner}/{repo}/import/lfs\",\n {},\n {\n deprecated: \"octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference\"\n }\n ],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n startImport: [\n \"PUT /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import\"\n }\n ],\n unlockRepoForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\"\n ],\n unlockRepoForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\"\n ],\n updateImport: [\n \"PATCH /repos/{owner}/{repo}/import\",\n {},\n {\n deprecated: \"octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import\"\n }\n ]\n },\n oidc: {\n getOidcCustomSubTemplateForOrg: [\n \"GET /orgs/{org}/actions/oidc/customization/sub\"\n ],\n updateOidcCustomSubTemplateForOrg: [\n \"PUT /orgs/{org}/actions/oidc/customization/sub\"\n ]\n },\n orgs: {\n addSecurityManagerTeam: [\n \"PUT /orgs/{org}/security-managers/teams/{team_slug}\"\n ],\n assignTeamToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\"\n ],\n assignUserToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/users/{username}/{role_id}\"\n ],\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n cancelInvitation: [\"DELETE /orgs/{org}/invitations/{invitation_id}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\n \"PUT /orgs/{org}/outside_collaborators/{username}\"\n ],\n createCustomOrganizationRole: [\"POST /orgs/{org}/organization-roles\"],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createOrUpdateCustomProperties: [\"PATCH /orgs/{org}/properties/schema\"],\n createOrUpdateCustomPropertiesValuesForRepos: [\n \"PATCH /orgs/{org}/properties/values\"\n ],\n createOrUpdateCustomProperty: [\n \"PUT /orgs/{org}/properties/schema/{custom_property_name}\"\n ],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n delete: [\"DELETE /orgs/{org}\"],\n deleteCustomOrganizationRole: [\n \"DELETE /orgs/{org}/organization-roles/{role_id}\"\n ],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n enableOrDisableSecurityProductOnAllOrgRepos: [\n \"POST /orgs/{org}/{security_product}/{enablement}\"\n ],\n get: [\"GET /orgs/{org}\"],\n getAllCustomProperties: [\"GET /orgs/{org}/properties/schema\"],\n getCustomProperty: [\n \"GET /orgs/{org}/properties/schema/{custom_property_name}\"\n ],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getOrgRole: [\"GET /orgs/{org}/organization-roles/{role_id}\"],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n getWebhookConfigForOrg: [\"GET /orgs/{org}/hooks/{hook_id}/config\"],\n getWebhookDelivery: [\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}\"\n ],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listCustomPropertiesValuesForRepos: [\"GET /orgs/{org}/properties/values\"],\n listFailedInvitations: [\"GET /orgs/{org}/failed_invitations\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOrgRoleTeams: [\"GET /orgs/{org}/organization-roles/{role_id}/teams\"],\n listOrgRoleUsers: [\"GET /orgs/{org}/organization-roles/{role_id}/users\"],\n listOrgRoles: [\"GET /orgs/{org}/organization-roles\"],\n listOrganizationFineGrainedPermissions: [\n \"GET /orgs/{org}/organization-fine-grained-permissions\"\n ],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPatGrantRepositories: [\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\"\n ],\n listPatGrantRequestRepositories: [\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\"\n ],\n listPatGrantRequests: [\"GET /orgs/{org}/personal-access-token-requests\"],\n listPatGrants: [\"GET /orgs/{org}/personal-access-tokens\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listSecurityManagerTeams: [\"GET /orgs/{org}/security-managers\"],\n listWebhookDeliveries: [\"GET /orgs/{org}/hooks/{hook_id}/deliveries\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n patchCustomOrganizationRole: [\n \"PATCH /orgs/{org}/organization-roles/{role_id}\"\n ],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\"\n ],\n removeCustomProperty: [\n \"DELETE /orgs/{org}/properties/schema/{custom_property_name}\"\n ],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\n \"DELETE /orgs/{org}/outside_collaborators/{username}\"\n ],\n removePublicMembershipForAuthenticatedUser: [\n \"DELETE /orgs/{org}/public_members/{username}\"\n ],\n removeSecurityManagerTeam: [\n \"DELETE /orgs/{org}/security-managers/teams/{team_slug}\"\n ],\n reviewPatGrantRequest: [\n \"POST /orgs/{org}/personal-access-token-requests/{pat_request_id}\"\n ],\n reviewPatGrantRequestsInBulk: [\n \"POST /orgs/{org}/personal-access-token-requests\"\n ],\n revokeAllOrgRolesTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}\"\n ],\n revokeAllOrgRolesUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}\"\n ],\n revokeOrgRoleTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\"\n ],\n revokeOrgRoleUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}\"\n ],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\n \"PUT /orgs/{org}/public_members/{username}\"\n ],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateMembershipForAuthenticatedUser: [\n \"PATCH /user/memberships/orgs/{org}\"\n ],\n updatePatAccess: [\"POST /orgs/{org}/personal-access-tokens/{pat_id}\"],\n updatePatAccesses: [\"POST /orgs/{org}/personal-access-tokens\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"],\n updateWebhookConfigForOrg: [\"PATCH /orgs/{org}/hooks/{hook_id}/config\"]\n },\n packages: {\n deletePackageForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}\"\n ],\n deletePackageForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}\"\n ],\n deletePackageForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}\"\n ],\n deletePackageVersionForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n deletePackageVersionForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n deletePackageVersionForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n getAllPackageVersionsForAPackageOwnedByAnOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n {},\n { renamed: [\"packages\", \"getAllPackageVersionsForPackageOwnedByOrg\"] }\n ],\n getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n {},\n {\n renamed: [\n \"packages\",\n \"getAllPackageVersionsForPackageOwnedByAuthenticatedUser\"\n ]\n }\n ],\n getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\"\n ],\n getAllPackageVersionsForPackageOwnedByOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\"\n ],\n getAllPackageVersionsForPackageOwnedByUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions\"\n ],\n getPackageForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}\"\n ],\n getPackageForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}\"\n ],\n getPackageForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}\"\n ],\n getPackageVersionForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n getPackageVersionForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n getPackageVersionForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\"\n ],\n listDockerMigrationConflictingPackagesForAuthenticatedUser: [\n \"GET /user/docker/conflicts\"\n ],\n listDockerMigrationConflictingPackagesForOrganization: [\n \"GET /orgs/{org}/docker/conflicts\"\n ],\n listDockerMigrationConflictingPackagesForUser: [\n \"GET /users/{username}/docker/conflicts\"\n ],\n listPackagesForAuthenticatedUser: [\"GET /user/packages\"],\n listPackagesForOrganization: [\"GET /orgs/{org}/packages\"],\n listPackagesForUser: [\"GET /users/{username}/packages\"],\n restorePackageForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/restore{?token}\"\n ],\n restorePackageForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}\"\n ],\n restorePackageForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}\"\n ],\n restorePackageVersionForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"\n ],\n restorePackageVersionForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"\n ],\n restorePackageVersionForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\"\n ]\n },\n projects: {\n addCollaborator: [\"PUT /projects/{project_id}/collaborators/{username}\"],\n createCard: [\"POST /projects/columns/{column_id}/cards\"],\n createColumn: [\"POST /projects/{project_id}/columns\"],\n createForAuthenticatedUser: [\"POST /user/projects\"],\n createForOrg: [\"POST /orgs/{org}/projects\"],\n createForRepo: [\"POST /repos/{owner}/{repo}/projects\"],\n delete: [\"DELETE /projects/{project_id}\"],\n deleteCard: [\"DELETE /projects/columns/cards/{card_id}\"],\n deleteColumn: [\"DELETE /projects/columns/{column_id}\"],\n get: [\"GET /projects/{project_id}\"],\n getCard: [\"GET /projects/columns/cards/{card_id}\"],\n getColumn: [\"GET /projects/columns/{column_id}\"],\n getPermissionForUser: [\n \"GET /projects/{project_id}/collaborators/{username}/permission\"\n ],\n listCards: [\"GET /projects/columns/{column_id}/cards\"],\n listCollaborators: [\"GET /projects/{project_id}/collaborators\"],\n listColumns: [\"GET /projects/{project_id}/columns\"],\n listForOrg: [\"GET /orgs/{org}/projects\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/projects\"],\n listForUser: [\"GET /users/{username}/projects\"],\n moveCard: [\"POST /projects/columns/cards/{card_id}/moves\"],\n moveColumn: [\"POST /projects/columns/{column_id}/moves\"],\n removeCollaborator: [\n \"DELETE /projects/{project_id}/collaborators/{username}\"\n ],\n update: [\"PATCH /projects/{project_id}\"],\n updateCard: [\"PATCH /projects/columns/cards/{card_id}\"],\n updateColumn: [\"PATCH /projects/columns/{column_id}\"]\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\"\n ],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\"\n ],\n deletePendingReview: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"\n ],\n deleteReviewComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\"\n ],\n dismissReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\"\n ],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"\n ],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\"\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"\n ],\n listReviewComments: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\"\n ],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"\n ],\n requestReviewers: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\"\n ],\n submitReview: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\"\n ],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\"\n ],\n updateReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\"\n ],\n updateReviewComment: [\n \"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\"\n ]\n },\n rateLimit: { get: [\"GET /rate_limit\"] },\n reactions: {\n createForCommitComment: [\n \"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\"\n ],\n createForIssue: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\"\n ],\n createForIssueComment: [\n \"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\"\n ],\n createForPullRequestReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\"\n ],\n createForRelease: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/reactions\"\n ],\n createForTeamDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\"\n ],\n createForTeamDiscussionInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\"\n ],\n deleteForCommitComment: [\n \"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\"\n ],\n deleteForIssue: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\"\n ],\n deleteForIssueComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\"\n ],\n deleteForPullRequestComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\"\n ],\n deleteForRelease: [\n \"DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}\"\n ],\n deleteForTeamDiscussion: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\"\n ],\n deleteForTeamDiscussionComment: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\"\n ],\n listForCommitComment: [\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\"\n ],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\"],\n listForIssueComment: [\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\"\n ],\n listForPullRequestReviewComment: [\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\"\n ],\n listForRelease: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\"\n ],\n listForTeamDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\"\n ],\n listForTeamDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\"\n ]\n },\n repos: {\n acceptInvitation: [\n \"PATCH /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"acceptInvitationForAuthenticatedUser\"] }\n ],\n acceptInvitationForAuthenticatedUser: [\n \"PATCH /user/repository_invitations/{invitation_id}\"\n ],\n addAppAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" }\n ],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" }\n ],\n addTeamAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" }\n ],\n addUserAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" }\n ],\n cancelPagesDeployment: [\n \"POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel\"\n ],\n checkAutomatedSecurityFixes: [\n \"GET /repos/{owner}/{repo}/automated-security-fixes\"\n ],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkVulnerabilityAlerts: [\n \"GET /repos/{owner}/{repo}/vulnerability-alerts\"\n ],\n codeownersErrors: [\"GET /repos/{owner}/{repo}/codeowners/errors\"],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n compareCommitsWithBasehead: [\n \"GET /repos/{owner}/{repo}/compare/{basehead}\"\n ],\n createAutolink: [\"POST /repos/{owner}/{repo}/autolinks\"],\n createCommitComment: [\n \"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\"\n ],\n createCommitSignatureProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\"\n ],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentBranchPolicy: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\"\n ],\n createDeploymentProtectionRule: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\"\n ],\n createDeploymentStatus: [\n \"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"\n ],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateCustomPropertiesValues: [\n \"PATCH /repos/{owner}/{repo}/properties/values\"\n ],\n createOrUpdateEnvironment: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}\"\n ],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createOrgRuleset: [\"POST /orgs/{org}/rulesets\"],\n createPagesDeployment: [\"POST /repos/{owner}/{repo}/pages/deployments\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\"],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createRepoRuleset: [\"POST /repos/{owner}/{repo}/rulesets\"],\n createTagProtection: [\"POST /repos/{owner}/{repo}/tags/protection\"],\n createUsingTemplate: [\n \"POST /repos/{template_owner}/{template_repo}/generate\"\n ],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n declineInvitation: [\n \"DELETE /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"declineInvitationForAuthenticatedUser\"] }\n ],\n declineInvitationForAuthenticatedUser: [\n \"DELETE /user/repository_invitations/{invitation_id}\"\n ],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"\n ],\n deleteAdminBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"\n ],\n deleteAnEnvironment: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}\"\n ],\n deleteAutolink: [\"DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n deleteBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\"\n ],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\"\n ],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\n \"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\"\n ],\n deleteDeploymentBranchPolicy: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\"\n ],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\n \"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\"\n ],\n deleteOrgRuleset: [\"DELETE /orgs/{org}/rulesets/{ruleset_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\"],\n deletePullRequestReviewProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"\n ],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\n \"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\"\n ],\n deleteRepoRuleset: [\"DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n deleteTagProtection: [\n \"DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}\"\n ],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\n \"DELETE /repos/{owner}/{repo}/automated-security-fixes\"\n ],\n disableDeploymentProtectionRule: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\"\n ],\n disablePrivateVulnerabilityReporting: [\n \"DELETE /repos/{owner}/{repo}/private-vulnerability-reporting\"\n ],\n disableVulnerabilityAlerts: [\n \"DELETE /repos/{owner}/{repo}/vulnerability-alerts\"\n ],\n downloadArchive: [\n \"GET /repos/{owner}/{repo}/zipball/{ref}\",\n {},\n { renamed: [\"repos\", \"downloadZipballArchive\"] }\n ],\n downloadTarballArchive: [\"GET /repos/{owner}/{repo}/tarball/{ref}\"],\n downloadZipballArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\"],\n enableAutomatedSecurityFixes: [\n \"PUT /repos/{owner}/{repo}/automated-security-fixes\"\n ],\n enablePrivateVulnerabilityReporting: [\n \"PUT /repos/{owner}/{repo}/private-vulnerability-reporting\"\n ],\n enableVulnerabilityAlerts: [\n \"PUT /repos/{owner}/{repo}/vulnerability-alerts\"\n ],\n generateReleaseNotes: [\n \"POST /repos/{owner}/{repo}/releases/generate-notes\"\n ],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\"\n ],\n getAdminBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"\n ],\n getAllDeploymentProtectionRules: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\"\n ],\n getAllEnvironments: [\"GET /repos/{owner}/{repo}/environments\"],\n getAllStatusCheckContexts: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\"\n ],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\"],\n getAppsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\"\n ],\n getAutolink: [\"GET /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection\"\n ],\n getBranchRules: [\"GET /repos/{owner}/{repo}/rules/branches/{branch}\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\n \"GET /repos/{owner}/{repo}/collaborators/{username}/permission\"\n ],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\"\n ],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\"],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getCustomDeploymentProtectionRule: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\"\n ],\n getCustomPropertiesValues: [\"GET /repos/{owner}/{repo}/properties/values\"],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentBranchPolicy: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\"\n ],\n getDeploymentStatus: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\"\n ],\n getEnvironment: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}\"\n ],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getOrgRuleSuite: [\"GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}\"],\n getOrgRuleSuites: [\"GET /orgs/{org}/rulesets/rule-suites\"],\n getOrgRuleset: [\"GET /orgs/{org}/rulesets/{ruleset_id}\"],\n getOrgRulesets: [\"GET /orgs/{org}/rulesets\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getPagesDeployment: [\n \"GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}\"\n ],\n getPagesHealthCheck: [\"GET /repos/{owner}/{repo}/pages/health\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"\n ],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getReadmeInDirectory: [\"GET /repos/{owner}/{repo}/readme/{dir}\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getRepoRuleSuite: [\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}\"\n ],\n getRepoRuleSuites: [\"GET /repos/{owner}/{repo}/rulesets/rule-suites\"],\n getRepoRuleset: [\"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n getRepoRulesets: [\"GET /repos/{owner}/{repo}/rulesets\"],\n getStatusChecksProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"\n ],\n getTeamsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\"\n ],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\"\n ],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n getWebhookConfigForRepo: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/config\"\n ],\n getWebhookDelivery: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}\"\n ],\n listActivities: [\"GET /repos/{owner}/{repo}/activity\"],\n listAutolinks: [\"GET /repos/{owner}/{repo}/autolinks\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\"\n ],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\"\n ],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\"\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listCustomDeploymentRuleIntegrations: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\"\n ],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentBranchPolicies: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\"\n ],\n listDeploymentStatuses: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\"\n ],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\"\n ],\n listReleaseAssets: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\"\n ],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTagProtection: [\"GET /repos/{owner}/{repo}/tags/protection\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhookDeliveries: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\"\n ],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n mergeUpstream: [\"POST /repos/{owner}/{repo}/merge-upstream\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\"\n ],\n removeAppAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" }\n ],\n removeCollaborator: [\n \"DELETE /repos/{owner}/{repo}/collaborators/{username}\"\n ],\n removeStatusCheckContexts: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" }\n ],\n removeStatusCheckProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"\n ],\n removeTeamAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" }\n ],\n removeUserAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" }\n ],\n renameBranch: [\"POST /repos/{owner}/{repo}/branches/{branch}/rename\"],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\"],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\"\n ],\n setAppAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" }\n ],\n setStatusCheckContexts: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" }\n ],\n setTeamAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" }\n ],\n setUserAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" }\n ],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection\"\n ],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateDeploymentBranchPolicy: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\"\n ],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\n \"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\"\n ],\n updateOrgRuleset: [\"PUT /orgs/{org}/rulesets/{ruleset_id}\"],\n updatePullRequestReviewProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\"\n ],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\n \"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\"\n ],\n updateRepoRuleset: [\"PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n updateStatusCheckPotection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n {},\n { renamed: [\"repos\", \"updateStatusCheckProtection\"] }\n ],\n updateStatusCheckProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\"\n ],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n updateWebhookConfigForRepo: [\n \"PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config\"\n ],\n uploadReleaseAsset: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\",\n { baseUrl: \"https://uploads.github.com\" }\n ]\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\"],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\"],\n users: [\"GET /search/users\"]\n },\n secretScanning: {\n getAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"\n ],\n listAlertsForEnterprise: [\n \"GET /enterprises/{enterprise}/secret-scanning/alerts\"\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/secret-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts\"],\n listLocationsForAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\"\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\"\n ]\n },\n securityAdvisories: {\n createFork: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks\"\n ],\n createPrivateVulnerabilityReport: [\n \"POST /repos/{owner}/{repo}/security-advisories/reports\"\n ],\n createRepositoryAdvisory: [\n \"POST /repos/{owner}/{repo}/security-advisories\"\n ],\n createRepositoryAdvisoryCveRequest: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve\"\n ],\n getGlobalAdvisory: [\"GET /advisories/{ghsa_id}\"],\n getRepositoryAdvisory: [\n \"GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}\"\n ],\n listGlobalAdvisories: [\"GET /advisories\"],\n listOrgRepositoryAdvisories: [\"GET /orgs/{org}/security-advisories\"],\n listRepositoryAdvisories: [\"GET /repos/{owner}/{repo}/security-advisories\"],\n updateRepositoryAdvisory: [\n \"PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}\"\n ]\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\"\n ],\n addOrUpdateProjectPermissionsInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}\"\n ],\n addOrUpdateRepoPermissionsInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"\n ],\n checkPermissionsForProjectInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/projects/{project_id}\"\n ],\n checkPermissionsForRepoInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"\n ],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"\n ],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"\n ],\n deleteDiscussionInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"\n ],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"\n ],\n getDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"\n ],\n getMembershipForUserInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\"\n ],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\"\n ],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/invitations\"\n ],\n listProjectsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/projects\"],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\"\n ],\n removeProjectInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}\"\n ],\n removeRepoInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\"\n ],\n updateDiscussionCommentInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\"\n ],\n updateDiscussionInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\"\n ],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"]\n },\n users: {\n addEmailForAuthenticated: [\n \"POST /user/emails\",\n {},\n { renamed: [\"users\", \"addEmailForAuthenticatedUser\"] }\n ],\n addEmailForAuthenticatedUser: [\"POST /user/emails\"],\n addSocialAccountForAuthenticatedUser: [\"POST /user/social_accounts\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\n \"POST /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"createGpgKeyForAuthenticatedUser\"] }\n ],\n createGpgKeyForAuthenticatedUser: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\n \"POST /user/keys\",\n {},\n { renamed: [\"users\", \"createPublicSshKeyForAuthenticatedUser\"] }\n ],\n createPublicSshKeyForAuthenticatedUser: [\"POST /user/keys\"],\n createSshSigningKeyForAuthenticatedUser: [\"POST /user/ssh_signing_keys\"],\n deleteEmailForAuthenticated: [\n \"DELETE /user/emails\",\n {},\n { renamed: [\"users\", \"deleteEmailForAuthenticatedUser\"] }\n ],\n deleteEmailForAuthenticatedUser: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\n \"DELETE /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"deleteGpgKeyForAuthenticatedUser\"] }\n ],\n deleteGpgKeyForAuthenticatedUser: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\n \"DELETE /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"deletePublicSshKeyForAuthenticatedUser\"] }\n ],\n deletePublicSshKeyForAuthenticatedUser: [\"DELETE /user/keys/{key_id}\"],\n deleteSocialAccountForAuthenticatedUser: [\"DELETE /user/social_accounts\"],\n deleteSshSigningKeyForAuthenticatedUser: [\n \"DELETE /user/ssh_signing_keys/{ssh_signing_key_id}\"\n ],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\n \"GET /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"getGpgKeyForAuthenticatedUser\"] }\n ],\n getGpgKeyForAuthenticatedUser: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\n \"GET /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"getPublicSshKeyForAuthenticatedUser\"] }\n ],\n getPublicSshKeyForAuthenticatedUser: [\"GET /user/keys/{key_id}\"],\n getSshSigningKeyForAuthenticatedUser: [\n \"GET /user/ssh_signing_keys/{ssh_signing_key_id}\"\n ],\n list: [\"GET /users\"],\n listBlockedByAuthenticated: [\n \"GET /user/blocks\",\n {},\n { renamed: [\"users\", \"listBlockedByAuthenticatedUser\"] }\n ],\n listBlockedByAuthenticatedUser: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\n \"GET /user/emails\",\n {},\n { renamed: [\"users\", \"listEmailsForAuthenticatedUser\"] }\n ],\n listEmailsForAuthenticatedUser: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\n \"GET /user/following\",\n {},\n { renamed: [\"users\", \"listFollowedByAuthenticatedUser\"] }\n ],\n listFollowedByAuthenticatedUser: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\n \"GET /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"listGpgKeysForAuthenticatedUser\"] }\n ],\n listGpgKeysForAuthenticatedUser: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\n \"GET /user/public_emails\",\n {},\n { renamed: [\"users\", \"listPublicEmailsForAuthenticatedUser\"] }\n ],\n listPublicEmailsForAuthenticatedUser: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\n \"GET /user/keys\",\n {},\n { renamed: [\"users\", \"listPublicSshKeysForAuthenticatedUser\"] }\n ],\n listPublicSshKeysForAuthenticatedUser: [\"GET /user/keys\"],\n listSocialAccountsForAuthenticatedUser: [\"GET /user/social_accounts\"],\n listSocialAccountsForUser: [\"GET /users/{username}/social_accounts\"],\n listSshSigningKeysForAuthenticatedUser: [\"GET /user/ssh_signing_keys\"],\n listSshSigningKeysForUser: [\"GET /users/{username}/ssh_signing_keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\n \"PATCH /user/email/visibility\",\n {},\n { renamed: [\"users\", \"setPrimaryEmailVisibilityForAuthenticatedUser\"] }\n ],\n setPrimaryEmailVisibilityForAuthenticatedUser: [\n \"PATCH /user/email/visibility\"\n ],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"]\n }\n};\nvar endpoints_default = Endpoints;\n\n// pkg/dist-src/endpoints-to-methods.js\nvar endpointMethodsMap = /* @__PURE__ */ new Map();\nfor (const [scope, endpoints] of Object.entries(endpoints_default)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign(\n {\n method,\n url\n },\n defaults\n );\n if (!endpointMethodsMap.has(scope)) {\n endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());\n }\n endpointMethodsMap.get(scope).set(methodName, {\n scope,\n methodName,\n endpointDefaults,\n decorations\n });\n }\n}\nvar handler = {\n has({ scope }, methodName) {\n return endpointMethodsMap.get(scope).has(methodName);\n },\n getOwnPropertyDescriptor(target, methodName) {\n return {\n value: this.get(target, methodName),\n // ensures method is in the cache\n configurable: true,\n writable: true,\n enumerable: true\n };\n },\n defineProperty(target, methodName, descriptor) {\n Object.defineProperty(target.cache, methodName, descriptor);\n return true;\n },\n deleteProperty(target, methodName) {\n delete target.cache[methodName];\n return true;\n },\n ownKeys({ scope }) {\n return [...endpointMethodsMap.get(scope).keys()];\n },\n set(target, methodName, value) {\n return target.cache[methodName] = value;\n },\n get({ octokit, scope, cache }, methodName) {\n if (cache[methodName]) {\n return cache[methodName];\n }\n const method = endpointMethodsMap.get(scope).get(methodName);\n if (!method) {\n return void 0;\n }\n const { endpointDefaults, decorations } = method;\n if (decorations) {\n cache[methodName] = decorate(\n octokit,\n scope,\n methodName,\n endpointDefaults,\n decorations\n );\n } else {\n cache[methodName] = octokit.request.defaults(endpointDefaults);\n }\n return cache[methodName];\n }\n};\nfunction endpointsToMethods(octokit) {\n const newMethods = {};\n for (const scope of endpointMethodsMap.keys()) {\n newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);\n }\n return newMethods;\n}\nfunction decorate(octokit, scope, methodName, defaults, decorations) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n function withDecorations(...args) {\n let options = requestWithDefaults.endpoint.merge(...args);\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: void 0\n });\n return requestWithDefaults(options);\n }\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(\n `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`\n );\n }\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n if (decorations.renamedParameters) {\n const options2 = requestWithDefaults.endpoint.merge(...args);\n for (const [name, alias] of Object.entries(\n decorations.renamedParameters\n )) {\n if (name in options2) {\n octokit.log.warn(\n `\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`\n );\n if (!(alias in options2)) {\n options2[alias] = options2[name];\n }\n delete options2[name];\n }\n }\n return requestWithDefaults(options2);\n }\n return requestWithDefaults(...args);\n }\n return Object.assign(withDecorations, requestWithDefaults);\n}\n\n// pkg/dist-src/index.js\nfunction restEndpointMethods(octokit) {\n const api = endpointsToMethods(octokit);\n return {\n rest: api\n };\n}\nrestEndpointMethods.VERSION = VERSION;\nfunction legacyRestEndpointMethods(octokit) {\n const api = endpointsToMethods(octokit);\n return {\n ...api,\n rest: api\n };\n}\nlegacyRestEndpointMethods.VERSION = VERSION;\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n legacyRestEndpointMethods,\n restEndpointMethods\n});\n","\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n RequestError: () => RequestError\n});\nmodule.exports = __toCommonJS(dist_src_exports);\nvar import_deprecation = require(\"deprecation\");\nvar import_once = __toESM(require(\"once\"));\nvar logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));\nvar logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));\nvar RequestError = class extends Error {\n constructor(message, statusCode, options) {\n super(message);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = \"HttpError\";\n this.status = statusCode;\n let headers;\n if (\"headers\" in options && typeof options.headers !== \"undefined\") {\n headers = options.headers;\n }\n if (\"response\" in options) {\n this.response = options.response;\n headers = options.response.headers;\n }\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(\n /(? {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// pkg/dist-src/index.js\nvar dist_src_exports = {};\n__export(dist_src_exports, {\n request: () => request\n});\nmodule.exports = __toCommonJS(dist_src_exports);\nvar import_endpoint = require(\"@octokit/endpoint\");\nvar import_universal_user_agent = require(\"universal-user-agent\");\n\n// pkg/dist-src/version.js\nvar VERSION = \"8.4.1\";\n\n// pkg/dist-src/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null)\n return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\")\n return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null)\n return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/fetch-wrapper.js\nvar import_request_error = require(\"@octokit/request-error\");\n\n// pkg/dist-src/get-buffer-response.js\nfunction getBufferResponse(response) {\n return response.arrayBuffer();\n}\n\n// pkg/dist-src/fetch-wrapper.js\nfunction fetchWrapper(requestOptions) {\n var _a, _b, _c, _d;\n const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;\n const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;\n if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {\n requestOptions.body = JSON.stringify(requestOptions.body);\n }\n let headers = {};\n let status;\n let url;\n let { fetch } = globalThis;\n if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {\n fetch = requestOptions.request.fetch;\n }\n if (!fetch) {\n throw new Error(\n \"fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing\"\n );\n }\n return fetch(requestOptions.url, {\n method: requestOptions.method,\n body: requestOptions.body,\n redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect,\n headers: requestOptions.headers,\n signal: (_d = requestOptions.request) == null ? void 0 : _d.signal,\n // duplex must be set if request.body is ReadableStream or Async Iterables.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.\n ...requestOptions.body && { duplex: \"half\" }\n }).then(async (response) => {\n url = response.url;\n status = response.status;\n for (const keyAndValue of response.headers) {\n headers[keyAndValue[0]] = keyAndValue[1];\n }\n if (\"deprecation\" in headers) {\n const matches = headers.link && headers.link.match(/<([^<>]+)>; rel=\"deprecation\"/);\n const deprecationLink = matches && matches.pop();\n log.warn(\n `[@octokit/request] \"${requestOptions.method} ${requestOptions.url}\" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : \"\"}`\n );\n }\n if (status === 204 || status === 205) {\n return;\n }\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return;\n }\n throw new import_request_error.RequestError(response.statusText, status, {\n response: {\n url,\n status,\n headers,\n data: void 0\n },\n request: requestOptions\n });\n }\n if (status === 304) {\n throw new import_request_error.RequestError(\"Not modified\", status, {\n response: {\n url,\n status,\n headers,\n data: await getResponseData(response)\n },\n request: requestOptions\n });\n }\n if (status >= 400) {\n const data = await getResponseData(response);\n const error = new import_request_error.RequestError(toErrorMessage(data), status, {\n response: {\n url,\n status,\n headers,\n data\n },\n request: requestOptions\n });\n throw error;\n }\n return parseSuccessResponseBody ? await getResponseData(response) : response.body;\n }).then((data) => {\n return {\n status,\n url,\n headers,\n data\n };\n }).catch((error) => {\n if (error instanceof import_request_error.RequestError)\n throw error;\n else if (error.name === \"AbortError\")\n throw error;\n let message = error.message;\n if (error.name === \"TypeError\" && \"cause\" in error) {\n if (error.cause instanceof Error) {\n message = error.cause.message;\n } else if (typeof error.cause === \"string\") {\n message = error.cause;\n }\n }\n throw new import_request_error.RequestError(message, 500, {\n request: requestOptions\n });\n });\n}\nasync function getResponseData(response) {\n const contentType = response.headers.get(\"content-type\");\n if (/application\\/json/.test(contentType)) {\n return response.json().catch(() => response.text()).catch(() => \"\");\n }\n if (!contentType || /^text\\/|charset=utf-8$/.test(contentType)) {\n return response.text();\n }\n return getBufferResponse(response);\n}\nfunction toErrorMessage(data) {\n if (typeof data === \"string\")\n return data;\n let suffix;\n if (\"documentation_url\" in data) {\n suffix = ` - ${data.documentation_url}`;\n } else {\n suffix = \"\";\n }\n if (\"message\" in data) {\n if (Array.isArray(data.errors)) {\n return `${data.message}: ${data.errors.map(JSON.stringify).join(\", \")}${suffix}`;\n }\n return `${data.message}${suffix}`;\n }\n return `Unknown error: ${JSON.stringify(data)}`;\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint2 = oldEndpoint.defaults(newDefaults);\n const newApi = function(route, parameters) {\n const endpointOptions = endpoint2.merge(route, parameters);\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint2.parse(endpointOptions));\n }\n const request2 = (route2, parameters2) => {\n return fetchWrapper(\n endpoint2.parse(endpoint2.merge(route2, parameters2))\n );\n };\n Object.assign(request2, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n return endpointOptions.request.hook(request2, endpointOptions);\n };\n return Object.assign(newApi, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n}\n\n// pkg/dist-src/index.js\nvar request = withDefaults(import_endpoint.endpoint, {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`\n }\n});\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n request\n});\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","var register = require(\"./lib/register\");\nvar addHook = require(\"./lib/add\");\nvar removeHook = require(\"./lib/remove\");\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nvar bind = Function.bind;\nvar bindable = bind.bind(bind);\n\nfunction bindApi(hook, state, name) {\n var removeHookRef = bindable(removeHook, null).apply(\n null,\n name ? [state, name] : [state]\n );\n hook.api = { remove: removeHookRef };\n hook.remove = removeHookRef;\n [\"before\", \"error\", \"after\", \"wrap\"].forEach(function (kind) {\n var args = name ? [state, kind, name] : [state, kind];\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);\n });\n}\n\nfunction HookSingular() {\n var singularHookName = \"h\";\n var singularHookState = {\n registry: {},\n };\n var singularHook = register.bind(null, singularHookState, singularHookName);\n bindApi(singularHook, singularHookState, singularHookName);\n return singularHook;\n}\n\nfunction HookCollection() {\n var state = {\n registry: {},\n };\n\n var hook = register.bind(null, state);\n bindApi(hook, state);\n\n return hook;\n}\n\nvar collectionHookDeprecationMessageDisplayed = false;\nfunction Hook() {\n if (!collectionHookDeprecationMessageDisplayed) {\n console.warn(\n '[before-after-hook]: \"Hook()\" repurposing warning, use \"Hook.Collection()\". Read more: https://git.io/upgrade-before-after-hook-to-1.4'\n );\n collectionHookDeprecationMessageDisplayed = true;\n }\n return HookCollection();\n}\n\nHook.Singular = HookSingular.bind();\nHook.Collection = HookCollection.bind();\n\nmodule.exports = Hook;\n// expose constructors as a named property for TypeScript\nmodule.exports.Hook = Hook;\nmodule.exports.Singular = Hook.Singular;\nmodule.exports.Collection = Hook.Collection;\n","module.exports = addHook;\n\nfunction addHook(state, kind, name, hook) {\n var orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = function (method, options) {\n var result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then(function (result_) {\n result = result_;\n return orig(result, options);\n })\n .then(function () {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = function (method, options) {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch(function (error) {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n","module.exports = register;\n\nfunction register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce(function (callback, name) {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(function () {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce(function (method, registered) {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n","module.exports = removeHook;\n\nfunction removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n var index = state.registry[name]\n .map(function (registered) {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n","'use strict';\nmodule.exports = function (str, sep) {\n\tif (typeof str !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\tsep = typeof sep === 'undefined' ? '_' : sep;\n\n\treturn str\n\t\t.replace(/([a-z\\d])([A-Z])/g, '$1' + sep + '$2')\n\t\t.replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, '$1' + sep + '$2')\n\t\t.toLowerCase();\n};\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass Deprecation extends Error {\n constructor(message) {\n super(message); // Maintains proper stack trace (only available on V8)\n\n /* istanbul ignore next */\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n this.name = 'Deprecation';\n }\n\n}\n\nexports.Deprecation = Deprecation;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"MAX\", {\n enumerable: true,\n get: function () {\n return _max.default;\n }\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v1ToV6\", {\n enumerable: true,\n get: function () {\n return _v1ToV.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"v6\", {\n enumerable: true,\n get: function () {\n return _v5.default;\n }\n});\nObject.defineProperty(exports, \"v6ToV1\", {\n enumerable: true,\n get: function () {\n return _v6ToV.default;\n }\n});\nObject.defineProperty(exports, \"v7\", {\n enumerable: true,\n get: function () {\n return _v6.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\nvar _max = _interopRequireDefault(require(\"./max.js\"));\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\nvar _v5 = _interopRequireDefault(require(\"./v6.js\"));\nvar _v6ToV = _interopRequireDefault(require(\"./v6ToV1.js\"));\nvar _v6 = _interopRequireDefault(require(\"./v7.js\"));\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nvar _version = _interopRequireDefault(require(\"./version.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction md5(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('md5').update(bytes).digest();\n}\nvar _default = exports.default = md5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nvar _default = exports.default = {\n randomUUID: _nodeCrypto.default.randomUUID\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = '00000000-0000-0000-0000-000000000000';","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n const arr = new Uint8Array(16);\n\n // Parse ########-....-....-....-............\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff;\n\n // Parse ........-####-....-....-............\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff;\n\n // Parse ........-....-####-....-............\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff;\n\n // Parse ........-....-....-####-............\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff;\n\n // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\nvar _default = exports.default = parse;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\nlet poolPtr = rnds8Pool.length;\nfunction rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n _nodeCrypto.default.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _nodeCrypto = _interopRequireDefault(require(\"node:crypto\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n return _nodeCrypto.default.createHash('sha1').update(bytes).digest();\n}\nvar _default = exports.default = sha1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nvar _default = exports.default = stringify;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nlet _nodeId;\nlet _clockseq;\n\n// Previous uuid creation time\nlet _lastMSecs = 0;\nlet _lastNSecs = 0;\n\n// See https://github.com/uuidjs/uuid for API details\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node;\n let clockseq = options.clockseq;\n\n // v1 only: Use cached `node` and `clockseq` values\n if (!options._v6) {\n if (!node) {\n node = _nodeId;\n }\n if (clockseq == null) {\n clockseq = _clockseq;\n }\n }\n\n // Handle cases where we need entropy. We do this lazily to minimize issues\n // related to insufficient system entropy. See #189\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n // Randomize node\n if (node == null) {\n node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n\n // v1 only: cache node value for reuse\n if (!_nodeId && !options._v6) {\n // per RFC4122 4.5: Set MAC multicast bit (v1 only)\n node[0] |= 0x01; // Set multicast bit\n\n _nodeId = node;\n }\n }\n\n // Randomize clockseq\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n if (_clockseq === undefined && !options._v6) {\n _clockseq = clockseq;\n }\n }\n }\n\n // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is\n // handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n let msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v1;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v1ToV6;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v1 UUID to a v6 UUID\n *\n * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6\n * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v1ToV6(uuid) {\n const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v6Bytes = _v1ToV6(v1Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes;\n}\n\n// Do the field transformation needed for v1 -> v6\nfunction _v1ToV6(v1Bytes, randomize = false) {\n return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = exports.default = v3;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\nvar _stringify = require(\"./stringify.js\");\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n return bytes;\n}\nconst DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nconst URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n }\n\n // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n }\n\n // Function#name is not settable on some platforms (#270)\n try {\n generateUUID.name = name;\n } catch (err) {}\n\n // For CommonJS default export support\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _native = _interopRequireDefault(require(\"./native.js\"));\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || _rng.default)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(rnds);\n}\nvar _default = exports.default = v4;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = exports.default = v5;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6;\nvar _stringify = require(\"./stringify.js\");\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\nvar _v1ToV = _interopRequireDefault(require(\"./v1ToV6.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n *\n * @param {object} options\n * @param {Uint8Array=} buf\n * @param {number=} offset\n * @returns\n */\nfunction v6(options = {}, buf, offset = 0) {\n // v6 is v1 with different field layout, so we start with a v1 UUID, albeit\n // with slightly different behavior around how the clock_seq and node fields\n // are randomized, which is why we call v1 with _v6: true.\n let bytes = (0, _v.default)({\n ...options,\n _v6: true\n }, new Uint8Array(16));\n\n // Reorder the fields to v6 layout.\n bytes = (0, _v1ToV.default)(bytes);\n\n // Return as a byte array if requested\n if (buf) {\n for (let i = 0; i < 16; i++) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, _stringify.unsafeStringify)(bytes);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = v6ToV1;\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * Convert a v6 UUID to a v1 UUID\n *\n * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6\n * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg\n * (string or Uint8Array)\n */\nfunction v6ToV1(uuid) {\n const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;\n const v1Bytes = _v6ToV1(v6Bytes);\n return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes;\n}\n\n// Do the field transformation needed for v6 -> v1\nfunction _v6ToV1(v6Bytes) {\n return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\nvar _stringify = require(\"./stringify.js\");\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\n/**\n * UUID V7 - Unix Epoch time-based UUID\n *\n * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This\n * implementation of V7 is based on the accepted, though not yet approved,\n * revisions.\n *\n * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique\n * IDentifiers (UUIDs)\n\n *\n * Sample V7 value:\n * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value\n *\n * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref:\n * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1\n *\n * 0 1 2 3 0 1 2 3 4 5 6\n * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | unix_ts_ms | ver | seq_hi |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * |var| seq_low | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | rand |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n *\n * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit\n * seq_low, and randomly initialized upon timestamp change. 31 bit counter size\n * was selected as any bitwise operations in node are done as _signed_ 32 bit\n * ints. we exclude the sign bit.\n */\n\nlet _seqLow = null;\nlet _seqHigh = null;\nlet _msecs = 0;\nfunction v7(options, buf, offset) {\n options = options || {};\n\n // initialize buffer and pointer\n let i = buf && offset || 0;\n const b = buf || new Uint8Array(16);\n\n // rnds is Uint8Array(16) filled with random bytes\n const rnds = options.random || (options.rng || _rng.default)();\n\n // milliseconds since unix epoch, 1970-01-01 00:00\n const msecs = options.msecs !== undefined ? options.msecs : Date.now();\n\n // seq is user provided 31 bit counter\n let seq = options.seq !== undefined ? options.seq : null;\n\n // initialize local seq high/low parts\n let seqHigh = _seqHigh;\n let seqLow = _seqLow;\n\n // check if clock has advanced and user has not provided msecs\n if (msecs > _msecs && options.msecs === undefined) {\n _msecs = msecs;\n\n // unless user provided seq, reset seq parts\n if (seq !== null) {\n seqHigh = null;\n seqLow = null;\n }\n }\n\n // if we have a user provided seq\n if (seq !== null) {\n // trim provided seq to 31 bits of value, avoiding overflow\n if (seq > 0x7fffffff) {\n seq = 0x7fffffff;\n }\n\n // split provided seq into high/low parts\n seqHigh = seq >>> 19 & 0xfff;\n seqLow = seq & 0x7ffff;\n }\n\n // randomly initialize seq\n if (seqHigh === null || seqLow === null) {\n seqHigh = rnds[6] & 0x7f;\n seqHigh = seqHigh << 8 | rnds[7];\n seqLow = rnds[8] & 0x3f; // pad for var\n seqLow = seqLow << 8 | rnds[9];\n seqLow = seqLow << 5 | rnds[10] >>> 3;\n }\n\n // increment seq if within msecs window\n if (msecs + 10000 > _msecs && seq === null) {\n if (++seqLow > 0x7ffff) {\n seqLow = 0;\n if (++seqHigh > 0xfff) {\n seqHigh = 0;\n\n // increment internal _msecs. this allows us to continue incrementing\n // while staying monotonic. Note, once we hit 10k milliseconds beyond system\n // clock, we will reset breaking monotonicity (after (2^31)*10000 generations)\n _msecs++;\n }\n }\n } else {\n // resetting; we have advanced more than\n // 10k milliseconds beyond system clock\n _msecs = msecs;\n }\n _seqHigh = seqHigh;\n _seqLow = seqLow;\n\n // [bytes 0-5] 48 bits of local timestamp\n b[i++] = _msecs / 0x10000000000 & 0xff;\n b[i++] = _msecs / 0x100000000 & 0xff;\n b[i++] = _msecs / 0x1000000 & 0xff;\n b[i++] = _msecs / 0x10000 & 0xff;\n b[i++] = _msecs / 0x100 & 0xff;\n b[i++] = _msecs & 0xff;\n\n // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi\n b[i++] = seqHigh >>> 4 & 0x0f | 0x70;\n\n // [byte 7] remaining 8 bits of seq_hi\n b[i++] = seqHigh & 0xff;\n\n // [byte 8] - variant (2 bits), first 6 bits seq_low\n b[i++] = seqLow >>> 13 & 0x3f | 0x80;\n\n // [byte 9] 8 bits seq_low\n b[i++] = seqLow >>> 5 & 0xff;\n\n // [byte 10] remaining 5 bits seq_low, 3 bits random\n b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07;\n\n // [bytes 11-15] always random\n b[i++] = rnds[11];\n b[i++] = rnds[12];\n b[i++] = rnds[13];\n b[i++] = rnds[14];\n b[i++] = rnds[15];\n return buf || (0, _stringify.unsafeStringify)(b);\n}\nvar _default = exports.default = v7;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\nvar _default = exports.default = validate;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\nfunction _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n return parseInt(uuid.slice(14, 15), 16);\n}\nvar _default = exports.default = version;","var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n","'use strict';\nmodule.exports = (promise, onFinally) => {\n\tonFinally = onFinally || (() => {});\n\n\treturn promise.then(\n\t\tval => new Promise(resolve => {\n\t\t\tresolve(onFinally());\n\t\t}).then(() => val),\n\t\terr => new Promise(resolve => {\n\t\t\tresolve(onFinally());\n\t\t}).then(() => {\n\t\t\tthrow err;\n\t\t})\n\t);\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst EventEmitter = require(\"eventemitter3\");\nconst p_timeout_1 = require(\"p-timeout\");\nconst priority_queue_1 = require(\"./priority-queue\");\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst empty = () => { };\nconst timeoutError = new p_timeout_1.TimeoutError();\n/**\nPromise queue with concurrency control.\n*/\nclass PQueue extends EventEmitter {\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n this._intervalCount = 0;\n this._intervalEnd = 0;\n this._pendingCount = 0;\n this._resolveEmpty = empty;\n this._resolveIdle = empty;\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options);\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n this._carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0;\n this._intervalCap = options.intervalCap;\n this._interval = options.interval;\n this._queue = new options.queueClass();\n this._queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this._timeout = options.timeout;\n this._throwOnTimeout = options.throwOnTimeout === true;\n this._isPaused = options.autoStart === false;\n }\n get _doesIntervalAllowAnother() {\n return this._isIntervalIgnored || this._intervalCount < this._intervalCap;\n }\n get _doesConcurrentAllowAnother() {\n return this._pendingCount < this._concurrency;\n }\n _next() {\n this._pendingCount--;\n this._tryToStartAnother();\n this.emit('next');\n }\n _resolvePromises() {\n this._resolveEmpty();\n this._resolveEmpty = empty;\n if (this._pendingCount === 0) {\n this._resolveIdle();\n this._resolveIdle = empty;\n this.emit('idle');\n }\n }\n _onResumeInterval() {\n this._onInterval();\n this._initializeIntervalIfNeeded();\n this._timeoutId = undefined;\n }\n _isIntervalPaused() {\n const now = Date.now();\n if (this._intervalId === undefined) {\n const delay = this._intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0;\n }\n else {\n // Act as the interval is pending\n if (this._timeoutId === undefined) {\n this._timeoutId = setTimeout(() => {\n this._onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n _tryToStartAnother() {\n if (this._queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this._intervalId) {\n clearInterval(this._intervalId);\n }\n this._intervalId = undefined;\n this._resolvePromises();\n return false;\n }\n if (!this._isPaused) {\n const canInitializeInterval = !this._isIntervalPaused();\n if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) {\n const job = this._queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this._initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n _initializeIntervalIfNeeded() {\n if (this._isIntervalIgnored || this._intervalId !== undefined) {\n return;\n }\n this._intervalId = setInterval(() => {\n this._onInterval();\n }, this._interval);\n this._intervalEnd = Date.now() + this._interval;\n }\n _onInterval() {\n if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) {\n clearInterval(this._intervalId);\n this._intervalId = undefined;\n }\n this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;\n this._processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n _processQueue() {\n // eslint-disable-next-line no-empty\n while (this._tryToStartAnother()) { }\n }\n get concurrency() {\n return this._concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this._concurrency = newConcurrency;\n this._processQueue();\n }\n /**\n Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options = {}) {\n return new Promise((resolve, reject) => {\n const run = async () => {\n this._pendingCount++;\n this._intervalCount++;\n try {\n const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => {\n if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) {\n reject(timeoutError);\n }\n return undefined;\n });\n resolve(await operation);\n }\n catch (error) {\n reject(error);\n }\n this._next();\n };\n this._queue.enqueue(run, options);\n this._tryToStartAnother();\n this.emit('add');\n });\n }\n /**\n Same as `.add()`, but accepts an array of sync or async functions.\n\n @returns A promise that resolves when all functions are resolved.\n */\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this._isPaused) {\n return this;\n }\n this._isPaused = false;\n this._processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this._isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this._queue = new this._queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this._queue.size === 0) {\n return;\n }\n return new Promise(resolve => {\n const existingResolve = this._resolveEmpty;\n this._resolveEmpty = () => {\n existingResolve();\n resolve();\n };\n });\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this._pendingCount === 0 && this._queue.size === 0) {\n return;\n }\n return new Promise(resolve => {\n const existingResolve = this._resolveIdle;\n this._resolveIdle = () => {\n existingResolve();\n resolve();\n };\n });\n }\n /**\n Size of the queue.\n */\n get size() {\n return this._queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-fn-reference-in-iterator\n return this._queue.filter(options).length;\n }\n /**\n Number of pending promises.\n */\n get pending() {\n return this._pendingCount;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this._isPaused;\n }\n get timeout() {\n return this._timeout;\n }\n /**\n Set the timeout for future operations.\n */\n set timeout(milliseconds) {\n this._timeout = milliseconds;\n }\n}\nexports.default = PQueue;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nfunction lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = (count / 2) | 0;\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\nexports.default = lowerBound;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst lower_bound_1 = require(\"./lower-bound\");\nclass PriorityQueue {\n constructor() {\n this._queue = [];\n }\n enqueue(run, options) {\n options = Object.assign({ priority: 0 }, options);\n const element = {\n priority: options.priority,\n run\n };\n if (this.size && this._queue[this.size - 1].priority >= options.priority) {\n this._queue.push(element);\n return;\n }\n const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);\n this._queue.splice(index, 0, element);\n }\n dequeue() {\n const item = this._queue.shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this._queue.length;\n }\n}\nexports.default = PriorityQueue;\n","'use strict';\nconst retry = require('retry');\n\nconst networkErrorMsgs = [\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari\n\t'Network request failed' // `cross-fetch`\n];\n\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nconst isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);\n\nconst pRetry = (input, options) => new Promise((resolve, reject) => {\n\toptions = {\n\t\tonFailedAttempt: () => {},\n\t\tretries: 10,\n\t\t...options\n\t};\n\n\tconst operation = retry.operation(options);\n\n\toperation.attempt(async attemptNumber => {\n\t\ttry {\n\t\t\tresolve(await input(attemptNumber));\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\treject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (error instanceof AbortError) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error.originalError);\n\t\t\t} else if (error instanceof TypeError && !isNetworkError(error.message)) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error);\n\t\t\t} else {\n\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\treject(operation.mainError());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n});\n\nmodule.exports = pRetry;\n// TODO: remove this in the next major version\nmodule.exports.default = pRetry;\n\nmodule.exports.AbortError = AbortError;\n","'use strict';\n\nconst pFinally = require('p-finally');\n\nclass TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\nconst pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => {\n\tif (typeof milliseconds !== 'number' || milliseconds < 0) {\n\t\tthrow new TypeError('Expected `milliseconds` to be a positive number');\n\t}\n\n\tif (milliseconds === Infinity) {\n\t\tresolve(promise);\n\t\treturn;\n\t}\n\n\tconst timer = setTimeout(() => {\n\t\tif (typeof fallback === 'function') {\n\t\t\ttry {\n\t\t\t\tresolve(fallback());\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;\n\t\tconst timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);\n\n\t\tif (typeof promise.cancel === 'function') {\n\t\t\tpromise.cancel();\n\t\t}\n\n\t\treject(timeoutError);\n\t}, milliseconds);\n\n\t// TODO: Use native `finally` keyword when targeting Node.js 10\n\tpFinally(\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tpromise.then(resolve, reject),\n\t\t() => {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t);\n});\n\nmodule.exports = pTimeout;\n// TODO: Remove this for the next major release\nmodule.exports.default = pTimeout;\n\nmodule.exports.TimeoutError = TimeoutError;\n","module.exports = require('./lib/retry');","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n","'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n","'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n","'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n","'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are preleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n","'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n","'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n","'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n","'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n","'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n","'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n","'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n","'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n","'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n","'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n","'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n","'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n","'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n","'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n","'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n","'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n","'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n","'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n","'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numberic identifiers include numberic identifiers but can be longer.\n// Therefore non-numberic identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n","'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n","'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n","'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n","'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n","'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n","'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n","'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n","module.exports = require('./lib/tunnel');\n","'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","'use strict'\n\nconst Client = require('./lib/client')\nconst Dispatcher = require('./lib/dispatcher')\nconst errors = require('./lib/core/errors')\nconst Pool = require('./lib/pool')\nconst BalancedPool = require('./lib/balanced-pool')\nconst Agent = require('./lib/agent')\nconst util = require('./lib/core/util')\nconst { InvalidArgumentError } = errors\nconst api = require('./lib/api')\nconst buildConnector = require('./lib/core/connect')\nconst MockClient = require('./lib/mock/mock-client')\nconst MockAgent = require('./lib/mock/mock-agent')\nconst MockPool = require('./lib/mock/mock-pool')\nconst mockErrors = require('./lib/mock/mock-errors')\nconst ProxyAgent = require('./lib/proxy-agent')\nconst RetryHandler = require('./lib/handler/RetryHandler')\nconst { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')\nconst DecoratorHandler = require('./lib/handler/DecoratorHandler')\nconst RedirectHandler = require('./lib/handler/RedirectHandler')\nconst createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor')\n\nlet hasCrypto\ntry {\n require('crypto')\n hasCrypto = true\n} catch {\n hasCrypto = false\n}\n\nObject.assign(Dispatcher.prototype, api)\n\nmodule.exports.Dispatcher = Dispatcher\nmodule.exports.Client = Client\nmodule.exports.Pool = Pool\nmodule.exports.BalancedPool = BalancedPool\nmodule.exports.Agent = Agent\nmodule.exports.ProxyAgent = ProxyAgent\nmodule.exports.RetryHandler = RetryHandler\n\nmodule.exports.DecoratorHandler = DecoratorHandler\nmodule.exports.RedirectHandler = RedirectHandler\nmodule.exports.createRedirectInterceptor = createRedirectInterceptor\n\nmodule.exports.buildConnector = buildConnector\nmodule.exports.errors = errors\n\nfunction makeDispatcher (fn) {\n return (url, opts, handler) => {\n if (typeof opts === 'function') {\n handler = opts\n opts = null\n }\n\n if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {\n throw new InvalidArgumentError('invalid url')\n }\n\n if (opts != null && typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (opts && opts.path != null) {\n if (typeof opts.path !== 'string') {\n throw new InvalidArgumentError('invalid opts.path')\n }\n\n let path = opts.path\n if (!opts.path.startsWith('/')) {\n path = `/${path}`\n }\n\n url = new URL(util.parseOrigin(url).origin + path)\n } else {\n if (!opts) {\n opts = typeof url === 'object' ? url : {}\n }\n\n url = util.parseURL(url)\n }\n\n const { agent, dispatcher = getGlobalDispatcher() } = opts\n\n if (agent) {\n throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')\n }\n\n return fn.call(dispatcher, {\n ...opts,\n origin: url.origin,\n path: url.search ? `${url.pathname}${url.search}` : url.pathname,\n method: opts.method || (opts.body ? 'PUT' : 'GET')\n }, handler)\n }\n}\n\nmodule.exports.setGlobalDispatcher = setGlobalDispatcher\nmodule.exports.getGlobalDispatcher = getGlobalDispatcher\n\nif (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {\n let fetchImpl = null\n module.exports.fetch = async function fetch (resource) {\n if (!fetchImpl) {\n fetchImpl = require('./lib/fetch').fetch\n }\n\n try {\n return await fetchImpl(...arguments)\n } catch (err) {\n if (typeof err === 'object') {\n Error.captureStackTrace(err, this)\n }\n\n throw err\n }\n }\n module.exports.Headers = require('./lib/fetch/headers').Headers\n module.exports.Response = require('./lib/fetch/response').Response\n module.exports.Request = require('./lib/fetch/request').Request\n module.exports.FormData = require('./lib/fetch/formdata').FormData\n module.exports.File = require('./lib/fetch/file').File\n module.exports.FileReader = require('./lib/fileapi/filereader').FileReader\n\n const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global')\n\n module.exports.setGlobalOrigin = setGlobalOrigin\n module.exports.getGlobalOrigin = getGlobalOrigin\n\n const { CacheStorage } = require('./lib/cache/cachestorage')\n const { kConstruct } = require('./lib/cache/symbols')\n\n // Cache & CacheStorage are tightly coupled with fetch. Even if it may run\n // in an older version of Node, it doesn't have any use without fetch.\n module.exports.caches = new CacheStorage(kConstruct)\n}\n\nif (util.nodeMajor >= 16) {\n const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/cookies')\n\n module.exports.deleteCookie = deleteCookie\n module.exports.getCookies = getCookies\n module.exports.getSetCookies = getSetCookies\n module.exports.setCookie = setCookie\n\n const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL')\n\n module.exports.parseMIMEType = parseMIMEType\n module.exports.serializeAMimeType = serializeAMimeType\n}\n\nif (util.nodeMajor >= 18 && hasCrypto) {\n const { WebSocket } = require('./lib/websocket/websocket')\n\n module.exports.WebSocket = WebSocket\n}\n\nmodule.exports.request = makeDispatcher(api.request)\nmodule.exports.stream = makeDispatcher(api.stream)\nmodule.exports.pipeline = makeDispatcher(api.pipeline)\nmodule.exports.connect = makeDispatcher(api.connect)\nmodule.exports.upgrade = makeDispatcher(api.upgrade)\n\nmodule.exports.MockClient = MockClient\nmodule.exports.MockPool = MockPool\nmodule.exports.MockAgent = MockAgent\nmodule.exports.mockErrors = mockErrors\n","'use strict'\n\nconst { InvalidArgumentError } = require('./core/errors')\nconst { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols')\nconst DispatcherBase = require('./dispatcher-base')\nconst Pool = require('./pool')\nconst Client = require('./client')\nconst util = require('./core/util')\nconst createRedirectInterceptor = require('./interceptor/redirectInterceptor')\nconst { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')()\n\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kMaxRedirections = Symbol('maxRedirections')\nconst kOnDrain = Symbol('onDrain')\nconst kFactory = Symbol('factory')\nconst kFinalizer = Symbol('finalizer')\nconst kOptions = Symbol('options')\n\nfunction defaultFactory (origin, opts) {\n return opts && opts.connections === 1\n ? new Client(origin, opts)\n : new Pool(origin, opts)\n}\n\nclass Agent extends DispatcherBase {\n constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {\n super()\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (connect && typeof connect !== 'function') {\n connect = { ...connect }\n }\n\n this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)\n ? options.interceptors.Agent\n : [createRedirectInterceptor({ maxRedirections })]\n\n this[kOptions] = { ...util.deepClone(options), connect }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kMaxRedirections] = maxRedirections\n this[kFactory] = factory\n this[kClients] = new Map()\n this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {\n const ref = this[kClients].get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this[kClients].delete(key)\n }\n })\n\n const agent = this\n\n this[kOnDrain] = (origin, targets) => {\n agent.emit('drain', origin, [agent, ...targets])\n }\n\n this[kOnConnect] = (origin, targets) => {\n agent.emit('connect', origin, [agent, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n agent.emit('disconnect', origin, [agent, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n agent.emit('connectionError', origin, [agent, ...targets], err)\n }\n }\n\n get [kRunning] () {\n let ret = 0\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore next: gc is undeterministic */\n if (client) {\n ret += client[kRunning]\n }\n }\n return ret\n }\n\n [kDispatch] (opts, handler) {\n let key\n if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {\n key = String(opts.origin)\n } else {\n throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')\n }\n\n const ref = this[kClients].get(key)\n\n let dispatcher = ref ? ref.deref() : null\n if (!dispatcher) {\n dispatcher = this[kFactory](opts.origin, this[kOptions])\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].set(key, new WeakRef(dispatcher))\n this[kFinalizer].register(dispatcher, key)\n }\n\n return dispatcher.dispatch(opts, handler)\n }\n\n async [kClose] () {\n const closePromises = []\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore else: gc is undeterministic */\n if (client) {\n closePromises.push(client.close())\n }\n }\n\n await Promise.all(closePromises)\n }\n\n async [kDestroy] (err) {\n const destroyPromises = []\n for (const ref of this[kClients].values()) {\n const client = ref.deref()\n /* istanbul ignore else: gc is undeterministic */\n if (client) {\n destroyPromises.push(client.destroy(err))\n }\n }\n\n await Promise.all(destroyPromises)\n }\n}\n\nmodule.exports = Agent\n","const { addAbortListener } = require('../core/util')\nconst { RequestAbortedError } = require('../core/errors')\n\nconst kListener = Symbol('kListener')\nconst kSignal = Symbol('kSignal')\n\nfunction abort (self) {\n if (self.abort) {\n self.abort()\n } else {\n self.onError(new RequestAbortedError())\n }\n}\n\nfunction addSignal (self, signal) {\n self[kSignal] = null\n self[kListener] = null\n\n if (!signal) {\n return\n }\n\n if (signal.aborted) {\n abort(self)\n return\n }\n\n self[kSignal] = signal\n self[kListener] = () => {\n abort(self)\n }\n\n addAbortListener(self[kSignal], self[kListener])\n}\n\nfunction removeSignal (self) {\n if (!self[kSignal]) {\n return\n }\n\n if ('removeEventListener' in self[kSignal]) {\n self[kSignal].removeEventListener('abort', self[kListener])\n } else {\n self[kSignal].removeListener('abort', self[kListener])\n }\n\n self[kSignal] = null\n self[kListener] = null\n}\n\nmodule.exports = {\n addSignal,\n removeSignal\n}\n","'use strict'\n\nconst { AsyncResource } = require('async_hooks')\nconst { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass ConnectHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_CONNECT')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.callback = callback\n this.abort = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders () {\n throw new SocketError('bad connect', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n removeSignal(this)\n\n this.callback = null\n\n let headers = rawHeaders\n // Indicates is an HTTP2Session\n if (headers != null) {\n headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n }\n\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction connect (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n connect.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const connectHandler = new ConnectHandler(opts, callback)\n this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = connect\n","'use strict'\n\nconst {\n Readable,\n Duplex,\n PassThrough\n} = require('stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('assert')\n\nconst kResume = Symbol('resume')\n\nclass PipelineRequest extends Readable {\n constructor () {\n super({ autoDestroy: true })\n\n this[kResume] = null\n }\n\n _read () {\n const { [kResume]: resume } = this\n\n if (resume) {\n this[kResume] = null\n resume()\n }\n }\n\n _destroy (err, callback) {\n this._read()\n\n callback(err)\n }\n}\n\nclass PipelineResponse extends Readable {\n constructor (resume) {\n super({ autoDestroy: true })\n this[kResume] = resume\n }\n\n _read () {\n this[kResume]()\n }\n\n _destroy (err, callback) {\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n callback(err)\n }\n}\n\nclass PipelineHandler extends AsyncResource {\n constructor (opts, handler) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof handler !== 'function') {\n throw new InvalidArgumentError('invalid handler')\n }\n\n const { signal, method, opaque, onInfo, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_PIPELINE')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.handler = handler\n this.abort = null\n this.context = null\n this.onInfo = onInfo || null\n\n this.req = new PipelineRequest().on('error', util.nop)\n\n this.ret = new Duplex({\n readableObjectMode: opts.objectMode,\n autoDestroy: true,\n read: () => {\n const { body } = this\n\n if (body && body.resume) {\n body.resume()\n }\n },\n write: (chunk, encoding, callback) => {\n const { req } = this\n\n if (req.push(chunk, encoding) || req._readableState.destroyed) {\n callback()\n } else {\n req[kResume] = callback\n }\n },\n destroy: (err, callback) => {\n const { body, req, res, ret, abort } = this\n\n if (!err && !ret._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (abort && err) {\n abort()\n }\n\n util.destroy(body, err)\n util.destroy(req, err)\n util.destroy(res, err)\n\n removeSignal(this)\n\n callback(err)\n }\n }).on('prefinish', () => {\n const { req } = this\n\n // Node < 15 does not call _final in same tick.\n req.push(null)\n })\n\n this.res = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n const { ret, res } = this\n\n assert(!res, 'pipeline cannot be retried')\n\n if (ret.destroyed) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume) {\n const { opaque, handler, context } = this\n\n if (statusCode < 200) {\n if (this.onInfo) {\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.res = new PipelineResponse(resume)\n\n let body\n try {\n this.handler = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n body = this.runInAsyncScope(handler, null, {\n statusCode,\n headers,\n opaque,\n body: this.res,\n context\n })\n } catch (err) {\n this.res.on('error', util.nop)\n throw err\n }\n\n if (!body || typeof body.on !== 'function') {\n throw new InvalidReturnValueError('expected Readable')\n }\n\n body\n .on('data', (chunk) => {\n const { ret, body } = this\n\n if (!ret.push(chunk) && body.pause) {\n body.pause()\n }\n })\n .on('error', (err) => {\n const { ret } = this\n\n util.destroy(ret, err)\n })\n .on('end', () => {\n const { ret } = this\n\n ret.push(null)\n })\n .on('close', () => {\n const { ret } = this\n\n if (!ret._readableState.ended) {\n util.destroy(ret, new RequestAbortedError())\n }\n })\n\n this.body = body\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n res.push(null)\n }\n\n onError (err) {\n const { ret } = this\n this.handler = null\n util.destroy(ret, err)\n }\n}\n\nfunction pipeline (opts, handler) {\n try {\n const pipelineHandler = new PipelineHandler(opts, handler)\n this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)\n return pipelineHandler.ret\n } catch (err) {\n return new PassThrough().destroy(err)\n }\n}\n\nmodule.exports = pipeline\n","'use strict'\n\nconst Readable = require('./readable')\nconst {\n InvalidArgumentError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass RequestHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {\n throw new InvalidArgumentError('invalid highWaterMark')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_REQUEST')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.res = null\n this.abort = null\n this.body = body\n this.trailers = {}\n this.context = null\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError\n this.highWaterMark = highWaterMark\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n const body = new Readable({ resume, abort, contentType, highWaterMark })\n\n this.callback = null\n this.res = body\n if (callback !== null) {\n if (this.throwOnError && statusCode >= 400) {\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body, contentType, statusCode, statusMessage, headers }\n )\n } else {\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n trailers: this.trailers,\n opaque,\n body,\n context\n })\n }\n }\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n util.parseHeaders(trailers, this.trailers)\n\n res.push(null)\n }\n\n onError (err) {\n const { res, callback, body, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n // TODO: Does this need queueMicrotask?\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (res) {\n this.res = null\n // Ensure all queued handlers are invoked before destroying res.\n queueMicrotask(() => {\n util.destroy(res, err)\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction request (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n request.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new RequestHandler(opts, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = request\nmodule.exports.RequestHandler = RequestHandler\n","'use strict'\n\nconst { finished, PassThrough } = require('stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass StreamHandler extends AsyncResource {\n constructor (opts, factory, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('invalid factory')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_STREAM')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.factory = factory\n this.callback = callback\n this.res = null\n this.abort = null\n this.context = null\n this.trailers = null\n this.body = body\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError || false\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { factory, opaque, context, callback, responseHeaders } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.factory = null\n\n let res\n\n if (this.throwOnError && statusCode >= 400) {\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n res = new PassThrough()\n\n this.callback = null\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body: res, contentType, statusCode, statusMessage, headers }\n )\n } else {\n if (factory === null) {\n return\n }\n\n res = this.runInAsyncScope(factory, null, {\n statusCode,\n headers,\n opaque,\n context\n })\n\n if (\n !res ||\n typeof res.write !== 'function' ||\n typeof res.end !== 'function' ||\n typeof res.on !== 'function'\n ) {\n throw new InvalidReturnValueError('expected Writable')\n }\n\n // TODO: Avoid finished. It registers an unnecessary amount of listeners.\n finished(res, { readable: false }, (err) => {\n const { callback, res, opaque, trailers, abort } = this\n\n this.res = null\n if (err || !res.readable) {\n util.destroy(res, err)\n }\n\n this.callback = null\n this.runInAsyncScope(callback, null, err || null, { opaque, trailers })\n\n if (err) {\n abort()\n }\n })\n }\n\n res.on('drain', resume)\n\n this.res = res\n\n const needDrain = res.writableNeedDrain !== undefined\n ? res.writableNeedDrain\n : res._writableState && res._writableState.needDrain\n\n return needDrain !== true\n }\n\n onData (chunk) {\n const { res } = this\n\n return res ? res.write(chunk) : true\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n if (!res) {\n return\n }\n\n this.trailers = util.parseHeaders(trailers)\n\n res.end()\n }\n\n onError (err) {\n const { res, callback, opaque, body } = this\n\n removeSignal(this)\n\n this.factory = null\n\n if (res) {\n this.res = null\n util.destroy(res, err)\n } else if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction stream (opts, factory, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n stream.call(this, opts, factory, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new StreamHandler(opts, factory, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = stream\n","'use strict'\n\nconst { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')\nconst { AsyncResource } = require('async_hooks')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('assert')\n\nclass UpgradeHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_UPGRADE')\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.abort = null\n this.context = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (!this.callback) {\n throw new RequestAbortedError()\n }\n\n this.abort = abort\n this.context = null\n }\n\n onHeaders () {\n throw new SocketError('bad upgrade', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n assert.strictEqual(statusCode, 101)\n\n removeSignal(this)\n\n this.callback = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.runInAsyncScope(callback, null, null, {\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction upgrade (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n upgrade.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const upgradeHandler = new UpgradeHandler(opts, callback)\n this.dispatch({\n ...opts,\n method: opts.method || 'GET',\n upgrade: opts.protocol || 'Websocket'\n }, upgradeHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts && opts.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = upgrade\n","'use strict'\n\nmodule.exports.request = require('./api-request')\nmodule.exports.stream = require('./api-stream')\nmodule.exports.pipeline = require('./api-pipeline')\nmodule.exports.upgrade = require('./api-upgrade')\nmodule.exports.connect = require('./api-connect')\n","// Ported from https://github.com/nodejs/undici/pull/907\n\n'use strict'\n\nconst assert = require('assert')\nconst { Readable } = require('stream')\nconst { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors')\nconst util = require('../core/util')\nconst { ReadableStreamFrom, toUSVString } = require('../core/util')\n\nlet Blob\n\nconst kConsume = Symbol('kConsume')\nconst kReading = Symbol('kReading')\nconst kBody = Symbol('kBody')\nconst kAbort = Symbol('abort')\nconst kContentType = Symbol('kContentType')\n\nconst noop = () => {}\n\nmodule.exports = class BodyReadable extends Readable {\n constructor ({\n resume,\n abort,\n contentType = '',\n highWaterMark = 64 * 1024 // Same as nodejs fs streams.\n }) {\n super({\n autoDestroy: true,\n read: resume,\n highWaterMark\n })\n\n this._readableState.dataEmitted = false\n\n this[kAbort] = abort\n this[kConsume] = null\n this[kBody] = null\n this[kContentType] = contentType\n\n // Is stream being consumed through Readable API?\n // This is an optimization so that we avoid checking\n // for 'data' and 'readable' listeners in the hot path\n // inside push().\n this[kReading] = false\n }\n\n destroy (err) {\n if (this.destroyed) {\n // Node < 16\n return this\n }\n\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (err) {\n this[kAbort]()\n }\n\n return super.destroy(err)\n }\n\n emit (ev, ...args) {\n if (ev === 'data') {\n // Node < 16.7\n this._readableState.dataEmitted = true\n } else if (ev === 'error') {\n // Node < 16\n this._readableState.errorEmitted = true\n }\n return super.emit(ev, ...args)\n }\n\n on (ev, ...args) {\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = true\n }\n return super.on(ev, ...args)\n }\n\n addListener (ev, ...args) {\n return this.on(ev, ...args)\n }\n\n off (ev, ...args) {\n const ret = super.off(ev, ...args)\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = (\n this.listenerCount('data') > 0 ||\n this.listenerCount('readable') > 0\n )\n }\n return ret\n }\n\n removeListener (ev, ...args) {\n return this.off(ev, ...args)\n }\n\n push (chunk) {\n if (this[kConsume] && chunk !== null && this.readableLength === 0) {\n consumePush(this[kConsume], chunk)\n return this[kReading] ? super.push(chunk) : true\n }\n return super.push(chunk)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-text\n async text () {\n return consume(this, 'text')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-json\n async json () {\n return consume(this, 'json')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-blob\n async blob () {\n return consume(this, 'blob')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-arraybuffer\n async arrayBuffer () {\n return consume(this, 'arrayBuffer')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-formdata\n async formData () {\n // TODO: Implement.\n throw new NotSupportedError()\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-bodyused\n get bodyUsed () {\n return util.isDisturbed(this)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-body\n get body () {\n if (!this[kBody]) {\n this[kBody] = ReadableStreamFrom(this)\n if (this[kConsume]) {\n // TODO: Is this the best way to force a lock?\n this[kBody].getReader() // Ensure stream is locked.\n assert(this[kBody].locked)\n }\n }\n return this[kBody]\n }\n\n dump (opts) {\n let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144\n const signal = opts && opts.signal\n\n if (signal) {\n try {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n throw new InvalidArgumentError('signal must be an AbortSignal')\n }\n util.throwIfAborted(signal)\n } catch (err) {\n return Promise.reject(err)\n }\n }\n\n if (this.closed) {\n return Promise.resolve(null)\n }\n\n return new Promise((resolve, reject) => {\n const signalListenerCleanup = signal\n ? util.addAbortListener(signal, () => {\n this.destroy()\n })\n : noop\n\n this\n .on('close', function () {\n signalListenerCleanup()\n if (signal && signal.aborted) {\n reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))\n } else {\n resolve(null)\n }\n })\n .on('error', noop)\n .on('data', function (chunk) {\n limit -= chunk.length\n if (limit <= 0) {\n this.destroy()\n }\n })\n .resume()\n })\n }\n}\n\n// https://streams.spec.whatwg.org/#readablestream-locked\nfunction isLocked (self) {\n // Consume is an implicit lock.\n return (self[kBody] && self[kBody].locked === true) || self[kConsume]\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction isUnusable (self) {\n return util.isDisturbed(self) || isLocked(self)\n}\n\nasync function consume (stream, type) {\n if (isUnusable(stream)) {\n throw new TypeError('unusable')\n }\n\n assert(!stream[kConsume])\n\n return new Promise((resolve, reject) => {\n stream[kConsume] = {\n type,\n stream,\n resolve,\n reject,\n length: 0,\n body: []\n }\n\n stream\n .on('error', function (err) {\n consumeFinish(this[kConsume], err)\n })\n .on('close', function () {\n if (this[kConsume].body !== null) {\n consumeFinish(this[kConsume], new RequestAbortedError())\n }\n })\n\n process.nextTick(consumeStart, stream[kConsume])\n })\n}\n\nfunction consumeStart (consume) {\n if (consume.body === null) {\n return\n }\n\n const { _readableState: state } = consume.stream\n\n for (const chunk of state.buffer) {\n consumePush(consume, chunk)\n }\n\n if (state.endEmitted) {\n consumeEnd(this[kConsume])\n } else {\n consume.stream.on('end', function () {\n consumeEnd(this[kConsume])\n })\n }\n\n consume.stream.resume()\n\n while (consume.stream.read() != null) {\n // Loop\n }\n}\n\nfunction consumeEnd (consume) {\n const { type, body, resolve, stream, length } = consume\n\n try {\n if (type === 'text') {\n resolve(toUSVString(Buffer.concat(body)))\n } else if (type === 'json') {\n resolve(JSON.parse(Buffer.concat(body)))\n } else if (type === 'arrayBuffer') {\n const dst = new Uint8Array(length)\n\n let pos = 0\n for (const buf of body) {\n dst.set(buf, pos)\n pos += buf.byteLength\n }\n\n resolve(dst.buffer)\n } else if (type === 'blob') {\n if (!Blob) {\n Blob = require('buffer').Blob\n }\n resolve(new Blob(body, { type: stream[kContentType] }))\n }\n\n consumeFinish(consume)\n } catch (err) {\n stream.destroy(err)\n }\n}\n\nfunction consumePush (consume, chunk) {\n consume.length += chunk.length\n consume.body.push(chunk)\n}\n\nfunction consumeFinish (consume, err) {\n if (consume.body === null) {\n return\n }\n\n if (err) {\n consume.reject(err)\n } else {\n consume.resolve()\n }\n\n consume.type = null\n consume.stream = null\n consume.resolve = null\n consume.reject = null\n consume.length = 0\n consume.body = null\n}\n","const assert = require('assert')\nconst {\n ResponseStatusCodeError\n} = require('../core/errors')\nconst { toUSVString } = require('../core/util')\n\nasync function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {\n assert(body)\n\n let chunks = []\n let limit = 0\n\n for await (const chunk of body) {\n chunks.push(chunk)\n limit += chunk.length\n if (limit > 128 * 1024) {\n chunks = null\n break\n }\n }\n\n if (statusCode === 204 || !contentType || !chunks) {\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))\n return\n }\n\n try {\n if (contentType.startsWith('application/json')) {\n const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))\n return\n }\n\n if (contentType.startsWith('text/')) {\n const payload = toUSVString(Buffer.concat(chunks))\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))\n return\n }\n } catch (err) {\n // Process in a fallback if error\n }\n\n process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))\n}\n\nmodule.exports = { getResolveErrorBodyCallback }\n","'use strict'\n\nconst {\n BalancedPoolMissingUpstreamError,\n InvalidArgumentError\n} = require('./core/errors')\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Pool = require('./pool')\nconst { kUrl, kInterceptors } = require('./core/symbols')\nconst { parseOrigin } = require('./core/util')\nconst kFactory = Symbol('factory')\n\nconst kOptions = Symbol('options')\nconst kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')\nconst kCurrentWeight = Symbol('kCurrentWeight')\nconst kIndex = Symbol('kIndex')\nconst kWeight = Symbol('kWeight')\nconst kMaxWeightPerServer = Symbol('kMaxWeightPerServer')\nconst kErrorPenalty = Symbol('kErrorPenalty')\n\nfunction getGreatestCommonDivisor (a, b) {\n if (b === 0) return a\n return getGreatestCommonDivisor(b, a % b)\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass BalancedPool extends PoolBase {\n constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {\n super()\n\n this[kOptions] = opts\n this[kIndex] = -1\n this[kCurrentWeight] = 0\n\n this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100\n this[kErrorPenalty] = this[kOptions].errorPenalty || 15\n\n if (!Array.isArray(upstreams)) {\n upstreams = [upstreams]\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)\n ? opts.interceptors.BalancedPool\n : []\n this[kFactory] = factory\n\n for (const upstream of upstreams) {\n this.addUpstream(upstream)\n }\n this._updateBalancedPoolStats()\n }\n\n addUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n if (this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))) {\n return this\n }\n const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))\n\n this[kAddClient](pool)\n pool.on('connect', () => {\n pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])\n })\n\n pool.on('connectionError', () => {\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n })\n\n pool.on('disconnect', (...args) => {\n const err = args[2]\n if (err && err.code === 'UND_ERR_SOCKET') {\n // decrease the weight of the pool.\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n }\n })\n\n for (const client of this[kClients]) {\n client[kWeight] = this[kMaxWeightPerServer]\n }\n\n this._updateBalancedPoolStats()\n\n return this\n }\n\n _updateBalancedPoolStats () {\n this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)\n }\n\n removeUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n const pool = this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))\n\n if (pool) {\n this[kRemoveClient](pool)\n }\n\n return this\n }\n\n get upstreams () {\n return this[kClients]\n .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)\n .map((p) => p[kUrl].origin)\n }\n\n [kGetDispatcher] () {\n // We validate that pools is greater than 0,\n // otherwise we would have to wait until an upstream\n // is added, which might never happen.\n if (this[kClients].length === 0) {\n throw new BalancedPoolMissingUpstreamError()\n }\n\n const dispatcher = this[kClients].find(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n\n if (!dispatcher) {\n return\n }\n\n const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)\n\n if (allClientsBusy) {\n return\n }\n\n let counter = 0\n\n let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])\n\n while (counter++ < this[kClients].length) {\n this[kIndex] = (this[kIndex] + 1) % this[kClients].length\n const pool = this[kClients][this[kIndex]]\n\n // find pool index with the largest weight\n if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {\n maxWeightIndex = this[kIndex]\n }\n\n // decrease the current weight every `this[kClients].length`.\n if (this[kIndex] === 0) {\n // Set the current weight to the next lower weight.\n this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]\n\n if (this[kCurrentWeight] <= 0) {\n this[kCurrentWeight] = this[kMaxWeightPerServer]\n }\n }\n if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {\n return pool\n }\n }\n\n this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]\n this[kIndex] = maxWeightIndex\n return this[kClients][maxWeightIndex]\n }\n}\n\nmodule.exports = BalancedPool\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { urlEquals, fieldValues: getFieldValues } = require('./util')\nconst { kEnumerableProperty, isDisturbed } = require('../core/util')\nconst { kHeadersList } = require('../core/symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { Response, cloneResponse } = require('../fetch/response')\nconst { Request } = require('../fetch/request')\nconst { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols')\nconst { fetching } = require('../fetch/index')\nconst { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')\nconst assert = require('assert')\nconst { getGlobalDispatcher } = require('../global')\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation\n * @typedef {Object} CacheBatchOperation\n * @property {'delete' | 'put'} type\n * @property {any} request\n * @property {any} response\n * @property {import('../../types/cache').CacheQueryOptions} options\n */\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list\n * @typedef {[any, any][]} requestResponseList\n */\n\nclass Cache {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list\n * @type {requestResponseList}\n */\n #relevantRequestResponseList\n\n constructor () {\n if (arguments[0] !== kConstruct) {\n webidl.illegalConstructor()\n }\n\n this.#relevantRequestResponseList = arguments[1]\n }\n\n async match (request, options = {}) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })\n\n request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n const p = await this.matchAll(request, options)\n\n if (p.length === 0) {\n return\n }\n\n return p[0]\n }\n\n async matchAll (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') {\n // 2.2.1\n r = new Request(request)[kState]\n }\n }\n\n // 5.\n // 5.1\n const responses = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n responses.push(requestResponse[1])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n responses.push(requestResponse[1])\n }\n }\n\n // 5.4\n // We don't implement CORs so we don't need to loop over the responses, yay!\n\n // 5.5.1\n const responseList = []\n\n // 5.5.2\n for (const response of responses) {\n // 5.5.2.1\n const responseObject = new Response(response.body?.source ?? null)\n const body = responseObject[kState].body\n responseObject[kState] = response\n responseObject[kState].body = body\n responseObject[kHeaders][kHeadersList] = response.headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n\n responseList.push(responseObject)\n }\n\n // 6.\n return Object.freeze(responseList)\n }\n\n async add (request) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })\n\n request = webidl.converters.RequestInfo(request)\n\n // 1.\n const requests = [request]\n\n // 2.\n const responseArrayPromise = this.addAll(requests)\n\n // 3.\n return await responseArrayPromise\n }\n\n async addAll (requests) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })\n\n requests = webidl.converters['sequence'](requests)\n\n // 1.\n const responsePromises = []\n\n // 2.\n const requestList = []\n\n // 3.\n for (const request of requests) {\n if (typeof request === 'string') {\n continue\n }\n\n // 3.1\n const r = request[kState]\n\n // 3.2\n if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Expected http/s scheme when method is not GET.'\n })\n }\n }\n\n // 4.\n /** @type {ReturnType[]} */\n const fetchControllers = []\n\n // 5.\n for (const request of requests) {\n // 5.1\n const r = new Request(request)[kState]\n\n // 5.2\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Expected http/s scheme.'\n })\n }\n\n // 5.4\n r.initiator = 'fetch'\n r.destination = 'subresource'\n\n // 5.5\n requestList.push(r)\n\n // 5.6\n const responsePromise = createDeferredPromise()\n\n // 5.7\n fetchControllers.push(fetching({\n request: r,\n dispatcher: getGlobalDispatcher(),\n processResponse (response) {\n // 1.\n if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Received an invalid status code or the request failed.'\n }))\n } else if (response.headersList.contains('vary')) { // 2.\n // 2.1\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n // 2.2\n for (const fieldValue of fieldValues) {\n // 2.2.1\n if (fieldValue === '*') {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'invalid vary field value'\n }))\n\n for (const controller of fetchControllers) {\n controller.abort()\n }\n\n return\n }\n }\n }\n },\n processResponseEndOfBody (response) {\n // 1.\n if (response.aborted) {\n responsePromise.reject(new DOMException('aborted', 'AbortError'))\n return\n }\n\n // 2.\n responsePromise.resolve(response)\n }\n }))\n\n // 5.8\n responsePromises.push(responsePromise.promise)\n }\n\n // 6.\n const p = Promise.all(responsePromises)\n\n // 7.\n const responses = await p\n\n // 7.1\n const operations = []\n\n // 7.2\n let index = 0\n\n // 7.3\n for (const response of responses) {\n // 7.3.1\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 7.3.2\n request: requestList[index], // 7.3.3\n response // 7.3.4\n }\n\n operations.push(operation) // 7.3.5\n\n index++ // 7.3.6\n }\n\n // 7.5\n const cacheJobPromise = createDeferredPromise()\n\n // 7.6.1\n let errorData = null\n\n // 7.6.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 7.6.3\n queueMicrotask(() => {\n // 7.6.3.1\n if (errorData === null) {\n cacheJobPromise.resolve(undefined)\n } else {\n // 7.6.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n // 7.7\n return cacheJobPromise.promise\n }\n\n async put (request, response) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })\n\n request = webidl.converters.RequestInfo(request)\n response = webidl.converters.Response(response)\n\n // 1.\n let innerRequest = null\n\n // 2.\n if (request instanceof Request) {\n innerRequest = request[kState]\n } else { // 3.\n innerRequest = new Request(request)[kState]\n }\n\n // 4.\n if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Expected an http/s scheme when method is not GET'\n })\n }\n\n // 5.\n const innerResponse = response[kState]\n\n // 6.\n if (innerResponse.status === 206) {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Got 206 status'\n })\n }\n\n // 7.\n if (innerResponse.headersList.contains('vary')) {\n // 7.1.\n const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))\n\n // 7.2.\n for (const fieldValue of fieldValues) {\n // 7.2.1\n if (fieldValue === '*') {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Got * vary field value'\n })\n }\n }\n }\n\n // 8.\n if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {\n throw webidl.errors.exception({\n header: 'Cache.put',\n message: 'Response body is locked or disturbed'\n })\n }\n\n // 9.\n const clonedResponse = cloneResponse(innerResponse)\n\n // 10.\n const bodyReadPromise = createDeferredPromise()\n\n // 11.\n if (innerResponse.body != null) {\n // 11.1\n const stream = innerResponse.body.stream\n\n // 11.2\n const reader = stream.getReader()\n\n // 11.3\n readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)\n } else {\n bodyReadPromise.resolve(undefined)\n }\n\n // 12.\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n // 13.\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 14.\n request: innerRequest, // 15.\n response: clonedResponse // 16.\n }\n\n // 17.\n operations.push(operation)\n\n // 19.\n const bytes = await bodyReadPromise.promise\n\n if (clonedResponse.body != null) {\n clonedResponse.body.source = bytes\n }\n\n // 19.1\n const cacheJobPromise = createDeferredPromise()\n\n // 19.2.1\n let errorData = null\n\n // 19.2.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 19.2.3\n queueMicrotask(() => {\n // 19.2.3.1\n if (errorData === null) {\n cacheJobPromise.resolve()\n } else { // 19.2.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n async delete (request, options = {}) {\n webidl.brandCheck(this, Cache)\n webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })\n\n request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n /**\n * @type {Request}\n */\n let r = null\n\n if (request instanceof Request) {\n r = request[kState]\n\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return false\n }\n } else {\n assert(typeof request === 'string')\n\n r = new Request(request)[kState]\n }\n\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'delete',\n request: r,\n options\n }\n\n operations.push(operation)\n\n const cacheJobPromise = createDeferredPromise()\n\n let errorData = null\n let requestResponses\n\n try {\n requestResponses = this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n queueMicrotask(() => {\n if (errorData === null) {\n cacheJobPromise.resolve(!!requestResponses?.length)\n } else {\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys\n * @param {any} request\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @returns {readonly Request[]}\n */\n async keys (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request)\n options = webidl.converters.CacheQueryOptions(options)\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n // 2.1\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') { // 2.2\n r = new Request(request)[kState]\n }\n }\n\n // 4.\n const promise = createDeferredPromise()\n\n // 5.\n // 5.1\n const requests = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n // 5.2.1.1\n requests.push(requestResponse[0])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n // 5.3.2.1\n requests.push(requestResponse[0])\n }\n }\n\n // 5.4\n queueMicrotask(() => {\n // 5.4.1\n const requestList = []\n\n // 5.4.2\n for (const request of requests) {\n const requestObject = new Request('https://a')\n requestObject[kState] = request\n requestObject[kHeaders][kHeadersList] = request.headersList\n requestObject[kHeaders][kGuard] = 'immutable'\n requestObject[kRealm] = request.client\n\n // 5.4.2.1\n requestList.push(requestObject)\n }\n\n // 5.4.3\n promise.resolve(Object.freeze(requestList))\n })\n\n return promise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm\n * @param {CacheBatchOperation[]} operations\n * @returns {requestResponseList}\n */\n #batchCacheOperations (operations) {\n // 1.\n const cache = this.#relevantRequestResponseList\n\n // 2.\n const backupCache = [...cache]\n\n // 3.\n const addedItems = []\n\n // 4.1\n const resultList = []\n\n try {\n // 4.2\n for (const operation of operations) {\n // 4.2.1\n if (operation.type !== 'delete' && operation.type !== 'put') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'operation type does not match \"delete\" or \"put\"'\n })\n }\n\n // 4.2.2\n if (operation.type === 'delete' && operation.response != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'delete operation should not have an associated response'\n })\n }\n\n // 4.2.3\n if (this.#queryCache(operation.request, operation.options, addedItems).length) {\n throw new DOMException('???', 'InvalidStateError')\n }\n\n // 4.2.4\n let requestResponses\n\n // 4.2.5\n if (operation.type === 'delete') {\n // 4.2.5.1\n requestResponses = this.#queryCache(operation.request, operation.options)\n\n // TODO: the spec is wrong, this is needed to pass WPTs\n if (requestResponses.length === 0) {\n return []\n }\n\n // 4.2.5.2\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.5.2.1\n cache.splice(idx, 1)\n }\n } else if (operation.type === 'put') { // 4.2.6\n // 4.2.6.1\n if (operation.response == null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'put operation should have an associated response'\n })\n }\n\n // 4.2.6.2\n const r = operation.request\n\n // 4.2.6.3\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'expected http or https scheme'\n })\n }\n\n // 4.2.6.4\n if (r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'not get method'\n })\n }\n\n // 4.2.6.5\n if (operation.options != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'options must not be defined'\n })\n }\n\n // 4.2.6.6\n requestResponses = this.#queryCache(operation.request)\n\n // 4.2.6.7\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.6.7.1\n cache.splice(idx, 1)\n }\n\n // 4.2.6.8\n cache.push([operation.request, operation.response])\n\n // 4.2.6.10\n addedItems.push([operation.request, operation.response])\n }\n\n // 4.2.7\n resultList.push([operation.request, operation.response])\n }\n\n // 4.3\n return resultList\n } catch (e) { // 5.\n // 5.1\n this.#relevantRequestResponseList.length = 0\n\n // 5.2\n this.#relevantRequestResponseList = backupCache\n\n // 5.3\n throw e\n }\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#query-cache\n * @param {any} requestQuery\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @param {requestResponseList} targetStorage\n * @returns {requestResponseList}\n */\n #queryCache (requestQuery, options, targetStorage) {\n /** @type {requestResponseList} */\n const resultList = []\n\n const storage = targetStorage ?? this.#relevantRequestResponseList\n\n for (const requestResponse of storage) {\n const [cachedRequest, cachedResponse] = requestResponse\n if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {\n resultList.push(requestResponse)\n }\n }\n\n return resultList\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm\n * @param {any} requestQuery\n * @param {any} request\n * @param {any | null} response\n * @param {import('../../types/cache').CacheQueryOptions | undefined} options\n * @returns {boolean}\n */\n #requestMatchesCachedItem (requestQuery, request, response = null, options) {\n // if (options?.ignoreMethod === false && request.method === 'GET') {\n // return false\n // }\n\n const queryURL = new URL(requestQuery.url)\n\n const cachedURL = new URL(request.url)\n\n if (options?.ignoreSearch) {\n cachedURL.search = ''\n\n queryURL.search = ''\n }\n\n if (!urlEquals(queryURL, cachedURL, true)) {\n return false\n }\n\n if (\n response == null ||\n options?.ignoreVary ||\n !response.headersList.contains('vary')\n ) {\n return true\n }\n\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n for (const fieldValue of fieldValues) {\n if (fieldValue === '*') {\n return false\n }\n\n const requestValue = request.headersList.get(fieldValue)\n const queryValue = requestQuery.headersList.get(fieldValue)\n\n // If one has the header and the other doesn't, or one has\n // a different value than the other, return false\n if (requestValue !== queryValue) {\n return false\n }\n }\n\n return true\n }\n}\n\nObject.defineProperties(Cache.prototype, {\n [Symbol.toStringTag]: {\n value: 'Cache',\n configurable: true\n },\n match: kEnumerableProperty,\n matchAll: kEnumerableProperty,\n add: kEnumerableProperty,\n addAll: kEnumerableProperty,\n put: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nconst cacheQueryOptionConverters = [\n {\n key: 'ignoreSearch',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'ignoreMethod',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'ignoreVary',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n]\n\nwebidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)\n\nwebidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([\n ...cacheQueryOptionConverters,\n {\n key: 'cacheName',\n converter: webidl.converters.DOMString\n }\n])\n\nwebidl.converters.Response = webidl.interfaceConverter(Response)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.RequestInfo\n)\n\nmodule.exports = {\n Cache\n}\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { Cache } = require('./cache')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\n\nclass CacheStorage {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map\n * @type {Map}\n */\n async has (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n // 2.1.1\n // 2.2\n return this.#caches.has(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open\n * @param {string} cacheName\n * @returns {Promise}\n */\n async open (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n // 2.1\n if (this.#caches.has(cacheName)) {\n // await caches.open('v1') !== await caches.open('v1')\n\n // 2.1.1\n const cache = this.#caches.get(cacheName)\n\n // 2.1.1.1\n return new Cache(kConstruct, cache)\n }\n\n // 2.2\n const cache = []\n\n // 2.3\n this.#caches.set(cacheName, cache)\n\n // 2.4\n return new Cache(kConstruct, cache)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete\n * @param {string} cacheName\n * @returns {Promise}\n */\n async delete (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })\n\n cacheName = webidl.converters.DOMString(cacheName)\n\n return this.#caches.delete(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys\n * @returns {string[]}\n */\n async keys () {\n webidl.brandCheck(this, CacheStorage)\n\n // 2.1\n const keys = this.#caches.keys()\n\n // 2.2\n return [...keys]\n }\n}\n\nObject.defineProperties(CacheStorage.prototype, {\n [Symbol.toStringTag]: {\n value: 'CacheStorage',\n configurable: true\n },\n match: kEnumerableProperty,\n has: kEnumerableProperty,\n open: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nmodule.exports = {\n CacheStorage\n}\n","'use strict'\n\nmodule.exports = {\n kConstruct: require('../core/symbols').kConstruct\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { URLSerializer } = require('../fetch/dataURL')\nconst { isValidHeaderName } = require('../fetch/util')\n\n/**\n * @see https://url.spec.whatwg.org/#concept-url-equals\n * @param {URL} A\n * @param {URL} B\n * @param {boolean | undefined} excludeFragment\n * @returns {boolean}\n */\nfunction urlEquals (A, B, excludeFragment = false) {\n const serializedA = URLSerializer(A, excludeFragment)\n\n const serializedB = URLSerializer(B, excludeFragment)\n\n return serializedA === serializedB\n}\n\n/**\n * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262\n * @param {string} header\n */\nfunction fieldValues (header) {\n assert(header !== null)\n\n const values = []\n\n for (let value of header.split(',')) {\n value = value.trim()\n\n if (!value.length) {\n continue\n } else if (!isValidHeaderName(value)) {\n continue\n }\n\n values.push(value)\n }\n\n return values\n}\n\nmodule.exports = {\n urlEquals,\n fieldValues\n}\n","// @ts-check\n\n'use strict'\n\n/* global WebAssembly */\n\nconst assert = require('assert')\nconst net = require('net')\nconst http = require('http')\nconst { pipeline } = require('stream')\nconst util = require('./core/util')\nconst timers = require('./timers')\nconst Request = require('./core/request')\nconst DispatcherBase = require('./dispatcher-base')\nconst {\n RequestContentLengthMismatchError,\n ResponseContentLengthMismatchError,\n InvalidArgumentError,\n RequestAbortedError,\n HeadersTimeoutError,\n HeadersOverflowError,\n SocketError,\n InformationalError,\n BodyTimeoutError,\n HTTPParserError,\n ResponseExceededMaxSizeError,\n ClientDestroyedError\n} = require('./core/errors')\nconst buildConnector = require('./core/connect')\nconst {\n kUrl,\n kReset,\n kServerName,\n kClient,\n kBusy,\n kParser,\n kConnect,\n kBlocking,\n kResuming,\n kRunning,\n kPending,\n kSize,\n kWriting,\n kQueue,\n kConnected,\n kConnecting,\n kNeedDrain,\n kNoRef,\n kKeepAliveDefaultTimeout,\n kHostHeader,\n kPendingIdx,\n kRunningIdx,\n kError,\n kPipelining,\n kSocket,\n kKeepAliveTimeoutValue,\n kMaxHeadersSize,\n kKeepAliveMaxTimeout,\n kKeepAliveTimeoutThreshold,\n kHeadersTimeout,\n kBodyTimeout,\n kStrictContentLength,\n kConnector,\n kMaxRedirections,\n kMaxRequests,\n kCounter,\n kClose,\n kDestroy,\n kDispatch,\n kInterceptors,\n kLocalAddress,\n kMaxResponseSize,\n kHTTPConnVersion,\n // HTTP2\n kHost,\n kHTTP2Session,\n kHTTP2SessionState,\n kHTTP2BuildRequest,\n kHTTP2CopyHeaders,\n kHTTP1BuildRequest\n} = require('./core/symbols')\n\n/** @type {import('http2')} */\nlet http2\ntry {\n http2 = require('http2')\n} catch {\n // @ts-ignore\n http2 = { constants: {} }\n}\n\nconst {\n constants: {\n HTTP2_HEADER_AUTHORITY,\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_SCHEME,\n HTTP2_HEADER_CONTENT_LENGTH,\n HTTP2_HEADER_EXPECT,\n HTTP2_HEADER_STATUS\n }\n} = http2\n\n// Experimental\nlet h2ExperimentalWarned = false\n\nconst FastBuffer = Buffer[Symbol.species]\n\nconst kClosedResolve = Symbol('kClosedResolve')\n\nconst channels = {}\n\ntry {\n const diagnosticsChannel = require('diagnostics_channel')\n channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')\n channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')\n channels.connectError = diagnosticsChannel.channel('undici:client:connectError')\n channels.connected = diagnosticsChannel.channel('undici:client:connected')\n} catch {\n channels.sendHeaders = { hasSubscribers: false }\n channels.beforeConnect = { hasSubscribers: false }\n channels.connectError = { hasSubscribers: false }\n channels.connected = { hasSubscribers: false }\n}\n\n/**\n * @type {import('../types/client').default}\n */\nclass Client extends DispatcherBase {\n /**\n *\n * @param {string|URL} url\n * @param {import('../types/client').Client.Options} options\n */\n constructor (url, {\n interceptors,\n maxHeaderSize,\n headersTimeout,\n socketTimeout,\n requestTimeout,\n connectTimeout,\n bodyTimeout,\n idleTimeout,\n keepAlive,\n keepAliveTimeout,\n maxKeepAliveTimeout,\n keepAliveMaxTimeout,\n keepAliveTimeoutThreshold,\n socketPath,\n pipelining,\n tls,\n strictContentLength,\n maxCachedSessions,\n maxRedirections,\n connect,\n maxRequestsPerClient,\n localAddress,\n maxResponseSize,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n // h2\n allowH2,\n maxConcurrentStreams\n } = {}) {\n super()\n\n if (keepAlive !== undefined) {\n throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')\n }\n\n if (socketTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (requestTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (idleTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')\n }\n\n if (maxKeepAliveTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')\n }\n\n if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {\n throw new InvalidArgumentError('invalid maxHeaderSize')\n }\n\n if (socketPath != null && typeof socketPath !== 'string') {\n throw new InvalidArgumentError('invalid socketPath')\n }\n\n if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {\n throw new InvalidArgumentError('invalid connectTimeout')\n }\n\n if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveTimeout')\n }\n\n if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveMaxTimeout')\n }\n\n if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {\n throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')\n }\n\n if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')\n }\n\n if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {\n throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')\n }\n\n if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {\n throw new InvalidArgumentError('localAddress must be valid string IP address')\n }\n\n if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {\n throw new InvalidArgumentError('maxResponseSize must be a positive number')\n }\n\n if (\n autoSelectFamilyAttemptTimeout != null &&\n (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)\n ) {\n throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')\n }\n\n // h2\n if (allowH2 != null && typeof allowH2 !== 'boolean') {\n throw new InvalidArgumentError('allowH2 must be a valid boolean value')\n }\n\n if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {\n throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)\n ? interceptors.Client\n : [createRedirectInterceptor({ maxRedirections })]\n this[kUrl] = util.parseOrigin(url)\n this[kConnector] = connect\n this[kSocket] = null\n this[kPipelining] = pipelining != null ? pipelining : 1\n this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize\n this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout\n this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout\n this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold\n this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]\n this[kServerName] = null\n this[kLocalAddress] = localAddress != null ? localAddress : null\n this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\\r\\n`\n this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3\n this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3\n this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength\n this[kMaxRedirections] = maxRedirections\n this[kMaxRequests] = maxRequestsPerClient\n this[kClosedResolve] = null\n this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1\n this[kHTTPConnVersion] = 'h1'\n\n // HTTP/2\n this[kHTTP2Session] = null\n this[kHTTP2SessionState] = !allowH2\n ? null\n : {\n // streams: null, // Fixed queue of streams - For future support of `push`\n openStreams: 0, // Keep track of them to decide wether or not unref the session\n maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server\n }\n this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`\n\n // kQueue is built up of 3 sections separated by\n // the kRunningIdx and kPendingIdx indices.\n // | complete | running | pending |\n // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length\n // kRunningIdx points to the first running element.\n // kPendingIdx points to the first pending element.\n // This implements a fast queue with an amortized\n // time of O(1).\n\n this[kQueue] = []\n this[kRunningIdx] = 0\n this[kPendingIdx] = 0\n }\n\n get pipelining () {\n return this[kPipelining]\n }\n\n set pipelining (value) {\n this[kPipelining] = value\n resume(this, true)\n }\n\n get [kPending] () {\n return this[kQueue].length - this[kPendingIdx]\n }\n\n get [kRunning] () {\n return this[kPendingIdx] - this[kRunningIdx]\n }\n\n get [kSize] () {\n return this[kQueue].length - this[kRunningIdx]\n }\n\n get [kConnected] () {\n return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed\n }\n\n get [kBusy] () {\n const socket = this[kSocket]\n return (\n (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||\n (this[kSize] >= (this[kPipelining] || 1)) ||\n this[kPending] > 0\n )\n }\n\n /* istanbul ignore: only used for test */\n [kConnect] (cb) {\n connect(this)\n this.once('connect', cb)\n }\n\n [kDispatch] (opts, handler) {\n const origin = opts.origin || this[kUrl].origin\n\n const request = this[kHTTPConnVersion] === 'h2'\n ? Request[kHTTP2BuildRequest](origin, opts, handler)\n : Request[kHTTP1BuildRequest](origin, opts, handler)\n\n this[kQueue].push(request)\n if (this[kResuming]) {\n // Do nothing.\n } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {\n // Wait a tick in case stream/iterator is ended in the same tick.\n this[kResuming] = 1\n process.nextTick(resume, this)\n } else {\n resume(this, true)\n }\n\n if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {\n this[kNeedDrain] = 2\n }\n\n return this[kNeedDrain] < 2\n }\n\n async [kClose] () {\n // TODO: for H2 we need to gracefully flush the remaining enqueued\n // request and close each stream.\n return new Promise((resolve) => {\n if (!this[kSize]) {\n resolve(null)\n } else {\n this[kClosedResolve] = resolve\n }\n })\n }\n\n async [kDestroy] (err) {\n return new Promise((resolve) => {\n const requests = this[kQueue].splice(this[kPendingIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(this, request, err)\n }\n\n const callback = () => {\n if (this[kClosedResolve]) {\n // TODO (fix): Should we error here with ClientDestroyedError?\n this[kClosedResolve]()\n this[kClosedResolve] = null\n }\n resolve()\n }\n\n if (this[kHTTP2Session] != null) {\n util.destroy(this[kHTTP2Session], err)\n this[kHTTP2Session] = null\n this[kHTTP2SessionState] = null\n }\n\n if (!this[kSocket]) {\n queueMicrotask(callback)\n } else {\n util.destroy(this[kSocket].on('close', callback), err)\n }\n\n resume(this)\n })\n }\n}\n\nfunction onHttp2SessionError (err) {\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n this[kSocket][kError] = err\n\n onError(this[kClient], err)\n}\n\nfunction onHttp2FrameError (type, code, id) {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n\n if (id === 0) {\n this[kSocket][kError] = err\n onError(this[kClient], err)\n }\n}\n\nfunction onHttp2SessionEnd () {\n util.destroy(this, new SocketError('other side closed'))\n util.destroy(this[kSocket], new SocketError('other side closed'))\n}\n\nfunction onHTTP2GoAway (code) {\n const client = this[kClient]\n const err = new InformationalError(`HTTP/2: \"GOAWAY\" frame received with code ${code}`)\n client[kSocket] = null\n client[kHTTP2Session] = null\n\n if (client.destroyed) {\n assert(this[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(this, request, err)\n }\n } else if (client[kRunning] > 0) {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect',\n client[kUrl],\n [client],\n err\n )\n\n resume(client)\n}\n\nconst constants = require('./llhttp/constants')\nconst createRedirectInterceptor = require('./interceptor/redirectInterceptor')\nconst EMPTY_BUF = Buffer.alloc(0)\n\nasync function lazyllhttp () {\n const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp-wasm.js') : undefined\n\n let mod\n try {\n mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd-wasm.js'), 'base64'))\n } catch (e) {\n /* istanbul ignore next */\n\n // We could check if the error was caused by the simd option not\n // being enabled, but the occurring of this other error\n // * https://github.com/emscripten-core/emscripten/issues/11495\n // got me to remove that check to avoid breaking Node 12.\n mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp-wasm.js'), 'base64'))\n }\n\n return await WebAssembly.instantiate(mod, {\n env: {\n /* eslint-disable camelcase */\n\n wasm_on_url: (p, at, len) => {\n /* istanbul ignore next */\n return 0\n },\n wasm_on_status: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_begin: (p) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onMessageBegin() || 0\n },\n wasm_on_header_field: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_header_value: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0\n },\n wasm_on_body: (p, at, len) => {\n assert.strictEqual(currentParser.ptr, p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_complete: (p) => {\n assert.strictEqual(currentParser.ptr, p)\n return currentParser.onMessageComplete() || 0\n }\n\n /* eslint-enable camelcase */\n }\n })\n}\n\nlet llhttpInstance = null\nlet llhttpPromise = lazyllhttp()\nllhttpPromise.catch()\n\nlet currentParser = null\nlet currentBufferRef = null\nlet currentBufferSize = 0\nlet currentBufferPtr = null\n\nconst TIMEOUT_HEADERS = 1\nconst TIMEOUT_BODY = 2\nconst TIMEOUT_IDLE = 3\n\nclass Parser {\n constructor (client, socket, { exports }) {\n assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)\n\n this.llhttp = exports\n this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)\n this.client = client\n this.socket = socket\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n this.statusCode = null\n this.statusText = ''\n this.upgrade = false\n this.headers = []\n this.headersSize = 0\n this.headersMaxSize = client[kMaxHeadersSize]\n this.shouldKeepAlive = false\n this.paused = false\n this.resume = this.resume.bind(this)\n\n this.bytesRead = 0\n\n this.keepAlive = ''\n this.contentLength = ''\n this.connection = ''\n this.maxResponseSize = client[kMaxResponseSize]\n }\n\n setTimeout (value, type) {\n this.timeoutType = type\n if (value !== this.timeoutValue) {\n timers.clearTimeout(this.timeout)\n if (value) {\n this.timeout = timers.setTimeout(onParserTimeout, value, this)\n // istanbul ignore else: only for jest\n if (this.timeout.unref) {\n this.timeout.unref()\n }\n } else {\n this.timeout = null\n }\n this.timeoutValue = value\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n }\n\n resume () {\n if (this.socket.destroyed || !this.paused) {\n return\n }\n\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_resume(this.ptr)\n\n assert(this.timeoutType === TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n this.paused = false\n this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.\n this.readMore()\n }\n\n readMore () {\n while (!this.paused && this.ptr) {\n const chunk = this.socket.read()\n if (chunk === null) {\n break\n }\n this.execute(chunk)\n }\n }\n\n execute (data) {\n assert(this.ptr != null)\n assert(currentParser == null)\n assert(!this.paused)\n\n const { socket, llhttp } = this\n\n if (data.length > currentBufferSize) {\n if (currentBufferPtr) {\n llhttp.free(currentBufferPtr)\n }\n currentBufferSize = Math.ceil(data.length / 4096) * 4096\n currentBufferPtr = llhttp.malloc(currentBufferSize)\n }\n\n new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)\n\n // Call `execute` on the wasm parser.\n // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,\n // and finally the length of bytes to parse.\n // The return value is an error code or `constants.ERROR.OK`.\n try {\n let ret\n\n try {\n currentBufferRef = data\n currentParser = this\n ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)\n /* eslint-disable-next-line no-useless-catch */\n } catch (err) {\n /* istanbul ignore next: difficult to make a test case for */\n throw err\n } finally {\n currentParser = null\n currentBufferRef = null\n }\n\n const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr\n\n if (ret === constants.ERROR.PAUSED_UPGRADE) {\n this.onUpgrade(data.slice(offset))\n } else if (ret === constants.ERROR.PAUSED) {\n this.paused = true\n socket.unshift(data.slice(offset))\n } else if (ret !== constants.ERROR.OK) {\n const ptr = llhttp.llhttp_get_error_reason(this.ptr)\n let message = ''\n /* istanbul ignore else: difficult to make a test case for */\n if (ptr) {\n const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)\n message =\n 'Response does not match the HTTP/1.1 protocol (' +\n Buffer.from(llhttp.memory.buffer, ptr, len).toString() +\n ')'\n }\n throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))\n }\n } catch (err) {\n util.destroy(socket, err)\n }\n }\n\n destroy () {\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_free(this.ptr)\n this.ptr = null\n\n timers.clearTimeout(this.timeout)\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n\n this.paused = false\n }\n\n onStatus (buf) {\n this.statusText = buf.toString()\n }\n\n onMessageBegin () {\n const { socket, client } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n if (!request) {\n return -1\n }\n }\n\n onHeaderField (buf) {\n const len = this.headers.length\n\n if ((len & 1) === 0) {\n this.headers.push(buf)\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n this.trackHeader(buf.length)\n }\n\n onHeaderValue (buf) {\n let len = this.headers.length\n\n if ((len & 1) === 1) {\n this.headers.push(buf)\n len += 1\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n const key = this.headers[len - 2]\n if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {\n this.keepAlive += buf.toString()\n } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {\n this.connection += buf.toString()\n } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {\n this.contentLength += buf.toString()\n }\n\n this.trackHeader(buf.length)\n }\n\n trackHeader (len) {\n this.headersSize += len\n if (this.headersSize >= this.headersMaxSize) {\n util.destroy(this.socket, new HeadersOverflowError())\n }\n }\n\n onUpgrade (head) {\n const { upgrade, client, socket, headers, statusCode } = this\n\n assert(upgrade)\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(!socket.destroyed)\n assert(socket === client[kSocket])\n assert(!this.paused)\n assert(request.upgrade || request.method === 'CONNECT')\n\n this.statusCode = null\n this.statusText = ''\n this.shouldKeepAlive = null\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n socket.unshift(head)\n\n socket[kParser].destroy()\n socket[kParser] = null\n\n socket[kClient] = null\n socket[kError] = null\n socket\n .removeListener('error', onSocketError)\n .removeListener('readable', onSocketReadable)\n .removeListener('end', onSocketEnd)\n .removeListener('close', onSocketClose)\n\n client[kSocket] = null\n client[kQueue][client[kRunningIdx]++] = null\n client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))\n\n try {\n request.onUpgrade(statusCode, headers, socket)\n } catch (err) {\n util.destroy(socket, err)\n }\n\n resume(client)\n }\n\n onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {\n const { client, socket, headers, statusText } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n\n /* istanbul ignore next: difficult to make a test case for */\n if (!request) {\n return -1\n }\n\n assert(!this.upgrade)\n assert(this.statusCode < 200)\n\n if (statusCode === 100) {\n util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))\n return -1\n }\n\n /* this can only happen if server is misbehaving */\n if (upgrade && !request.upgrade) {\n util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))\n return -1\n }\n\n assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)\n\n this.statusCode = statusCode\n this.shouldKeepAlive = (\n shouldKeepAlive ||\n // Override llhttp value which does not allow keepAlive for HEAD.\n (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')\n )\n\n if (this.statusCode >= 200) {\n const bodyTimeout = request.bodyTimeout != null\n ? request.bodyTimeout\n : client[kBodyTimeout]\n this.setTimeout(bodyTimeout, TIMEOUT_BODY)\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n if (request.method === 'CONNECT') {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n if (upgrade) {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n if (this.shouldKeepAlive && client[kPipelining]) {\n const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null\n\n if (keepAliveTimeout != null) {\n const timeout = Math.min(\n keepAliveTimeout - client[kKeepAliveTimeoutThreshold],\n client[kKeepAliveMaxTimeout]\n )\n if (timeout <= 0) {\n socket[kReset] = true\n } else {\n client[kKeepAliveTimeoutValue] = timeout\n }\n } else {\n client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]\n }\n } else {\n // Stop more requests from being dispatched.\n socket[kReset] = true\n }\n\n const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false\n\n if (request.aborted) {\n return -1\n }\n\n if (request.method === 'HEAD') {\n return 1\n }\n\n if (statusCode < 200) {\n return 1\n }\n\n if (socket[kBlocking]) {\n socket[kBlocking] = false\n resume(client)\n }\n\n return pause ? constants.ERROR.PAUSED : 0\n }\n\n onBody (buf) {\n const { client, socket, statusCode, maxResponseSize } = this\n\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert.strictEqual(this.timeoutType, TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n assert(statusCode >= 200)\n\n if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {\n util.destroy(socket, new ResponseExceededMaxSizeError())\n return -1\n }\n\n this.bytesRead += buf.length\n\n if (request.onData(buf) === false) {\n return constants.ERROR.PAUSED\n }\n }\n\n onMessageComplete () {\n const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this\n\n if (socket.destroyed && (!statusCode || shouldKeepAlive)) {\n return -1\n }\n\n if (upgrade) {\n return\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(statusCode >= 100)\n\n this.statusCode = null\n this.statusText = ''\n this.bytesRead = 0\n this.contentLength = ''\n this.keepAlive = ''\n this.connection = ''\n\n assert(this.headers.length % 2 === 0)\n this.headers = []\n this.headersSize = 0\n\n if (statusCode < 200) {\n return\n }\n\n /* istanbul ignore next: should be handled by llhttp? */\n if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {\n util.destroy(socket, new ResponseContentLengthMismatchError())\n return -1\n }\n\n request.onComplete(headers)\n\n client[kQueue][client[kRunningIdx]++] = null\n\n if (socket[kWriting]) {\n assert.strictEqual(client[kRunning], 0)\n // Response completed before request.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (!shouldKeepAlive) {\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (socket[kReset] && client[kRunning] === 0) {\n // Destroy socket once all requests have completed.\n // The request at the tail of the pipeline is the one\n // that requested reset and no further requests should\n // have been queued since then.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (client[kPipelining] === 1) {\n // We must wait a full event loop cycle to reuse this socket to make sure\n // that non-spec compliant servers are not closing the connection even if they\n // said they won't.\n setImmediate(resume, client)\n } else {\n resume(client)\n }\n }\n}\n\nfunction onParserTimeout (parser) {\n const { socket, timeoutType, client } = parser\n\n /* istanbul ignore else */\n if (timeoutType === TIMEOUT_HEADERS) {\n if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {\n assert(!parser.paused, 'cannot be paused while waiting for headers')\n util.destroy(socket, new HeadersTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_BODY) {\n if (!parser.paused) {\n util.destroy(socket, new BodyTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_IDLE) {\n assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])\n util.destroy(socket, new InformationalError('socket idle timeout'))\n }\n}\n\nfunction onSocketReadable () {\n const { [kParser]: parser } = this\n if (parser) {\n parser.readMore()\n }\n}\n\nfunction onSocketError (err) {\n const { [kClient]: client, [kParser]: parser } = this\n\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n if (client[kHTTPConnVersion] !== 'h2') {\n // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded\n // to the user.\n if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so for as a valid response.\n parser.onMessageComplete()\n return\n }\n }\n\n this[kError] = err\n\n onError(this[kClient], err)\n}\n\nfunction onError (client, err) {\n if (\n client[kRunning] === 0 &&\n err.code !== 'UND_ERR_INFO' &&\n err.code !== 'UND_ERR_SOCKET'\n ) {\n // Error is not caused by running request and not a recoverable\n // socket error.\n\n assert(client[kPendingIdx] === client[kRunningIdx])\n\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(client, request, err)\n }\n assert(client[kSize] === 0)\n }\n}\n\nfunction onSocketEnd () {\n const { [kParser]: parser, [kClient]: client } = this\n\n if (client[kHTTPConnVersion] !== 'h2') {\n if (parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n return\n }\n }\n\n util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))\n}\n\nfunction onSocketClose () {\n const { [kClient]: client, [kParser]: parser } = this\n\n if (client[kHTTPConnVersion] === 'h1' && parser) {\n if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n }\n\n this[kParser].destroy()\n this[kParser] = null\n }\n\n const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))\n\n client[kSocket] = null\n\n if (client.destroyed) {\n assert(client[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n errorRequest(client, request, err)\n }\n } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect', client[kUrl], [client], err)\n\n resume(client)\n}\n\nasync function connect (client) {\n assert(!client[kConnecting])\n assert(!client[kSocket])\n\n let { host, hostname, protocol, port } = client[kUrl]\n\n // Resolve ipv6\n if (hostname[0] === '[') {\n const idx = hostname.indexOf(']')\n\n assert(idx !== -1)\n const ip = hostname.substring(1, idx)\n\n assert(net.isIP(ip))\n hostname = ip\n }\n\n client[kConnecting] = true\n\n if (channels.beforeConnect.hasSubscribers) {\n channels.beforeConnect.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector]\n })\n }\n\n try {\n const socket = await new Promise((resolve, reject) => {\n client[kConnector]({\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n }, (err, socket) => {\n if (err) {\n reject(err)\n } else {\n resolve(socket)\n }\n })\n })\n\n if (client.destroyed) {\n util.destroy(socket.on('error', () => {}), new ClientDestroyedError())\n return\n }\n\n client[kConnecting] = false\n\n assert(socket)\n\n const isH2 = socket.alpnProtocol === 'h2'\n if (isH2) {\n if (!h2ExperimentalWarned) {\n h2ExperimentalWarned = true\n process.emitWarning('H2 support is experimental, expect them to change at any time.', {\n code: 'UNDICI-H2'\n })\n }\n\n const session = http2.connect(client[kUrl], {\n createConnection: () => socket,\n peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams\n })\n\n client[kHTTPConnVersion] = 'h2'\n session[kClient] = client\n session[kSocket] = socket\n session.on('error', onHttp2SessionError)\n session.on('frameError', onHttp2FrameError)\n session.on('end', onHttp2SessionEnd)\n session.on('goaway', onHTTP2GoAway)\n session.on('close', onSocketClose)\n session.unref()\n\n client[kHTTP2Session] = session\n socket[kHTTP2Session] = session\n } else {\n if (!llhttpInstance) {\n llhttpInstance = await llhttpPromise\n llhttpPromise = null\n }\n\n socket[kNoRef] = false\n socket[kWriting] = false\n socket[kReset] = false\n socket[kBlocking] = false\n socket[kParser] = new Parser(client, socket, llhttpInstance)\n }\n\n socket[kCounter] = 0\n socket[kMaxRequests] = client[kMaxRequests]\n socket[kClient] = client\n socket[kError] = null\n\n socket\n .on('error', onSocketError)\n .on('readable', onSocketReadable)\n .on('end', onSocketEnd)\n .on('close', onSocketClose)\n\n client[kSocket] = socket\n\n if (channels.connected.hasSubscribers) {\n channels.connected.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n socket\n })\n }\n client.emit('connect', client[kUrl], [client])\n } catch (err) {\n if (client.destroyed) {\n return\n }\n\n client[kConnecting] = false\n\n if (channels.connectError.hasSubscribers) {\n channels.connectError.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n error: err\n })\n }\n\n if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {\n assert(client[kRunning] === 0)\n while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {\n const request = client[kQueue][client[kPendingIdx]++]\n errorRequest(client, request, err)\n }\n } else {\n onError(client, err)\n }\n\n client.emit('connectionError', client[kUrl], [client], err)\n }\n\n resume(client)\n}\n\nfunction emitDrain (client) {\n client[kNeedDrain] = 0\n client.emit('drain', client[kUrl], [client])\n}\n\nfunction resume (client, sync) {\n if (client[kResuming] === 2) {\n return\n }\n\n client[kResuming] = 2\n\n _resume(client, sync)\n client[kResuming] = 0\n\n if (client[kRunningIdx] > 256) {\n client[kQueue].splice(0, client[kRunningIdx])\n client[kPendingIdx] -= client[kRunningIdx]\n client[kRunningIdx] = 0\n }\n}\n\nfunction _resume (client, sync) {\n while (true) {\n if (client.destroyed) {\n assert(client[kPending] === 0)\n return\n }\n\n if (client[kClosedResolve] && !client[kSize]) {\n client[kClosedResolve]()\n client[kClosedResolve] = null\n return\n }\n\n const socket = client[kSocket]\n\n if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {\n if (client[kSize] === 0) {\n if (!socket[kNoRef] && socket.unref) {\n socket.unref()\n socket[kNoRef] = true\n }\n } else if (socket[kNoRef] && socket.ref) {\n socket.ref()\n socket[kNoRef] = false\n }\n\n if (client[kSize] === 0) {\n if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {\n socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)\n }\n } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {\n if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {\n const request = client[kQueue][client[kRunningIdx]]\n const headersTimeout = request.headersTimeout != null\n ? request.headersTimeout\n : client[kHeadersTimeout]\n socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)\n }\n }\n }\n\n if (client[kBusy]) {\n client[kNeedDrain] = 2\n } else if (client[kNeedDrain] === 2) {\n if (sync) {\n client[kNeedDrain] = 1\n process.nextTick(emitDrain, client)\n } else {\n emitDrain(client)\n }\n continue\n }\n\n if (client[kPending] === 0) {\n return\n }\n\n if (client[kRunning] >= (client[kPipelining] || 1)) {\n return\n }\n\n const request = client[kQueue][client[kPendingIdx]]\n\n if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {\n if (client[kRunning] > 0) {\n return\n }\n\n client[kServerName] = request.servername\n\n if (socket && socket.servername !== request.servername) {\n util.destroy(socket, new InformationalError('servername changed'))\n return\n }\n }\n\n if (client[kConnecting]) {\n return\n }\n\n if (!socket && !client[kHTTP2Session]) {\n connect(client)\n return\n }\n\n if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {\n return\n }\n\n if (client[kRunning] > 0 && !request.idempotent) {\n // Non-idempotent request cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return\n }\n\n if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {\n // Don't dispatch an upgrade until all preceding requests have completed.\n // A misbehaving server might upgrade the connection before all pipelined\n // request has completed.\n return\n }\n\n if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&\n (util.isStream(request.body) || util.isAsyncIterable(request.body))) {\n // Request with stream or iterator body can error while other requests\n // are inflight and indirectly error those as well.\n // Ensure this doesn't happen by waiting for inflight\n // to complete before dispatching.\n\n // Request with stream or iterator body cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return\n }\n\n if (!request.aborted && write(client, request)) {\n client[kPendingIdx]++\n } else {\n client[kQueue].splice(client[kPendingIdx], 1)\n }\n }\n}\n\n// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2\nfunction shouldSendContentLength (method) {\n return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'\n}\n\nfunction write (client, request) {\n if (client[kHTTPConnVersion] === 'h2') {\n writeH2(client, client[kHTTP2Session], request)\n return\n }\n\n const { body, method, path, host, upgrade, headers, blocking, reset } = request\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n const bodyLength = util.bodyLength(body)\n\n let contentLength = bodyLength\n\n if (contentLength === null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 && !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n const socket = client[kSocket]\n\n try {\n request.onConnect((err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n errorRequest(client, request, err || new RequestAbortedError())\n\n util.destroy(socket, new InformationalError('aborted'))\n })\n } catch (err) {\n errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n if (method === 'HEAD') {\n // https://github.com/mcollina/undici/issues/258\n // Close after a HEAD request to interop with misbehaving servers\n // that may send a body in the response.\n\n socket[kReset] = true\n }\n\n if (upgrade || method === 'CONNECT') {\n // On CONNECT or upgrade, block pipeline from dispatching further\n // requests on this connection.\n\n socket[kReset] = true\n }\n\n if (reset != null) {\n socket[kReset] = reset\n }\n\n if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {\n socket[kReset] = true\n }\n\n if (blocking) {\n socket[kBlocking] = true\n }\n\n let header = `${method} ${path} HTTP/1.1\\r\\n`\n\n if (typeof host === 'string') {\n header += `host: ${host}\\r\\n`\n } else {\n header += client[kHostHeader]\n }\n\n if (upgrade) {\n header += `connection: upgrade\\r\\nupgrade: ${upgrade}\\r\\n`\n } else if (client[kPipelining] && !socket[kReset]) {\n header += 'connection: keep-alive\\r\\n'\n } else {\n header += 'connection: close\\r\\n'\n }\n\n if (headers) {\n header += headers\n }\n\n if (channels.sendHeaders.hasSubscribers) {\n channels.sendHeaders.publish({ request, headers: header, socket })\n }\n\n /* istanbul ignore else: assertion */\n if (!body || bodyLength === 0) {\n if (contentLength === 0) {\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n assert(contentLength === null, 'no body must not have content length')\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n request.onRequestSent()\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(body)\n socket.uncork()\n request.onBodySent(body)\n request.onRequestSent()\n if (!expectsPayload) {\n socket[kReset] = true\n }\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })\n } else {\n writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })\n }\n } else if (util.isStream(body)) {\n writeStream({ body, client, request, socket, contentLength, header, expectsPayload })\n } else if (util.isIterable(body)) {\n writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })\n } else {\n assert(false)\n }\n\n return true\n}\n\nfunction writeH2 (client, session, request) {\n const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request\n\n let headers\n if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())\n else headers = reqHeaders\n\n if (upgrade) {\n errorRequest(client, request, new Error('Upgrade not supported for H2'))\n return false\n }\n\n try {\n // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?\n request.onConnect((err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n errorRequest(client, request, err || new RequestAbortedError())\n })\n } catch (err) {\n errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n /** @type {import('node:http2').ClientHttp2Stream} */\n let stream\n const h2State = client[kHTTP2SessionState]\n\n headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]\n headers[HTTP2_HEADER_METHOD] = method\n\n if (method === 'CONNECT') {\n session.ref()\n // we are already connected, streams are pending, first request\n // will create a new stream. We trigger a request to create the stream and wait until\n // `ready` event is triggered\n // We disabled endStream to allow the user to write to the stream\n stream = session.request(headers, { endStream: false, signal })\n\n if (stream.id && !stream.pending) {\n request.onUpgrade(null, null, stream)\n ++h2State.openStreams\n } else {\n stream.once('ready', () => {\n request.onUpgrade(null, null, stream)\n ++h2State.openStreams\n })\n }\n\n stream.once('close', () => {\n h2State.openStreams -= 1\n // TODO(HTTP/2): unref only if current streams count is 0\n if (h2State.openStreams === 0) session.unref()\n })\n\n return true\n }\n\n // https://tools.ietf.org/html/rfc7540#section-8.3\n // :path and :scheme headers must be omited when sending CONNECT\n\n headers[HTTP2_HEADER_PATH] = path\n headers[HTTP2_HEADER_SCHEME] = 'https'\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n let contentLength = util.bodyLength(body)\n\n if (contentLength == null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 || !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n if (contentLength != null) {\n assert(body, 'no body must not have content length')\n headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`\n }\n\n session.ref()\n\n const shouldEndStream = method === 'GET' || method === 'HEAD'\n if (expectContinue) {\n headers[HTTP2_HEADER_EXPECT] = '100-continue'\n stream = session.request(headers, { endStream: shouldEndStream, signal })\n\n stream.once('continue', writeBodyH2)\n } else {\n stream = session.request(headers, {\n endStream: shouldEndStream,\n signal\n })\n writeBodyH2()\n }\n\n // Increment counter as we have new several streams open\n ++h2State.openStreams\n\n stream.once('response', headers => {\n const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers\n\n if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {\n stream.pause()\n }\n })\n\n stream.once('end', () => {\n request.onComplete([])\n })\n\n stream.on('data', (chunk) => {\n if (request.onData(chunk) === false) {\n stream.pause()\n }\n })\n\n stream.once('close', () => {\n h2State.openStreams -= 1\n // TODO(HTTP/2): unref only if current streams count is 0\n if (h2State.openStreams === 0) {\n session.unref()\n }\n })\n\n stream.once('error', function (err) {\n if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {\n h2State.streams -= 1\n util.destroy(stream, err)\n }\n })\n\n stream.once('frameError', (type, code) => {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n errorRequest(client, request, err)\n\n if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {\n h2State.streams -= 1\n util.destroy(stream, err)\n }\n })\n\n // stream.on('aborted', () => {\n // // TODO(HTTP/2): Support aborted\n // })\n\n // stream.on('timeout', () => {\n // // TODO(HTTP/2): Support timeout\n // })\n\n // stream.on('push', headers => {\n // // TODO(HTTP/2): Suppor push\n // })\n\n // stream.on('trailers', headers => {\n // // TODO(HTTP/2): Support trailers\n // })\n\n return true\n\n function writeBodyH2 () {\n /* istanbul ignore else: assertion */\n if (!body) {\n request.onRequestSent()\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n stream.cork()\n stream.write(body)\n stream.uncork()\n stream.end()\n request.onBodySent(body)\n request.onRequestSent()\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable({\n client,\n request,\n contentLength,\n h2stream: stream,\n expectsPayload,\n body: body.stream(),\n socket: client[kSocket],\n header: ''\n })\n } else {\n writeBlob({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n h2stream: stream,\n header: '',\n socket: client[kSocket]\n })\n }\n } else if (util.isStream(body)) {\n writeStream({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n socket: client[kSocket],\n h2stream: stream,\n header: ''\n })\n } else if (util.isIterable(body)) {\n writeIterable({\n body,\n client,\n request,\n contentLength,\n expectsPayload,\n header: '',\n h2stream: stream,\n socket: client[kSocket]\n })\n } else {\n assert(false)\n }\n }\n}\n\nfunction writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')\n\n if (client[kHTTPConnVersion] === 'h2') {\n // For HTTP/2, is enough to pipe the stream\n const pipe = pipeline(\n body,\n h2stream,\n (err) => {\n if (err) {\n util.destroy(body, err)\n util.destroy(h2stream, err)\n } else {\n request.onRequestSent()\n }\n }\n )\n\n pipe.on('data', onPipeData)\n pipe.once('end', () => {\n pipe.removeListener('data', onPipeData)\n util.destroy(pipe)\n })\n\n function onPipeData (chunk) {\n request.onBodySent(chunk)\n }\n\n return\n }\n\n let finished = false\n\n const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })\n\n const onData = function (chunk) {\n if (finished) {\n return\n }\n\n try {\n if (!writer.write(chunk) && this.pause) {\n this.pause()\n }\n } catch (err) {\n util.destroy(this, err)\n }\n }\n const onDrain = function () {\n if (finished) {\n return\n }\n\n if (body.resume) {\n body.resume()\n }\n }\n const onAbort = function () {\n if (finished) {\n return\n }\n const err = new RequestAbortedError()\n queueMicrotask(() => onFinished(err))\n }\n const onFinished = function (err) {\n if (finished) {\n return\n }\n\n finished = true\n\n assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))\n\n socket\n .off('drain', onDrain)\n .off('error', onFinished)\n\n body\n .removeListener('data', onData)\n .removeListener('end', onFinished)\n .removeListener('error', onFinished)\n .removeListener('close', onAbort)\n\n if (!err) {\n try {\n writer.end()\n } catch (er) {\n err = er\n }\n }\n\n writer.destroy(err)\n\n if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {\n util.destroy(body, err)\n } else {\n util.destroy(body)\n }\n }\n\n body\n .on('data', onData)\n .on('end', onFinished)\n .on('error', onFinished)\n .on('close', onAbort)\n\n if (body.resume) {\n body.resume()\n }\n\n socket\n .on('drain', onDrain)\n .on('error', onFinished)\n}\n\nasync function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength === body.size, 'blob body must have content length')\n\n const isH2 = client[kHTTPConnVersion] === 'h2'\n try {\n if (contentLength != null && contentLength !== body.size) {\n throw new RequestContentLengthMismatchError()\n }\n\n const buffer = Buffer.from(await body.arrayBuffer())\n\n if (isH2) {\n h2stream.cork()\n h2stream.write(buffer)\n h2stream.uncork()\n } else {\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(buffer)\n socket.uncork()\n }\n\n request.onBodySent(buffer)\n request.onRequestSent()\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n resume(client)\n } catch (err) {\n util.destroy(isH2 ? h2stream : socket, err)\n }\n}\n\nasync function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')\n\n let callback = null\n function onDrain () {\n if (callback) {\n const cb = callback\n callback = null\n cb()\n }\n }\n\n const waitForDrain = () => new Promise((resolve, reject) => {\n assert(callback === null)\n\n if (socket[kError]) {\n reject(socket[kError])\n } else {\n callback = resolve\n }\n })\n\n if (client[kHTTPConnVersion] === 'h2') {\n h2stream\n .on('close', onDrain)\n .on('drain', onDrain)\n\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n const res = h2stream.write(chunk)\n request.onBodySent(chunk)\n if (!res) {\n await waitForDrain()\n }\n }\n } catch (err) {\n h2stream.destroy(err)\n } finally {\n request.onRequestSent()\n h2stream.end()\n h2stream\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n\n return\n }\n\n socket\n .on('close', onDrain)\n .on('drain', onDrain)\n\n const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (!writer.write(chunk)) {\n await waitForDrain()\n }\n }\n\n writer.end()\n } catch (err) {\n writer.destroy(err)\n } finally {\n socket\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n}\n\nclass AsyncWriter {\n constructor ({ socket, request, contentLength, client, expectsPayload, header }) {\n this.socket = socket\n this.request = request\n this.contentLength = contentLength\n this.client = client\n this.bytesWritten = 0\n this.expectsPayload = expectsPayload\n this.header = header\n\n socket[kWriting] = true\n }\n\n write (chunk) {\n const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return false\n }\n\n const len = Buffer.byteLength(chunk)\n if (!len) {\n return true\n }\n\n // We should defer writing chunks.\n if (contentLength !== null && bytesWritten + len > contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n socket.cork()\n\n if (bytesWritten === 0) {\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n if (contentLength === null) {\n socket.write(`${header}transfer-encoding: chunked\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n }\n }\n\n if (contentLength === null) {\n socket.write(`\\r\\n${len.toString(16)}\\r\\n`, 'latin1')\n }\n\n this.bytesWritten += len\n\n const ret = socket.write(chunk)\n\n socket.uncork()\n\n request.onBodySent(chunk)\n\n if (!ret) {\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n }\n\n return ret\n }\n\n end () {\n const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this\n request.onRequestSent()\n\n socket[kWriting] = false\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return\n }\n\n if (bytesWritten === 0) {\n if (expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body.\n\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n } else if (contentLength === null) {\n socket.write('\\r\\n0\\r\\n\\r\\n', 'latin1')\n }\n\n if (contentLength !== null && bytesWritten !== contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n } else {\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n }\n\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n\n resume(client)\n }\n\n destroy (err) {\n const { socket, client } = this\n\n socket[kWriting] = false\n\n if (err) {\n assert(client[kRunning] <= 1, 'pipeline should only contain this request')\n util.destroy(socket, err)\n }\n }\n}\n\nfunction errorRequest (client, request, err) {\n try {\n request.onError(err)\n assert(request.aborted)\n } catch (err) {\n client.emit('error', err)\n }\n}\n\nmodule.exports = Client\n","'use strict'\n\n/* istanbul ignore file: only for Node 12 */\n\nconst { kConnected, kSize } = require('../core/symbols')\n\nclass CompatWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value[kConnected] === 0 && this.value[kSize] === 0\n ? undefined\n : this.value\n }\n}\n\nclass CompatFinalizer {\n constructor (finalizer) {\n this.finalizer = finalizer\n }\n\n register (dispatcher, key) {\n if (dispatcher.on) {\n dispatcher.on('disconnect', () => {\n if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {\n this.finalizer(key)\n }\n })\n }\n }\n}\n\nmodule.exports = function () {\n // FIXME: remove workaround when the Node bug is fixed\n // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\n if (process.env.NODE_V8_COVERAGE) {\n return {\n WeakRef: CompatWeakRef,\n FinalizationRegistry: CompatFinalizer\n }\n }\n return {\n WeakRef: global.WeakRef || CompatWeakRef,\n FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer\n }\n}\n","'use strict'\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size\nconst maxAttributeValueSize = 1024\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size\nconst maxNameValuePairSize = 4096\n\nmodule.exports = {\n maxAttributeValueSize,\n maxNameValuePairSize\n}\n","'use strict'\n\nconst { parseSetCookie } = require('./parse')\nconst { stringify } = require('./util')\nconst { webidl } = require('../fetch/webidl')\nconst { Headers } = require('../fetch/headers')\n\n/**\n * @typedef {Object} Cookie\n * @property {string} name\n * @property {string} value\n * @property {Date|number|undefined} expires\n * @property {number|undefined} maxAge\n * @property {string|undefined} domain\n * @property {string|undefined} path\n * @property {boolean|undefined} secure\n * @property {boolean|undefined} httpOnly\n * @property {'Strict'|'Lax'|'None'} sameSite\n * @property {string[]} unparsed\n */\n\n/**\n * @param {Headers} headers\n * @returns {Record}\n */\nfunction getCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookie = headers.get('cookie')\n const out = {}\n\n if (!cookie) {\n return out\n }\n\n for (const piece of cookie.split(';')) {\n const [name, ...value] = piece.split('=')\n\n out[name.trim()] = value.join('=')\n }\n\n return out\n}\n\n/**\n * @param {Headers} headers\n * @param {string} name\n * @param {{ path?: string, domain?: string }|undefined} attributes\n * @returns {void}\n */\nfunction deleteCookie (headers, name, attributes) {\n webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n name = webidl.converters.DOMString(name)\n attributes = webidl.converters.DeleteCookieAttributes(attributes)\n\n // Matches behavior of\n // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278\n setCookie(headers, {\n name,\n value: '',\n expires: new Date(0),\n ...attributes\n })\n}\n\n/**\n * @param {Headers} headers\n * @returns {Cookie[]}\n */\nfunction getSetCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookies = headers.getSetCookie()\n\n if (!cookies) {\n return []\n }\n\n return cookies.map((pair) => parseSetCookie(pair))\n}\n\n/**\n * @param {Headers} headers\n * @param {Cookie} cookie\n * @returns {void}\n */\nfunction setCookie (headers, cookie) {\n webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n cookie = webidl.converters.Cookie(cookie)\n\n const str = stringify(cookie)\n\n if (str) {\n headers.append('Set-Cookie', stringify(cookie))\n }\n}\n\nwebidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: null\n }\n])\n\nwebidl.converters.Cookie = webidl.dictionaryConverter([\n {\n converter: webidl.converters.DOMString,\n key: 'name'\n },\n {\n converter: webidl.converters.DOMString,\n key: 'value'\n },\n {\n converter: webidl.nullableConverter((value) => {\n if (typeof value === 'number') {\n return webidl.converters['unsigned long long'](value)\n }\n\n return new Date(value)\n }),\n key: 'expires',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters['long long']),\n key: 'maxAge',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'secure',\n defaultValue: null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'httpOnly',\n defaultValue: null\n },\n {\n converter: webidl.converters.USVString,\n key: 'sameSite',\n allowedValues: ['Strict', 'Lax', 'None']\n },\n {\n converter: webidl.sequenceConverter(webidl.converters.DOMString),\n key: 'unparsed',\n defaultValue: []\n }\n])\n\nmodule.exports = {\n getCookies,\n deleteCookie,\n getSetCookies,\n setCookie\n}\n","'use strict'\n\nconst { maxNameValuePairSize, maxAttributeValueSize } = require('./constants')\nconst { isCTLExcludingHtab } = require('./util')\nconst { collectASequenceOfCodePointsFast } = require('../fetch/dataURL')\nconst assert = require('assert')\n\n/**\n * @description Parses the field-value attributes of a set-cookie header string.\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} header\n * @returns if the header is invalid, null will be returned\n */\nfunction parseSetCookie (header) {\n // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F\n // character (CTL characters excluding HTAB): Abort these steps and\n // ignore the set-cookie-string entirely.\n if (isCTLExcludingHtab(header)) {\n return null\n }\n\n let nameValuePair = ''\n let unparsedAttributes = ''\n let name = ''\n let value = ''\n\n // 2. If the set-cookie-string contains a %x3B (\";\") character:\n if (header.includes(';')) {\n // 1. The name-value-pair string consists of the characters up to,\n // but not including, the first %x3B (\";\"), and the unparsed-\n // attributes consist of the remainder of the set-cookie-string\n // (including the %x3B (\";\") in question).\n const position = { position: 0 }\n\n nameValuePair = collectASequenceOfCodePointsFast(';', header, position)\n unparsedAttributes = header.slice(position.position)\n } else {\n // Otherwise:\n\n // 1. The name-value-pair string consists of all the characters\n // contained in the set-cookie-string, and the unparsed-\n // attributes is the empty string.\n nameValuePair = header\n }\n\n // 3. If the name-value-pair string lacks a %x3D (\"=\") character, then\n // the name string is empty, and the value string is the value of\n // name-value-pair.\n if (!nameValuePair.includes('=')) {\n value = nameValuePair\n } else {\n // Otherwise, the name string consists of the characters up to, but\n // not including, the first %x3D (\"=\") character, and the (possibly\n // empty) value string consists of the characters after the first\n // %x3D (\"=\") character.\n const position = { position: 0 }\n name = collectASequenceOfCodePointsFast(\n '=',\n nameValuePair,\n position\n )\n value = nameValuePair.slice(position.position + 1)\n }\n\n // 4. Remove any leading or trailing WSP characters from the name\n // string and the value string.\n name = name.trim()\n value = value.trim()\n\n // 5. If the sum of the lengths of the name string and the value string\n // is more than 4096 octets, abort these steps and ignore the set-\n // cookie-string entirely.\n if (name.length + value.length > maxNameValuePairSize) {\n return null\n }\n\n // 6. The cookie-name is the name string, and the cookie-value is the\n // value string.\n return {\n name, value, ...parseUnparsedAttributes(unparsedAttributes)\n }\n}\n\n/**\n * Parses the remaining attributes of a set-cookie header\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} unparsedAttributes\n * @param {[Object.]={}} cookieAttributeList\n */\nfunction parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {\n // 1. If the unparsed-attributes string is empty, skip the rest of\n // these steps.\n if (unparsedAttributes.length === 0) {\n return cookieAttributeList\n }\n\n // 2. Discard the first character of the unparsed-attributes (which\n // will be a %x3B (\";\") character).\n assert(unparsedAttributes[0] === ';')\n unparsedAttributes = unparsedAttributes.slice(1)\n\n let cookieAv = ''\n\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n if (unparsedAttributes.includes(';')) {\n // 1. Consume the characters of the unparsed-attributes up to, but\n // not including, the first %x3B (\";\") character.\n cookieAv = collectASequenceOfCodePointsFast(\n ';',\n unparsedAttributes,\n { position: 0 }\n )\n unparsedAttributes = unparsedAttributes.slice(cookieAv.length)\n } else {\n // Otherwise:\n\n // 1. Consume the remainder of the unparsed-attributes.\n cookieAv = unparsedAttributes\n unparsedAttributes = ''\n }\n\n // Let the cookie-av string be the characters consumed in this step.\n\n let attributeName = ''\n let attributeValue = ''\n\n // 4. If the cookie-av string contains a %x3D (\"=\") character:\n if (cookieAv.includes('=')) {\n // 1. The (possibly empty) attribute-name string consists of the\n // characters up to, but not including, the first %x3D (\"=\")\n // character, and the (possibly empty) attribute-value string\n // consists of the characters after the first %x3D (\"=\")\n // character.\n const position = { position: 0 }\n\n attributeName = collectASequenceOfCodePointsFast(\n '=',\n cookieAv,\n position\n )\n attributeValue = cookieAv.slice(position.position + 1)\n } else {\n // Otherwise:\n\n // 1. The attribute-name string consists of the entire cookie-av\n // string, and the attribute-value string is empty.\n attributeName = cookieAv\n }\n\n // 5. Remove any leading or trailing WSP characters from the attribute-\n // name string and the attribute-value string.\n attributeName = attributeName.trim()\n attributeValue = attributeValue.trim()\n\n // 6. If the attribute-value is longer than 1024 octets, ignore the\n // cookie-av string and return to Step 1 of this algorithm.\n if (attributeValue.length > maxAttributeValueSize) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 7. Process the attribute-name and attribute-value according to the\n // requirements in the following subsections. (Notice that\n // attributes with unrecognized attribute-names are ignored.)\n const attributeNameLowercase = attributeName.toLowerCase()\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1\n // If the attribute-name case-insensitively matches the string\n // \"Expires\", the user agent MUST process the cookie-av as follows.\n if (attributeNameLowercase === 'expires') {\n // 1. Let the expiry-time be the result of parsing the attribute-value\n // as cookie-date (see Section 5.1.1).\n const expiryTime = new Date(attributeValue)\n\n // 2. If the attribute-value failed to parse as a cookie date, ignore\n // the cookie-av.\n\n cookieAttributeList.expires = expiryTime\n } else if (attributeNameLowercase === 'max-age') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2\n // If the attribute-name case-insensitively matches the string \"Max-\n // Age\", the user agent MUST process the cookie-av as follows.\n\n // 1. If the first character of the attribute-value is not a DIGIT or a\n // \"-\" character, ignore the cookie-av.\n const charCode = attributeValue.charCodeAt(0)\n\n if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 2. If the remainder of attribute-value contains a non-DIGIT\n // character, ignore the cookie-av.\n if (!/^\\d+$/.test(attributeValue)) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 3. Let delta-seconds be the attribute-value converted to an integer.\n const deltaSeconds = Number(attributeValue)\n\n // 4. Let cookie-age-limit be the maximum age of the cookie (which\n // SHOULD be 400 days or less, see Section 4.1.2.2).\n\n // 5. Set delta-seconds to the smaller of its present value and cookie-\n // age-limit.\n // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)\n\n // 6. If delta-seconds is less than or equal to zero (0), let expiry-\n // time be the earliest representable date and time. Otherwise, let\n // the expiry-time be the current date and time plus delta-seconds\n // seconds.\n // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds\n\n // 7. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Max-Age and an attribute-value of expiry-time.\n cookieAttributeList.maxAge = deltaSeconds\n } else if (attributeNameLowercase === 'domain') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3\n // If the attribute-name case-insensitively matches the string \"Domain\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. Let cookie-domain be the attribute-value.\n let cookieDomain = attributeValue\n\n // 2. If cookie-domain starts with %x2E (\".\"), let cookie-domain be\n // cookie-domain without its leading %x2E (\".\").\n if (cookieDomain[0] === '.') {\n cookieDomain = cookieDomain.slice(1)\n }\n\n // 3. Convert the cookie-domain to lower case.\n cookieDomain = cookieDomain.toLowerCase()\n\n // 4. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Domain and an attribute-value of cookie-domain.\n cookieAttributeList.domain = cookieDomain\n } else if (attributeNameLowercase === 'path') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4\n // If the attribute-name case-insensitively matches the string \"Path\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. If the attribute-value is empty or if the first character of the\n // attribute-value is not %x2F (\"/\"):\n let cookiePath = ''\n if (attributeValue.length === 0 || attributeValue[0] !== '/') {\n // 1. Let cookie-path be the default-path.\n cookiePath = '/'\n } else {\n // Otherwise:\n\n // 1. Let cookie-path be the attribute-value.\n cookiePath = attributeValue\n }\n\n // 2. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Path and an attribute-value of cookie-path.\n cookieAttributeList.path = cookiePath\n } else if (attributeNameLowercase === 'secure') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5\n // If the attribute-name case-insensitively matches the string \"Secure\",\n // the user agent MUST append an attribute to the cookie-attribute-list\n // with an attribute-name of Secure and an empty attribute-value.\n\n cookieAttributeList.secure = true\n } else if (attributeNameLowercase === 'httponly') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6\n // If the attribute-name case-insensitively matches the string\n // \"HttpOnly\", the user agent MUST append an attribute to the cookie-\n // attribute-list with an attribute-name of HttpOnly and an empty\n // attribute-value.\n\n cookieAttributeList.httpOnly = true\n } else if (attributeNameLowercase === 'samesite') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7\n // If the attribute-name case-insensitively matches the string\n // \"SameSite\", the user agent MUST process the cookie-av as follows:\n\n // 1. Let enforcement be \"Default\".\n let enforcement = 'Default'\n\n const attributeValueLowercase = attributeValue.toLowerCase()\n // 2. If cookie-av's attribute-value is a case-insensitive match for\n // \"None\", set enforcement to \"None\".\n if (attributeValueLowercase.includes('none')) {\n enforcement = 'None'\n }\n\n // 3. If cookie-av's attribute-value is a case-insensitive match for\n // \"Strict\", set enforcement to \"Strict\".\n if (attributeValueLowercase.includes('strict')) {\n enforcement = 'Strict'\n }\n\n // 4. If cookie-av's attribute-value is a case-insensitive match for\n // \"Lax\", set enforcement to \"Lax\".\n if (attributeValueLowercase.includes('lax')) {\n enforcement = 'Lax'\n }\n\n // 5. Append an attribute to the cookie-attribute-list with an\n // attribute-name of \"SameSite\" and an attribute-value of\n // enforcement.\n cookieAttributeList.sameSite = enforcement\n } else {\n cookieAttributeList.unparsed ??= []\n\n cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)\n }\n\n // 8. Return to Step 1 of this algorithm.\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n}\n\nmodule.exports = {\n parseSetCookie,\n parseUnparsedAttributes\n}\n","'use strict'\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nfunction isCTLExcludingHtab (value) {\n if (value.length === 0) {\n return false\n }\n\n for (const char of value) {\n const code = char.charCodeAt(0)\n\n if (\n (code >= 0x00 || code <= 0x08) ||\n (code >= 0x0A || code <= 0x1F) ||\n code === 0x7F\n ) {\n return false\n }\n }\n}\n\n/**\n CHAR = \n token = 1*\n separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n | \",\" | \";\" | \":\" | \"\\\" | <\">\n | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n | \"{\" | \"}\" | SP | HT\n * @param {string} name\n */\nfunction validateCookieName (name) {\n for (const char of name) {\n const code = char.charCodeAt(0)\n\n if (\n (code <= 0x20 || code > 0x7F) ||\n char === '(' ||\n char === ')' ||\n char === '>' ||\n char === '<' ||\n char === '@' ||\n char === ',' ||\n char === ';' ||\n char === ':' ||\n char === '\\\\' ||\n char === '\"' ||\n char === '/' ||\n char === '[' ||\n char === ']' ||\n char === '?' ||\n char === '=' ||\n char === '{' ||\n char === '}'\n ) {\n throw new Error('Invalid cookie name')\n }\n }\n}\n\n/**\n cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n ; US-ASCII characters excluding CTLs,\n ; whitespace DQUOTE, comma, semicolon,\n ; and backslash\n * @param {string} value\n */\nfunction validateCookieValue (value) {\n for (const char of value) {\n const code = char.charCodeAt(0)\n\n if (\n code < 0x21 || // exclude CTLs (0-31)\n code === 0x22 ||\n code === 0x2C ||\n code === 0x3B ||\n code === 0x5C ||\n code > 0x7E // non-ascii\n ) {\n throw new Error('Invalid header value')\n }\n }\n}\n\n/**\n * path-value = \n * @param {string} path\n */\nfunction validateCookiePath (path) {\n for (const char of path) {\n const code = char.charCodeAt(0)\n\n if (code < 0x21 || char === ';') {\n throw new Error('Invalid cookie path')\n }\n }\n}\n\n/**\n * I have no idea why these values aren't allowed to be honest,\n * but Deno tests these. - Khafra\n * @param {string} domain\n */\nfunction validateCookieDomain (domain) {\n if (\n domain.startsWith('-') ||\n domain.endsWith('.') ||\n domain.endsWith('-')\n ) {\n throw new Error('Invalid cookie domain')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1\n * @param {number|Date} date\n IMF-fixdate = day-name \",\" SP date1 SP time-of-day SP GMT\n ; fixed length/zone/capitalization subset of the format\n ; see Section 3.3 of [RFC5322]\n\n day-name = %x4D.6F.6E ; \"Mon\", case-sensitive\n / %x54.75.65 ; \"Tue\", case-sensitive\n / %x57.65.64 ; \"Wed\", case-sensitive\n / %x54.68.75 ; \"Thu\", case-sensitive\n / %x46.72.69 ; \"Fri\", case-sensitive\n / %x53.61.74 ; \"Sat\", case-sensitive\n / %x53.75.6E ; \"Sun\", case-sensitive\n date1 = day SP month SP year\n ; e.g., 02 Jun 1982\n\n day = 2DIGIT\n month = %x4A.61.6E ; \"Jan\", case-sensitive\n / %x46.65.62 ; \"Feb\", case-sensitive\n / %x4D.61.72 ; \"Mar\", case-sensitive\n / %x41.70.72 ; \"Apr\", case-sensitive\n / %x4D.61.79 ; \"May\", case-sensitive\n / %x4A.75.6E ; \"Jun\", case-sensitive\n / %x4A.75.6C ; \"Jul\", case-sensitive\n / %x41.75.67 ; \"Aug\", case-sensitive\n / %x53.65.70 ; \"Sep\", case-sensitive\n / %x4F.63.74 ; \"Oct\", case-sensitive\n / %x4E.6F.76 ; \"Nov\", case-sensitive\n / %x44.65.63 ; \"Dec\", case-sensitive\n year = 4DIGIT\n\n GMT = %x47.4D.54 ; \"GMT\", case-sensitive\n\n time-of-day = hour \":\" minute \":\" second\n ; 00:00:00 - 23:59:60 (leap second)\n\n hour = 2DIGIT\n minute = 2DIGIT\n second = 2DIGIT\n */\nfunction toIMFDate (date) {\n if (typeof date === 'number') {\n date = new Date(date)\n }\n\n const days = [\n 'Sun', 'Mon', 'Tue', 'Wed',\n 'Thu', 'Fri', 'Sat'\n ]\n\n const months = [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'\n ]\n\n const dayName = days[date.getUTCDay()]\n const day = date.getUTCDate().toString().padStart(2, '0')\n const month = months[date.getUTCMonth()]\n const year = date.getUTCFullYear()\n const hour = date.getUTCHours().toString().padStart(2, '0')\n const minute = date.getUTCMinutes().toString().padStart(2, '0')\n const second = date.getUTCSeconds().toString().padStart(2, '0')\n\n return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`\n}\n\n/**\n max-age-av = \"Max-Age=\" non-zero-digit *DIGIT\n ; In practice, both expires-av and max-age-av\n ; are limited to dates representable by the\n ; user agent.\n * @param {number} maxAge\n */\nfunction validateCookieMaxAge (maxAge) {\n if (maxAge < 0) {\n throw new Error('Invalid cookie max-age')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1\n * @param {import('./index').Cookie} cookie\n */\nfunction stringify (cookie) {\n if (cookie.name.length === 0) {\n return null\n }\n\n validateCookieName(cookie.name)\n validateCookieValue(cookie.value)\n\n const out = [`${cookie.name}=${cookie.value}`]\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2\n if (cookie.name.startsWith('__Secure-')) {\n cookie.secure = true\n }\n\n if (cookie.name.startsWith('__Host-')) {\n cookie.secure = true\n cookie.domain = null\n cookie.path = '/'\n }\n\n if (cookie.secure) {\n out.push('Secure')\n }\n\n if (cookie.httpOnly) {\n out.push('HttpOnly')\n }\n\n if (typeof cookie.maxAge === 'number') {\n validateCookieMaxAge(cookie.maxAge)\n out.push(`Max-Age=${cookie.maxAge}`)\n }\n\n if (cookie.domain) {\n validateCookieDomain(cookie.domain)\n out.push(`Domain=${cookie.domain}`)\n }\n\n if (cookie.path) {\n validateCookiePath(cookie.path)\n out.push(`Path=${cookie.path}`)\n }\n\n if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {\n out.push(`Expires=${toIMFDate(cookie.expires)}`)\n }\n\n if (cookie.sameSite) {\n out.push(`SameSite=${cookie.sameSite}`)\n }\n\n for (const part of cookie.unparsed) {\n if (!part.includes('=')) {\n throw new Error('Invalid unparsed')\n }\n\n const [key, ...value] = part.split('=')\n\n out.push(`${key.trim()}=${value.join('=')}`)\n }\n\n return out.join('; ')\n}\n\nmodule.exports = {\n isCTLExcludingHtab,\n validateCookieName,\n validateCookiePath,\n validateCookieValue,\n toIMFDate,\n stringify\n}\n","'use strict'\n\nconst net = require('net')\nconst assert = require('assert')\nconst util = require('./util')\nconst { InvalidArgumentError, ConnectTimeoutError } = require('./errors')\n\nlet tls // include tls conditionally since it is not always available\n\n// TODO: session re-use does not wait for the first\n// connection to resolve the session and might therefore\n// resolve the same servername multiple times even when\n// re-use is enabled.\n\nlet SessionCache\n// FIXME: remove workaround when the Node bug is fixed\n// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\nif (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {\n SessionCache = class WeakSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n this._sessionRegistry = new global.FinalizationRegistry((key) => {\n if (this._sessionCache.size < this._maxCachedSessions) {\n return\n }\n\n const ref = this._sessionCache.get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this._sessionCache.delete(key)\n }\n })\n }\n\n get (sessionKey) {\n const ref = this._sessionCache.get(sessionKey)\n return ref ? ref.deref() : null\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n this._sessionCache.set(sessionKey, new WeakRef(session))\n this._sessionRegistry.register(session, sessionKey)\n }\n }\n} else {\n SessionCache = class SimpleSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n }\n\n get (sessionKey) {\n return this._sessionCache.get(sessionKey)\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n if (this._sessionCache.size >= this._maxCachedSessions) {\n // remove the oldest session\n const { value: oldestKey } = this._sessionCache.keys().next()\n this._sessionCache.delete(oldestKey)\n }\n\n this._sessionCache.set(sessionKey, session)\n }\n }\n}\n\nfunction buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {\n if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {\n throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')\n }\n\n const options = { path: socketPath, ...opts }\n const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)\n timeout = timeout == null ? 10e3 : timeout\n allowH2 = allowH2 != null ? allowH2 : false\n return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {\n let socket\n if (protocol === 'https:') {\n if (!tls) {\n tls = require('tls')\n }\n servername = servername || options.servername || util.getServerName(host) || null\n\n const sessionKey = servername || hostname\n const session = sessionCache.get(sessionKey) || null\n\n assert(sessionKey)\n\n socket = tls.connect({\n highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...\n ...options,\n servername,\n session,\n localAddress,\n // TODO(HTTP/2): Add support for h2c\n ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],\n socket: httpSocket, // upgrade socket connection\n port: port || 443,\n host: hostname\n })\n\n socket\n .on('session', function (session) {\n // TODO (fix): Can a session become invalid once established? Don't think so?\n sessionCache.set(sessionKey, session)\n })\n } else {\n assert(!httpSocket, 'httpSocket can only be sent on TLS update')\n socket = net.connect({\n highWaterMark: 64 * 1024, // Same as nodejs fs streams.\n ...options,\n localAddress,\n port: port || 80,\n host: hostname\n })\n }\n\n // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket\n if (options.keepAlive == null || options.keepAlive) {\n const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay\n socket.setKeepAlive(true, keepAliveInitialDelay)\n }\n\n const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)\n\n socket\n .setNoDelay(true)\n .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {\n cancelTimeout()\n\n if (callback) {\n const cb = callback\n callback = null\n cb(null, this)\n }\n })\n .on('error', function (err) {\n cancelTimeout()\n\n if (callback) {\n const cb = callback\n callback = null\n cb(err)\n }\n })\n\n return socket\n }\n}\n\nfunction setupTimeout (onConnectTimeout, timeout) {\n if (!timeout) {\n return () => {}\n }\n\n let s1 = null\n let s2 = null\n const timeoutId = setTimeout(() => {\n // setImmediate is added to make sure that we priotorise socket error events over timeouts\n s1 = setImmediate(() => {\n if (process.platform === 'win32') {\n // Windows needs an extra setImmediate probably due to implementation differences in the socket logic\n s2 = setImmediate(() => onConnectTimeout())\n } else {\n onConnectTimeout()\n }\n })\n }, timeout)\n return () => {\n clearTimeout(timeoutId)\n clearImmediate(s1)\n clearImmediate(s2)\n }\n}\n\nfunction onConnectTimeout (socket) {\n util.destroy(socket, new ConnectTimeoutError())\n}\n\nmodule.exports = buildConnector\n","'use strict'\n\n/** @type {Record} */\nconst headerNameLowerCasedRecord = {}\n\n// https://developer.mozilla.org/docs/Web/HTTP/Headers\nconst wellknownHeaderNames = [\n 'Accept',\n 'Accept-Encoding',\n 'Accept-Language',\n 'Accept-Ranges',\n 'Access-Control-Allow-Credentials',\n 'Access-Control-Allow-Headers',\n 'Access-Control-Allow-Methods',\n 'Access-Control-Allow-Origin',\n 'Access-Control-Expose-Headers',\n 'Access-Control-Max-Age',\n 'Access-Control-Request-Headers',\n 'Access-Control-Request-Method',\n 'Age',\n 'Allow',\n 'Alt-Svc',\n 'Alt-Used',\n 'Authorization',\n 'Cache-Control',\n 'Clear-Site-Data',\n 'Connection',\n 'Content-Disposition',\n 'Content-Encoding',\n 'Content-Language',\n 'Content-Length',\n 'Content-Location',\n 'Content-Range',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Content-Type',\n 'Cookie',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Resource-Policy',\n 'Date',\n 'Device-Memory',\n 'Downlink',\n 'ECT',\n 'ETag',\n 'Expect',\n 'Expect-CT',\n 'Expires',\n 'Forwarded',\n 'From',\n 'Host',\n 'If-Match',\n 'If-Modified-Since',\n 'If-None-Match',\n 'If-Range',\n 'If-Unmodified-Since',\n 'Keep-Alive',\n 'Last-Modified',\n 'Link',\n 'Location',\n 'Max-Forwards',\n 'Origin',\n 'Permissions-Policy',\n 'Pragma',\n 'Proxy-Authenticate',\n 'Proxy-Authorization',\n 'RTT',\n 'Range',\n 'Referer',\n 'Referrer-Policy',\n 'Refresh',\n 'Retry-After',\n 'Sec-WebSocket-Accept',\n 'Sec-WebSocket-Extensions',\n 'Sec-WebSocket-Key',\n 'Sec-WebSocket-Protocol',\n 'Sec-WebSocket-Version',\n 'Server',\n 'Server-Timing',\n 'Service-Worker-Allowed',\n 'Service-Worker-Navigation-Preload',\n 'Set-Cookie',\n 'SourceMap',\n 'Strict-Transport-Security',\n 'Supports-Loading-Mode',\n 'TE',\n 'Timing-Allow-Origin',\n 'Trailer',\n 'Transfer-Encoding',\n 'Upgrade',\n 'Upgrade-Insecure-Requests',\n 'User-Agent',\n 'Vary',\n 'Via',\n 'WWW-Authenticate',\n 'X-Content-Type-Options',\n 'X-DNS-Prefetch-Control',\n 'X-Frame-Options',\n 'X-Permitted-Cross-Domain-Policies',\n 'X-Powered-By',\n 'X-Requested-With',\n 'X-XSS-Protection'\n]\n\nfor (let i = 0; i < wellknownHeaderNames.length; ++i) {\n const key = wellknownHeaderNames[i]\n const lowerCasedKey = key.toLowerCase()\n headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =\n lowerCasedKey\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(headerNameLowerCasedRecord, null)\n\nmodule.exports = {\n wellknownHeaderNames,\n headerNameLowerCasedRecord\n}\n","'use strict'\n\nclass UndiciError extends Error {\n constructor (message) {\n super(message)\n this.name = 'UndiciError'\n this.code = 'UND_ERR'\n }\n}\n\nclass ConnectTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ConnectTimeoutError)\n this.name = 'ConnectTimeoutError'\n this.message = message || 'Connect Timeout Error'\n this.code = 'UND_ERR_CONNECT_TIMEOUT'\n }\n}\n\nclass HeadersTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, HeadersTimeoutError)\n this.name = 'HeadersTimeoutError'\n this.message = message || 'Headers Timeout Error'\n this.code = 'UND_ERR_HEADERS_TIMEOUT'\n }\n}\n\nclass HeadersOverflowError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, HeadersOverflowError)\n this.name = 'HeadersOverflowError'\n this.message = message || 'Headers Overflow Error'\n this.code = 'UND_ERR_HEADERS_OVERFLOW'\n }\n}\n\nclass BodyTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, BodyTimeoutError)\n this.name = 'BodyTimeoutError'\n this.message = message || 'Body Timeout Error'\n this.code = 'UND_ERR_BODY_TIMEOUT'\n }\n}\n\nclass ResponseStatusCodeError extends UndiciError {\n constructor (message, statusCode, headers, body) {\n super(message)\n Error.captureStackTrace(this, ResponseStatusCodeError)\n this.name = 'ResponseStatusCodeError'\n this.message = message || 'Response Status Code Error'\n this.code = 'UND_ERR_RESPONSE_STATUS_CODE'\n this.body = body\n this.status = statusCode\n this.statusCode = statusCode\n this.headers = headers\n }\n}\n\nclass InvalidArgumentError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InvalidArgumentError)\n this.name = 'InvalidArgumentError'\n this.message = message || 'Invalid Argument Error'\n this.code = 'UND_ERR_INVALID_ARG'\n }\n}\n\nclass InvalidReturnValueError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InvalidReturnValueError)\n this.name = 'InvalidReturnValueError'\n this.message = message || 'Invalid Return Value Error'\n this.code = 'UND_ERR_INVALID_RETURN_VALUE'\n }\n}\n\nclass RequestAbortedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, RequestAbortedError)\n this.name = 'AbortError'\n this.message = message || 'Request aborted'\n this.code = 'UND_ERR_ABORTED'\n }\n}\n\nclass InformationalError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, InformationalError)\n this.name = 'InformationalError'\n this.message = message || 'Request information'\n this.code = 'UND_ERR_INFO'\n }\n}\n\nclass RequestContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, RequestContentLengthMismatchError)\n this.name = 'RequestContentLengthMismatchError'\n this.message = message || 'Request body length does not match content-length header'\n this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'\n }\n}\n\nclass ResponseContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ResponseContentLengthMismatchError)\n this.name = 'ResponseContentLengthMismatchError'\n this.message = message || 'Response body length does not match content-length header'\n this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'\n }\n}\n\nclass ClientDestroyedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ClientDestroyedError)\n this.name = 'ClientDestroyedError'\n this.message = message || 'The client is destroyed'\n this.code = 'UND_ERR_DESTROYED'\n }\n}\n\nclass ClientClosedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ClientClosedError)\n this.name = 'ClientClosedError'\n this.message = message || 'The client is closed'\n this.code = 'UND_ERR_CLOSED'\n }\n}\n\nclass SocketError extends UndiciError {\n constructor (message, socket) {\n super(message)\n Error.captureStackTrace(this, SocketError)\n this.name = 'SocketError'\n this.message = message || 'Socket error'\n this.code = 'UND_ERR_SOCKET'\n this.socket = socket\n }\n}\n\nclass NotSupportedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, NotSupportedError)\n this.name = 'NotSupportedError'\n this.message = message || 'Not supported error'\n this.code = 'UND_ERR_NOT_SUPPORTED'\n }\n}\n\nclass BalancedPoolMissingUpstreamError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, NotSupportedError)\n this.name = 'MissingUpstreamError'\n this.message = message || 'No upstream has been added to the BalancedPool'\n this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'\n }\n}\n\nclass HTTPParserError extends Error {\n constructor (message, code, data) {\n super(message)\n Error.captureStackTrace(this, HTTPParserError)\n this.name = 'HTTPParserError'\n this.code = code ? `HPE_${code}` : undefined\n this.data = data ? data.toString() : undefined\n }\n}\n\nclass ResponseExceededMaxSizeError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, ResponseExceededMaxSizeError)\n this.name = 'ResponseExceededMaxSizeError'\n this.message = message || 'Response content exceeded max size'\n this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'\n }\n}\n\nclass RequestRetryError extends UndiciError {\n constructor (message, code, { headers, data }) {\n super(message)\n Error.captureStackTrace(this, RequestRetryError)\n this.name = 'RequestRetryError'\n this.message = message || 'Request retry error'\n this.code = 'UND_ERR_REQ_RETRY'\n this.statusCode = code\n this.data = data\n this.headers = headers\n }\n}\n\nmodule.exports = {\n HTTPParserError,\n UndiciError,\n HeadersTimeoutError,\n HeadersOverflowError,\n BodyTimeoutError,\n RequestContentLengthMismatchError,\n ConnectTimeoutError,\n ResponseStatusCodeError,\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError,\n ClientDestroyedError,\n ClientClosedError,\n InformationalError,\n SocketError,\n NotSupportedError,\n ResponseContentLengthMismatchError,\n BalancedPoolMissingUpstreamError,\n ResponseExceededMaxSizeError,\n RequestRetryError\n}\n","'use strict'\n\nconst {\n InvalidArgumentError,\n NotSupportedError\n} = require('./errors')\nconst assert = require('assert')\nconst { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = require('./symbols')\nconst util = require('./util')\n\n// tokenRegExp and headerCharRegex have been lifted from\n// https://github.com/nodejs/node/blob/main/lib/_http_common.js\n\n/**\n * Verifies that the given val is a valid HTTP token\n * per the rules defined in RFC 7230\n * See https://tools.ietf.org/html/rfc7230#section-3.2.6\n */\nconst tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/\n\n/**\n * Matches if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/\n\n// Verifies that a given path is valid does not contain control chars \\x00 to \\x20\nconst invalidPathRegex = /[^\\u0021-\\u00ff]/\n\nconst kHandler = Symbol('handler')\n\nconst channels = {}\n\nlet extractBody\n\ntry {\n const diagnosticsChannel = require('diagnostics_channel')\n channels.create = diagnosticsChannel.channel('undici:request:create')\n channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')\n channels.headers = diagnosticsChannel.channel('undici:request:headers')\n channels.trailers = diagnosticsChannel.channel('undici:request:trailers')\n channels.error = diagnosticsChannel.channel('undici:request:error')\n} catch {\n channels.create = { hasSubscribers: false }\n channels.bodySent = { hasSubscribers: false }\n channels.headers = { hasSubscribers: false }\n channels.trailers = { hasSubscribers: false }\n channels.error = { hasSubscribers: false }\n}\n\nclass Request {\n constructor (origin, {\n path,\n method,\n body,\n headers,\n query,\n idempotent,\n blocking,\n upgrade,\n headersTimeout,\n bodyTimeout,\n reset,\n throwOnError,\n expectContinue\n }, handler) {\n if (typeof path !== 'string') {\n throw new InvalidArgumentError('path must be a string')\n } else if (\n path[0] !== '/' &&\n !(path.startsWith('http://') || path.startsWith('https://')) &&\n method !== 'CONNECT'\n ) {\n throw new InvalidArgumentError('path must be an absolute URL or start with a slash')\n } else if (invalidPathRegex.exec(path) !== null) {\n throw new InvalidArgumentError('invalid request path')\n }\n\n if (typeof method !== 'string') {\n throw new InvalidArgumentError('method must be a string')\n } else if (tokenRegExp.exec(method) === null) {\n throw new InvalidArgumentError('invalid request method')\n }\n\n if (upgrade && typeof upgrade !== 'string') {\n throw new InvalidArgumentError('upgrade must be a string')\n }\n\n if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('invalid headersTimeout')\n }\n\n if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('invalid bodyTimeout')\n }\n\n if (reset != null && typeof reset !== 'boolean') {\n throw new InvalidArgumentError('invalid reset')\n }\n\n if (expectContinue != null && typeof expectContinue !== 'boolean') {\n throw new InvalidArgumentError('invalid expectContinue')\n }\n\n this.headersTimeout = headersTimeout\n\n this.bodyTimeout = bodyTimeout\n\n this.throwOnError = throwOnError === true\n\n this.method = method\n\n this.abort = null\n\n if (body == null) {\n this.body = null\n } else if (util.isStream(body)) {\n this.body = body\n\n const rState = this.body._readableState\n if (!rState || !rState.autoDestroy) {\n this.endHandler = function autoDestroy () {\n util.destroy(this)\n }\n this.body.on('end', this.endHandler)\n }\n\n this.errorHandler = err => {\n if (this.abort) {\n this.abort(err)\n } else {\n this.error = err\n }\n }\n this.body.on('error', this.errorHandler)\n } else if (util.isBuffer(body)) {\n this.body = body.byteLength ? body : null\n } else if (ArrayBuffer.isView(body)) {\n this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null\n } else if (body instanceof ArrayBuffer) {\n this.body = body.byteLength ? Buffer.from(body) : null\n } else if (typeof body === 'string') {\n this.body = body.length ? Buffer.from(body) : null\n } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {\n this.body = body\n } else {\n throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')\n }\n\n this.completed = false\n\n this.aborted = false\n\n this.upgrade = upgrade || null\n\n this.path = query ? util.buildURL(path, query) : path\n\n this.origin = origin\n\n this.idempotent = idempotent == null\n ? method === 'HEAD' || method === 'GET'\n : idempotent\n\n this.blocking = blocking == null ? false : blocking\n\n this.reset = reset == null ? null : reset\n\n this.host = null\n\n this.contentLength = null\n\n this.contentType = null\n\n this.headers = ''\n\n // Only for H2\n this.expectContinue = expectContinue != null ? expectContinue : false\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(this, headers[i], headers[i + 1])\n }\n } else if (headers && typeof headers === 'object') {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n processHeader(this, key, headers[key])\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n if (util.isFormDataLike(this.body)) {\n if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {\n throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')\n }\n\n if (!extractBody) {\n extractBody = require('../fetch/body.js').extractBody\n }\n\n const [bodyStream, contentType] = extractBody(body)\n if (this.contentType == null) {\n this.contentType = contentType\n this.headers += `content-type: ${contentType}\\r\\n`\n }\n this.body = bodyStream.stream\n this.contentLength = bodyStream.length\n } else if (util.isBlobLike(body) && this.contentType == null && body.type) {\n this.contentType = body.type\n this.headers += `content-type: ${body.type}\\r\\n`\n }\n\n util.validateHandler(handler, method, upgrade)\n\n this.servername = util.getServerName(this.host)\n\n this[kHandler] = handler\n\n if (channels.create.hasSubscribers) {\n channels.create.publish({ request: this })\n }\n }\n\n onBodySent (chunk) {\n if (this[kHandler].onBodySent) {\n try {\n return this[kHandler].onBodySent(chunk)\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onRequestSent () {\n if (channels.bodySent.hasSubscribers) {\n channels.bodySent.publish({ request: this })\n }\n\n if (this[kHandler].onRequestSent) {\n try {\n return this[kHandler].onRequestSent()\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onConnect (abort) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (this.error) {\n abort(this.error)\n } else {\n this.abort = abort\n return this[kHandler].onConnect(abort)\n }\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (channels.headers.hasSubscribers) {\n channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })\n }\n\n try {\n return this[kHandler].onHeaders(statusCode, headers, resume, statusText)\n } catch (err) {\n this.abort(err)\n }\n }\n\n onData (chunk) {\n assert(!this.aborted)\n assert(!this.completed)\n\n try {\n return this[kHandler].onData(chunk)\n } catch (err) {\n this.abort(err)\n return false\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n assert(!this.aborted)\n assert(!this.completed)\n\n return this[kHandler].onUpgrade(statusCode, headers, socket)\n }\n\n onComplete (trailers) {\n this.onFinally()\n\n assert(!this.aborted)\n\n this.completed = true\n if (channels.trailers.hasSubscribers) {\n channels.trailers.publish({ request: this, trailers })\n }\n\n try {\n return this[kHandler].onComplete(trailers)\n } catch (err) {\n // TODO (fix): This might be a bad idea?\n this.onError(err)\n }\n }\n\n onError (error) {\n this.onFinally()\n\n if (channels.error.hasSubscribers) {\n channels.error.publish({ request: this, error })\n }\n\n if (this.aborted) {\n return\n }\n this.aborted = true\n\n return this[kHandler].onError(error)\n }\n\n onFinally () {\n if (this.errorHandler) {\n this.body.off('error', this.errorHandler)\n this.errorHandler = null\n }\n\n if (this.endHandler) {\n this.body.off('end', this.endHandler)\n this.endHandler = null\n }\n }\n\n // TODO: adjust to support H2\n addHeader (key, value) {\n processHeader(this, key, value)\n return this\n }\n\n static [kHTTP1BuildRequest] (origin, opts, handler) {\n // TODO: Migrate header parsing here, to make Requests\n // HTTP agnostic\n return new Request(origin, opts, handler)\n }\n\n static [kHTTP2BuildRequest] (origin, opts, handler) {\n const headers = opts.headers\n opts = { ...opts, headers: null }\n\n const request = new Request(origin, opts, handler)\n\n request.headers = {}\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(request, headers[i], headers[i + 1], true)\n }\n } else if (headers && typeof headers === 'object') {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n processHeader(request, key, headers[key], true)\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n return request\n }\n\n static [kHTTP2CopyHeaders] (raw) {\n const rawHeaders = raw.split('\\r\\n')\n const headers = {}\n\n for (const header of rawHeaders) {\n const [key, value] = header.split(': ')\n\n if (value == null || value.length === 0) continue\n\n if (headers[key]) headers[key] += `,${value}`\n else headers[key] = value\n }\n\n return headers\n }\n}\n\nfunction processHeaderValue (key, val, skipAppend) {\n if (val && typeof val === 'object') {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n\n val = val != null ? `${val}` : ''\n\n if (headerCharRegex.exec(val) !== null) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n\n return skipAppend ? val : `${key}: ${val}\\r\\n`\n}\n\nfunction processHeader (request, key, val, skipAppend = false) {\n if (val && (typeof val === 'object' && !Array.isArray(val))) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n } else if (val === undefined) {\n return\n }\n\n if (\n request.host === null &&\n key.length === 4 &&\n key.toLowerCase() === 'host'\n ) {\n if (headerCharRegex.exec(val) !== null) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n // Consumed by Client\n request.host = val\n } else if (\n request.contentLength === null &&\n key.length === 14 &&\n key.toLowerCase() === 'content-length'\n ) {\n request.contentLength = parseInt(val, 10)\n if (!Number.isFinite(request.contentLength)) {\n throw new InvalidArgumentError('invalid content-length header')\n }\n } else if (\n request.contentType === null &&\n key.length === 12 &&\n key.toLowerCase() === 'content-type'\n ) {\n request.contentType = val\n if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)\n else request.headers += processHeaderValue(key, val)\n } else if (\n key.length === 17 &&\n key.toLowerCase() === 'transfer-encoding'\n ) {\n throw new InvalidArgumentError('invalid transfer-encoding header')\n } else if (\n key.length === 10 &&\n key.toLowerCase() === 'connection'\n ) {\n const value = typeof val === 'string' ? val.toLowerCase() : null\n if (value !== 'close' && value !== 'keep-alive') {\n throw new InvalidArgumentError('invalid connection header')\n } else if (value === 'close') {\n request.reset = true\n }\n } else if (\n key.length === 10 &&\n key.toLowerCase() === 'keep-alive'\n ) {\n throw new InvalidArgumentError('invalid keep-alive header')\n } else if (\n key.length === 7 &&\n key.toLowerCase() === 'upgrade'\n ) {\n throw new InvalidArgumentError('invalid upgrade header')\n } else if (\n key.length === 6 &&\n key.toLowerCase() === 'expect'\n ) {\n throw new NotSupportedError('expect header not supported')\n } else if (tokenRegExp.exec(key) === null) {\n throw new InvalidArgumentError('invalid header key')\n } else {\n if (Array.isArray(val)) {\n for (let i = 0; i < val.length; i++) {\n if (skipAppend) {\n if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`\n else request.headers[key] = processHeaderValue(key, val[i], skipAppend)\n } else {\n request.headers += processHeaderValue(key, val[i])\n }\n }\n } else {\n if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)\n else request.headers += processHeaderValue(key, val)\n }\n }\n}\n\nmodule.exports = Request\n","module.exports = {\n kClose: Symbol('close'),\n kDestroy: Symbol('destroy'),\n kDispatch: Symbol('dispatch'),\n kUrl: Symbol('url'),\n kWriting: Symbol('writing'),\n kResuming: Symbol('resuming'),\n kQueue: Symbol('queue'),\n kConnect: Symbol('connect'),\n kConnecting: Symbol('connecting'),\n kHeadersList: Symbol('headers list'),\n kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),\n kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),\n kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),\n kKeepAliveTimeoutValue: Symbol('keep alive timeout'),\n kKeepAlive: Symbol('keep alive'),\n kHeadersTimeout: Symbol('headers timeout'),\n kBodyTimeout: Symbol('body timeout'),\n kServerName: Symbol('server name'),\n kLocalAddress: Symbol('local address'),\n kHost: Symbol('host'),\n kNoRef: Symbol('no ref'),\n kBodyUsed: Symbol('used'),\n kRunning: Symbol('running'),\n kBlocking: Symbol('blocking'),\n kPending: Symbol('pending'),\n kSize: Symbol('size'),\n kBusy: Symbol('busy'),\n kQueued: Symbol('queued'),\n kFree: Symbol('free'),\n kConnected: Symbol('connected'),\n kClosed: Symbol('closed'),\n kNeedDrain: Symbol('need drain'),\n kReset: Symbol('reset'),\n kDestroyed: Symbol.for('nodejs.stream.destroyed'),\n kMaxHeadersSize: Symbol('max headers size'),\n kRunningIdx: Symbol('running index'),\n kPendingIdx: Symbol('pending index'),\n kError: Symbol('error'),\n kClients: Symbol('clients'),\n kClient: Symbol('client'),\n kParser: Symbol('parser'),\n kOnDestroyed: Symbol('destroy callbacks'),\n kPipelining: Symbol('pipelining'),\n kSocket: Symbol('socket'),\n kHostHeader: Symbol('host header'),\n kConnector: Symbol('connector'),\n kStrictContentLength: Symbol('strict content length'),\n kMaxRedirections: Symbol('maxRedirections'),\n kMaxRequests: Symbol('maxRequestsPerClient'),\n kProxy: Symbol('proxy agent options'),\n kCounter: Symbol('socket request counter'),\n kInterceptors: Symbol('dispatch interceptors'),\n kMaxResponseSize: Symbol('max response size'),\n kHTTP2Session: Symbol('http2Session'),\n kHTTP2SessionState: Symbol('http2Session state'),\n kHTTP2BuildRequest: Symbol('http2 build request'),\n kHTTP1BuildRequest: Symbol('http1 build request'),\n kHTTP2CopyHeaders: Symbol('http2 copy headers'),\n kHTTPConnVersion: Symbol('http connection version'),\n kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),\n kConstruct: Symbol('constructable')\n}\n","'use strict'\n\nconst assert = require('assert')\nconst { kDestroyed, kBodyUsed } = require('./symbols')\nconst { IncomingMessage } = require('http')\nconst stream = require('stream')\nconst net = require('net')\nconst { InvalidArgumentError } = require('./errors')\nconst { Blob } = require('buffer')\nconst nodeUtil = require('util')\nconst { stringify } = require('querystring')\nconst { headerNameLowerCasedRecord } = require('./constants')\n\nconst [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))\n\nfunction nop () {}\n\nfunction isStream (obj) {\n return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'\n}\n\n// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)\nfunction isBlobLike (object) {\n return (Blob && object instanceof Blob) || (\n object &&\n typeof object === 'object' &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n /^(Blob|File)$/.test(object[Symbol.toStringTag])\n )\n}\n\nfunction buildURL (url, queryParams) {\n if (url.includes('?') || url.includes('#')) {\n throw new Error('Query params cannot be passed when url already contains \"?\" or \"#\".')\n }\n\n const stringified = stringify(queryParams)\n\n if (stringified) {\n url += '?' + stringified\n }\n\n return url\n}\n\nfunction parseURL (url) {\n if (typeof url === 'string') {\n url = new URL(url)\n\n if (!/^https?:/.test(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n return url\n }\n\n if (!url || typeof url !== 'object') {\n throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')\n }\n\n if (!/^https?:/.test(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n if (!(url instanceof URL)) {\n if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {\n throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')\n }\n\n if (url.path != null && typeof url.path !== 'string') {\n throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')\n }\n\n if (url.pathname != null && typeof url.pathname !== 'string') {\n throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')\n }\n\n if (url.hostname != null && typeof url.hostname !== 'string') {\n throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')\n }\n\n if (url.origin != null && typeof url.origin !== 'string') {\n throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')\n }\n\n const port = url.port != null\n ? url.port\n : (url.protocol === 'https:' ? 443 : 80)\n let origin = url.origin != null\n ? url.origin\n : `${url.protocol}//${url.hostname}:${port}`\n let path = url.path != null\n ? url.path\n : `${url.pathname || ''}${url.search || ''}`\n\n if (origin.endsWith('/')) {\n origin = origin.substring(0, origin.length - 1)\n }\n\n if (path && !path.startsWith('/')) {\n path = `/${path}`\n }\n // new URL(path, origin) is unsafe when `path` contains an absolute URL\n // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:\n // If first parameter is a relative URL, second param is required, and will be used as the base URL.\n // If first parameter is an absolute URL, a given second param will be ignored.\n url = new URL(origin + path)\n }\n\n return url\n}\n\nfunction parseOrigin (url) {\n url = parseURL(url)\n\n if (url.pathname !== '/' || url.search || url.hash) {\n throw new InvalidArgumentError('invalid url')\n }\n\n return url\n}\n\nfunction getHostname (host) {\n if (host[0] === '[') {\n const idx = host.indexOf(']')\n\n assert(idx !== -1)\n return host.substring(1, idx)\n }\n\n const idx = host.indexOf(':')\n if (idx === -1) return host\n\n return host.substring(0, idx)\n}\n\n// IP addresses are not valid server names per RFC6066\n// > Currently, the only server names supported are DNS hostnames\nfunction getServerName (host) {\n if (!host) {\n return null\n }\n\n assert.strictEqual(typeof host, 'string')\n\n const servername = getHostname(host)\n if (net.isIP(servername)) {\n return ''\n }\n\n return servername\n}\n\nfunction deepClone (obj) {\n return JSON.parse(JSON.stringify(obj))\n}\n\nfunction isAsyncIterable (obj) {\n return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')\n}\n\nfunction isIterable (obj) {\n return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))\n}\n\nfunction bodyLength (body) {\n if (body == null) {\n return 0\n } else if (isStream(body)) {\n const state = body._readableState\n return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)\n ? state.length\n : null\n } else if (isBlobLike(body)) {\n return body.size != null ? body.size : null\n } else if (isBuffer(body)) {\n return body.byteLength\n }\n\n return null\n}\n\nfunction isDestroyed (stream) {\n return !stream || !!(stream.destroyed || stream[kDestroyed])\n}\n\nfunction isReadableAborted (stream) {\n const state = stream && stream._readableState\n return isDestroyed(stream) && state && !state.endEmitted\n}\n\nfunction destroy (stream, err) {\n if (stream == null || !isStream(stream) || isDestroyed(stream)) {\n return\n }\n\n if (typeof stream.destroy === 'function') {\n if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {\n // See: https://github.com/nodejs/node/pull/38505/files\n stream.socket = null\n }\n\n stream.destroy(err)\n } else if (err) {\n process.nextTick((stream, err) => {\n stream.emit('error', err)\n }, stream, err)\n }\n\n if (stream.destroyed !== true) {\n stream[kDestroyed] = true\n }\n}\n\nconst KEEPALIVE_TIMEOUT_EXPR = /timeout=(\\d+)/\nfunction parseKeepAliveTimeout (val) {\n const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)\n return m ? parseInt(m[1], 10) * 1000 : null\n}\n\n/**\n * Retrieves a header name and returns its lowercase value.\n * @param {string | Buffer} value Header name\n * @returns {string}\n */\nfunction headerNameToString (value) {\n return headerNameLowerCasedRecord[value] || value.toLowerCase()\n}\n\nfunction parseHeaders (headers, obj = {}) {\n // For H2 support\n if (!Array.isArray(headers)) return headers\n\n for (let i = 0; i < headers.length; i += 2) {\n const key = headers[i].toString().toLowerCase()\n let val = obj[key]\n\n if (!val) {\n if (Array.isArray(headers[i + 1])) {\n obj[key] = headers[i + 1].map(x => x.toString('utf8'))\n } else {\n obj[key] = headers[i + 1].toString('utf8')\n }\n } else {\n if (!Array.isArray(val)) {\n val = [val]\n obj[key] = val\n }\n val.push(headers[i + 1].toString('utf8'))\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if ('content-length' in obj && 'content-disposition' in obj) {\n obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')\n }\n\n return obj\n}\n\nfunction parseRawHeaders (headers) {\n const ret = []\n let hasContentLength = false\n let contentDispositionIdx = -1\n\n for (let n = 0; n < headers.length; n += 2) {\n const key = headers[n + 0].toString()\n const val = headers[n + 1].toString('utf8')\n\n if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {\n ret.push(key, val)\n hasContentLength = true\n } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {\n contentDispositionIdx = ret.push(key, val) - 1\n } else {\n ret.push(key, val)\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if (hasContentLength && contentDispositionIdx !== -1) {\n ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')\n }\n\n return ret\n}\n\nfunction isBuffer (buffer) {\n // See, https://github.com/mcollina/undici/pull/319\n return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)\n}\n\nfunction validateHandler (handler, method, upgrade) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n if (typeof handler.onConnect !== 'function') {\n throw new InvalidArgumentError('invalid onConnect method')\n }\n\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {\n throw new InvalidArgumentError('invalid onBodySent method')\n }\n\n if (upgrade || method === 'CONNECT') {\n if (typeof handler.onUpgrade !== 'function') {\n throw new InvalidArgumentError('invalid onUpgrade method')\n }\n } else {\n if (typeof handler.onHeaders !== 'function') {\n throw new InvalidArgumentError('invalid onHeaders method')\n }\n\n if (typeof handler.onData !== 'function') {\n throw new InvalidArgumentError('invalid onData method')\n }\n\n if (typeof handler.onComplete !== 'function') {\n throw new InvalidArgumentError('invalid onComplete method')\n }\n }\n}\n\n// A body is disturbed if it has been read from and it cannot\n// be re-used without losing state or data.\nfunction isDisturbed (body) {\n return !!(body && (\n stream.isDisturbed\n ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?\n : body[kBodyUsed] ||\n body.readableDidRead ||\n (body._readableState && body._readableState.dataEmitted) ||\n isReadableAborted(body)\n ))\n}\n\nfunction isErrored (body) {\n return !!(body && (\n stream.isErrored\n ? stream.isErrored(body)\n : /state: 'errored'/.test(nodeUtil.inspect(body)\n )))\n}\n\nfunction isReadable (body) {\n return !!(body && (\n stream.isReadable\n ? stream.isReadable(body)\n : /state: 'readable'/.test(nodeUtil.inspect(body)\n )))\n}\n\nfunction getSocketInfo (socket) {\n return {\n localAddress: socket.localAddress,\n localPort: socket.localPort,\n remoteAddress: socket.remoteAddress,\n remotePort: socket.remotePort,\n remoteFamily: socket.remoteFamily,\n timeout: socket.timeout,\n bytesWritten: socket.bytesWritten,\n bytesRead: socket.bytesRead\n }\n}\n\nasync function * convertIterableToBuffer (iterable) {\n for await (const chunk of iterable) {\n yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n }\n}\n\nlet ReadableStream\nfunction ReadableStreamFrom (iterable) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n if (ReadableStream.from) {\n return ReadableStream.from(convertIterableToBuffer(iterable))\n }\n\n let iterator\n return new ReadableStream(\n {\n async start () {\n iterator = iterable[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { done, value } = await iterator.next()\n if (done) {\n queueMicrotask(() => {\n controller.close()\n })\n } else {\n const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)\n controller.enqueue(new Uint8Array(buf))\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n }\n },\n 0\n )\n}\n\n// The chunk should be a FormData instance and contains\n// all the required methods.\nfunction isFormDataLike (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.append === 'function' &&\n typeof object.delete === 'function' &&\n typeof object.get === 'function' &&\n typeof object.getAll === 'function' &&\n typeof object.has === 'function' &&\n typeof object.set === 'function' &&\n object[Symbol.toStringTag] === 'FormData'\n )\n}\n\nfunction throwIfAborted (signal) {\n if (!signal) { return }\n if (typeof signal.throwIfAborted === 'function') {\n signal.throwIfAborted()\n } else {\n if (signal.aborted) {\n // DOMException not available < v17.0.0\n const err = new Error('The operation was aborted')\n err.name = 'AbortError'\n throw err\n }\n }\n}\n\nfunction addAbortListener (signal, listener) {\n if ('addEventListener' in signal) {\n signal.addEventListener('abort', listener, { once: true })\n return () => signal.removeEventListener('abort', listener)\n }\n signal.addListener('abort', listener)\n return () => signal.removeListener('abort', listener)\n}\n\nconst hasToWellFormed = !!String.prototype.toWellFormed\n\n/**\n * @param {string} val\n */\nfunction toUSVString (val) {\n if (hasToWellFormed) {\n return `${val}`.toWellFormed()\n } else if (nodeUtil.toUSVString) {\n return nodeUtil.toUSVString(val)\n }\n\n return `${val}`\n}\n\n// Parsed accordingly to RFC 9110\n// https://www.rfc-editor.org/rfc/rfc9110#field.content-range\nfunction parseRangeHeader (range) {\n if (range == null || range === '') return { start: 0, end: null, size: null }\n\n const m = range ? range.match(/^bytes (\\d+)-(\\d+)\\/(\\d+)?$/) : null\n return m\n ? {\n start: parseInt(m[1]),\n end: m[2] ? parseInt(m[2]) : null,\n size: m[3] ? parseInt(m[3]) : null\n }\n : null\n}\n\nconst kEnumerableProperty = Object.create(null)\nkEnumerableProperty.enumerable = true\n\nmodule.exports = {\n kEnumerableProperty,\n nop,\n isDisturbed,\n isErrored,\n isReadable,\n toUSVString,\n isReadableAborted,\n isBlobLike,\n parseOrigin,\n parseURL,\n getServerName,\n isStream,\n isIterable,\n isAsyncIterable,\n isDestroyed,\n headerNameToString,\n parseRawHeaders,\n parseHeaders,\n parseKeepAliveTimeout,\n destroy,\n bodyLength,\n deepClone,\n ReadableStreamFrom,\n isBuffer,\n validateHandler,\n getSocketInfo,\n isFormDataLike,\n buildURL,\n throwIfAborted,\n addAbortListener,\n parseRangeHeader,\n nodeMajor,\n nodeMinor,\n nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),\n safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']\n}\n","'use strict'\n\nconst Dispatcher = require('./dispatcher')\nconst {\n ClientDestroyedError,\n ClientClosedError,\n InvalidArgumentError\n} = require('./core/errors')\nconst { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols')\n\nconst kDestroyed = Symbol('destroyed')\nconst kClosed = Symbol('closed')\nconst kOnDestroyed = Symbol('onDestroyed')\nconst kOnClosed = Symbol('onClosed')\nconst kInterceptedDispatch = Symbol('Intercepted Dispatch')\n\nclass DispatcherBase extends Dispatcher {\n constructor () {\n super()\n\n this[kDestroyed] = false\n this[kOnDestroyed] = null\n this[kClosed] = false\n this[kOnClosed] = []\n }\n\n get destroyed () {\n return this[kDestroyed]\n }\n\n get closed () {\n return this[kClosed]\n }\n\n get interceptors () {\n return this[kInterceptors]\n }\n\n set interceptors (newInterceptors) {\n if (newInterceptors) {\n for (let i = newInterceptors.length - 1; i >= 0; i--) {\n const interceptor = this[kInterceptors][i]\n if (typeof interceptor !== 'function') {\n throw new InvalidArgumentError('interceptor must be an function')\n }\n }\n }\n\n this[kInterceptors] = newInterceptors\n }\n\n close (callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.close((err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n queueMicrotask(() => callback(new ClientDestroyedError(), null))\n return\n }\n\n if (this[kClosed]) {\n if (this[kOnClosed]) {\n this[kOnClosed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n this[kClosed] = true\n this[kOnClosed].push(callback)\n\n const onClosed = () => {\n const callbacks = this[kOnClosed]\n this[kOnClosed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kClose]()\n .then(() => this.destroy())\n .then(() => {\n queueMicrotask(onClosed)\n })\n }\n\n destroy (err, callback) {\n if (typeof err === 'function') {\n callback = err\n err = null\n }\n\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.destroy(err, (err, data) => {\n return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n if (this[kOnDestroyed]) {\n this[kOnDestroyed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n if (!err) {\n err = new ClientDestroyedError()\n }\n\n this[kDestroyed] = true\n this[kOnDestroyed] = this[kOnDestroyed] || []\n this[kOnDestroyed].push(callback)\n\n const onDestroyed = () => {\n const callbacks = this[kOnDestroyed]\n this[kOnDestroyed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kDestroy](err).then(() => {\n queueMicrotask(onDestroyed)\n })\n }\n\n [kInterceptedDispatch] (opts, handler) {\n if (!this[kInterceptors] || this[kInterceptors].length === 0) {\n this[kInterceptedDispatch] = this[kDispatch]\n return this[kDispatch](opts, handler)\n }\n\n let dispatch = this[kDispatch].bind(this)\n for (let i = this[kInterceptors].length - 1; i >= 0; i--) {\n dispatch = this[kInterceptors][i](dispatch)\n }\n this[kInterceptedDispatch] = dispatch\n return dispatch(opts, handler)\n }\n\n dispatch (opts, handler) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n try {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object.')\n }\n\n if (this[kDestroyed] || this[kOnDestroyed]) {\n throw new ClientDestroyedError()\n }\n\n if (this[kClosed]) {\n throw new ClientClosedError()\n }\n\n return this[kInterceptedDispatch](opts, handler)\n } catch (err) {\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n handler.onError(err)\n\n return false\n }\n }\n}\n\nmodule.exports = DispatcherBase\n","'use strict'\n\nconst EventEmitter = require('events')\n\nclass Dispatcher extends EventEmitter {\n dispatch () {\n throw new Error('not implemented')\n }\n\n close () {\n throw new Error('not implemented')\n }\n\n destroy () {\n throw new Error('not implemented')\n }\n}\n\nmodule.exports = Dispatcher\n","'use strict'\n\nconst Busboy = require('@fastify/busboy')\nconst util = require('../core/util')\nconst {\n ReadableStreamFrom,\n isBlobLike,\n isReadableStreamLike,\n readableStreamClose,\n createDeferredPromise,\n fullyReadBody\n} = require('./util')\nconst { FormData } = require('./formdata')\nconst { kState } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { DOMException, structuredClone } = require('./constants')\nconst { Blob, File: NativeFile } = require('buffer')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('assert')\nconst { isErrored } = require('../core/util')\nconst { isUint8Array, isArrayBuffer } = require('util/types')\nconst { File: UndiciFile } = require('./file')\nconst { parseMIMEType, serializeAMimeType } = require('./dataURL')\n\nlet random\ntry {\n const crypto = require('node:crypto')\n random = (max) => crypto.randomInt(0, max)\n} catch {\n random = (max) => Math.floor(Math.random(max))\n}\n\nlet ReadableStream = globalThis.ReadableStream\n\n/** @type {globalThis['File']} */\nconst File = NativeFile ?? UndiciFile\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n// https://fetch.spec.whatwg.org/#concept-bodyinit-extract\nfunction extractBody (object, keepalive = false) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n // 1. Let stream be null.\n let stream = null\n\n // 2. If object is a ReadableStream object, then set stream to object.\n if (object instanceof ReadableStream) {\n stream = object\n } else if (isBlobLike(object)) {\n // 3. Otherwise, if object is a Blob object, set stream to the\n // result of running object’s get stream.\n stream = object.stream()\n } else {\n // 4. Otherwise, set stream to a new ReadableStream object, and set\n // up stream.\n stream = new ReadableStream({\n async pull (controller) {\n controller.enqueue(\n typeof source === 'string' ? textEncoder.encode(source) : source\n )\n queueMicrotask(() => readableStreamClose(controller))\n },\n start () {},\n type: undefined\n })\n }\n\n // 5. Assert: stream is a ReadableStream object.\n assert(isReadableStreamLike(stream))\n\n // 6. Let action be null.\n let action = null\n\n // 7. Let source be null.\n let source = null\n\n // 8. Let length be null.\n let length = null\n\n // 9. Let type be null.\n let type = null\n\n // 10. Switch on object:\n if (typeof object === 'string') {\n // Set source to the UTF-8 encoding of object.\n // Note: setting source to a Uint8Array here breaks some mocking assumptions.\n source = object\n\n // Set type to `text/plain;charset=UTF-8`.\n type = 'text/plain;charset=UTF-8'\n } else if (object instanceof URLSearchParams) {\n // URLSearchParams\n\n // spec says to run application/x-www-form-urlencoded on body.list\n // this is implemented in Node.js as apart of an URLSearchParams instance toString method\n // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490\n // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100\n\n // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.\n source = object.toString()\n\n // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.\n type = 'application/x-www-form-urlencoded;charset=UTF-8'\n } else if (isArrayBuffer(object)) {\n // BufferSource/ArrayBuffer\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.slice())\n } else if (ArrayBuffer.isView(object)) {\n // BufferSource/ArrayBufferView\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))\n } else if (util.isFormDataLike(object)) {\n const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`\n const prefix = `--${boundary}\\r\\nContent-Disposition: form-data`\n\n /*! formdata-polyfill. MIT License. Jimmy Wärting */\n const escape = (str) =>\n str.replace(/\\n/g, '%0A').replace(/\\r/g, '%0D').replace(/\"/g, '%22')\n const normalizeLinefeeds = (value) => value.replace(/\\r?\\n|\\r/g, '\\r\\n')\n\n // Set action to this step: run the multipart/form-data\n // encoding algorithm, with object’s entry list and UTF-8.\n // - This ensures that the body is immutable and can't be changed afterwords\n // - That the content-length is calculated in advance.\n // - And that all parts are pre-encoded and ready to be sent.\n\n const blobParts = []\n const rn = new Uint8Array([13, 10]) // '\\r\\n'\n length = 0\n let hasUnknownSizeValue = false\n\n for (const [name, value] of object) {\n if (typeof value === 'string') {\n const chunk = textEncoder.encode(prefix +\n `; name=\"${escape(normalizeLinefeeds(name))}\"` +\n `\\r\\n\\r\\n${normalizeLinefeeds(value)}\\r\\n`)\n blobParts.push(chunk)\n length += chunk.byteLength\n } else {\n const chunk = textEncoder.encode(`${prefix}; name=\"${escape(normalizeLinefeeds(name))}\"` +\n (value.name ? `; filename=\"${escape(value.name)}\"` : '') + '\\r\\n' +\n `Content-Type: ${\n value.type || 'application/octet-stream'\n }\\r\\n\\r\\n`)\n blobParts.push(chunk, value, rn)\n if (typeof value.size === 'number') {\n length += chunk.byteLength + value.size + rn.byteLength\n } else {\n hasUnknownSizeValue = true\n }\n }\n }\n\n const chunk = textEncoder.encode(`--${boundary}--`)\n blobParts.push(chunk)\n length += chunk.byteLength\n if (hasUnknownSizeValue) {\n length = null\n }\n\n // Set source to object.\n source = object\n\n action = async function * () {\n for (const part of blobParts) {\n if (part.stream) {\n yield * part.stream()\n } else {\n yield part\n }\n }\n }\n\n // Set type to `multipart/form-data; boundary=`,\n // followed by the multipart/form-data boundary string generated\n // by the multipart/form-data encoding algorithm.\n type = 'multipart/form-data; boundary=' + boundary\n } else if (isBlobLike(object)) {\n // Blob\n\n // Set source to object.\n source = object\n\n // Set length to object’s size.\n length = object.size\n\n // If object’s type attribute is not the empty byte sequence, set\n // type to its value.\n if (object.type) {\n type = object.type\n }\n } else if (typeof object[Symbol.asyncIterator] === 'function') {\n // If keepalive is true, then throw a TypeError.\n if (keepalive) {\n throw new TypeError('keepalive')\n }\n\n // If object is disturbed or locked, then throw a TypeError.\n if (util.isDisturbed(object) || object.locked) {\n throw new TypeError(\n 'Response body object should not be disturbed or locked'\n )\n }\n\n stream =\n object instanceof ReadableStream ? object : ReadableStreamFrom(object)\n }\n\n // 11. If source is a byte sequence, then set action to a\n // step that returns source and length to source’s length.\n if (typeof source === 'string' || util.isBuffer(source)) {\n length = Buffer.byteLength(source)\n }\n\n // 12. If action is non-null, then run these steps in in parallel:\n if (action != null) {\n // Run action.\n let iterator\n stream = new ReadableStream({\n async start () {\n iterator = action(object)[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { value, done } = await iterator.next()\n if (done) {\n // When running action is done, close stream.\n queueMicrotask(() => {\n controller.close()\n })\n } else {\n // Whenever one or more bytes are available and stream is not errored,\n // enqueue a Uint8Array wrapping an ArrayBuffer containing the available\n // bytes into stream.\n if (!isErrored(stream)) {\n controller.enqueue(new Uint8Array(value))\n }\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n },\n type: undefined\n })\n }\n\n // 13. Let body be a body whose stream is stream, source is source,\n // and length is length.\n const body = { stream, source, length }\n\n // 14. Return (body, type).\n return [body, type]\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit-safely-extract\nfunction safelyExtractBody (object, keepalive = false) {\n if (!ReadableStream) {\n // istanbul ignore next\n ReadableStream = require('stream/web').ReadableStream\n }\n\n // To safely extract a body and a `Content-Type` value from\n // a byte sequence or BodyInit object object, run these steps:\n\n // 1. If object is a ReadableStream object, then:\n if (object instanceof ReadableStream) {\n // Assert: object is neither disturbed nor locked.\n // istanbul ignore next\n assert(!util.isDisturbed(object), 'The body has already been consumed.')\n // istanbul ignore next\n assert(!object.locked, 'The stream is locked.')\n }\n\n // 2. Return the results of extracting object.\n return extractBody(object, keepalive)\n}\n\nfunction cloneBody (body) {\n // To clone a body body, run these steps:\n\n // https://fetch.spec.whatwg.org/#concept-body-clone\n\n // 1. Let « out1, out2 » be the result of teeing body’s stream.\n const [out1, out2] = body.stream.tee()\n const out2Clone = structuredClone(out2, { transfer: [out2] })\n // This, for whatever reasons, unrefs out2Clone which allows\n // the process to exit by itself.\n const [, finalClone] = out2Clone.tee()\n\n // 2. Set body’s stream to out1.\n body.stream = out1\n\n // 3. Return a body whose stream is out2 and other members are copied from body.\n return {\n stream: finalClone,\n length: body.length,\n source: body.source\n }\n}\n\nasync function * consumeBody (body) {\n if (body) {\n if (isUint8Array(body)) {\n yield body\n } else {\n const stream = body.stream\n\n if (util.isDisturbed(stream)) {\n throw new TypeError('The body has already been consumed.')\n }\n\n if (stream.locked) {\n throw new TypeError('The stream is locked.')\n }\n\n // Compat.\n stream[kBodyUsed] = true\n\n yield * stream\n }\n }\n}\n\nfunction throwIfAborted (state) {\n if (state.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError')\n }\n}\n\nfunction bodyMixinMethods (instance) {\n const methods = {\n blob () {\n // The blob() method steps are to return the result of\n // running consume body with this and the following step\n // given a byte sequence bytes: return a Blob whose\n // contents are bytes and whose type attribute is this’s\n // MIME type.\n return specConsumeBody(this, (bytes) => {\n let mimeType = bodyMimeType(this)\n\n if (mimeType === 'failure') {\n mimeType = ''\n } else if (mimeType) {\n mimeType = serializeAMimeType(mimeType)\n }\n\n // Return a Blob whose contents are bytes and type attribute\n // is mimeType.\n return new Blob([bytes], { type: mimeType })\n }, instance)\n },\n\n arrayBuffer () {\n // The arrayBuffer() method steps are to return the result\n // of running consume body with this and the following step\n // given a byte sequence bytes: return a new ArrayBuffer\n // whose contents are bytes.\n return specConsumeBody(this, (bytes) => {\n return new Uint8Array(bytes).buffer\n }, instance)\n },\n\n text () {\n // The text() method steps are to return the result of running\n // consume body with this and UTF-8 decode.\n return specConsumeBody(this, utf8DecodeBytes, instance)\n },\n\n json () {\n // The json() method steps are to return the result of running\n // consume body with this and parse JSON from bytes.\n return specConsumeBody(this, parseJSONFromBytes, instance)\n },\n\n async formData () {\n webidl.brandCheck(this, instance)\n\n throwIfAborted(this[kState])\n\n const contentType = this.headers.get('Content-Type')\n\n // If mimeType’s essence is \"multipart/form-data\", then:\n if (/multipart\\/form-data/.test(contentType)) {\n const headers = {}\n for (const [key, value] of this.headers) headers[key.toLowerCase()] = value\n\n const responseFormData = new FormData()\n\n let busboy\n\n try {\n busboy = new Busboy({\n headers,\n preservePath: true\n })\n } catch (err) {\n throw new DOMException(`${err}`, 'AbortError')\n }\n\n busboy.on('field', (name, value) => {\n responseFormData.append(name, value)\n })\n busboy.on('file', (name, value, filename, encoding, mimeType) => {\n const chunks = []\n\n if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {\n let base64chunk = ''\n\n value.on('data', (chunk) => {\n base64chunk += chunk.toString().replace(/[\\r\\n]/gm, '')\n\n const end = base64chunk.length - base64chunk.length % 4\n chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))\n\n base64chunk = base64chunk.slice(end)\n })\n value.on('end', () => {\n chunks.push(Buffer.from(base64chunk, 'base64'))\n responseFormData.append(name, new File(chunks, filename, { type: mimeType }))\n })\n } else {\n value.on('data', (chunk) => {\n chunks.push(chunk)\n })\n value.on('end', () => {\n responseFormData.append(name, new File(chunks, filename, { type: mimeType }))\n })\n }\n })\n\n const busboyResolve = new Promise((resolve, reject) => {\n busboy.on('finish', resolve)\n busboy.on('error', (err) => reject(new TypeError(err)))\n })\n\n if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)\n busboy.end()\n await busboyResolve\n\n return responseFormData\n } else if (/application\\/x-www-form-urlencoded/.test(contentType)) {\n // Otherwise, if mimeType’s essence is \"application/x-www-form-urlencoded\", then:\n\n // 1. Let entries be the result of parsing bytes.\n let entries\n try {\n let text = ''\n // application/x-www-form-urlencoded parser will keep the BOM.\n // https://url.spec.whatwg.org/#concept-urlencoded-parser\n // Note that streaming decoder is stateful and cannot be reused\n const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })\n\n for await (const chunk of consumeBody(this[kState].body)) {\n if (!isUint8Array(chunk)) {\n throw new TypeError('Expected Uint8Array chunk')\n }\n text += streamingDecoder.decode(chunk, { stream: true })\n }\n text += streamingDecoder.decode()\n entries = new URLSearchParams(text)\n } catch (err) {\n // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.\n // 2. If entries is failure, then throw a TypeError.\n throw Object.assign(new TypeError(), { cause: err })\n }\n\n // 3. Return a new FormData object whose entries are entries.\n const formData = new FormData()\n for (const [name, value] of entries) {\n formData.append(name, value)\n }\n return formData\n } else {\n // Wait a tick before checking if the request has been aborted.\n // Otherwise, a TypeError can be thrown when an AbortError should.\n await Promise.resolve()\n\n throwIfAborted(this[kState])\n\n // Otherwise, throw a TypeError.\n throw webidl.errors.exception({\n header: `${instance.name}.formData`,\n message: 'Could not parse content as FormData.'\n })\n }\n }\n }\n\n return methods\n}\n\nfunction mixinBody (prototype) {\n Object.assign(prototype.prototype, bodyMixinMethods(prototype))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-consume-body\n * @param {Response|Request} object\n * @param {(value: unknown) => unknown} convertBytesToJSValue\n * @param {Response|Request} instance\n */\nasync function specConsumeBody (object, convertBytesToJSValue, instance) {\n webidl.brandCheck(object, instance)\n\n throwIfAborted(object[kState])\n\n // 1. If object is unusable, then return a promise rejected\n // with a TypeError.\n if (bodyUnusable(object[kState].body)) {\n throw new TypeError('Body is unusable')\n }\n\n // 2. Let promise be a new promise.\n const promise = createDeferredPromise()\n\n // 3. Let errorSteps given error be to reject promise with error.\n const errorSteps = (error) => promise.reject(error)\n\n // 4. Let successSteps given a byte sequence data be to resolve\n // promise with the result of running convertBytesToJSValue\n // with data. If that threw an exception, then run errorSteps\n // with that exception.\n const successSteps = (data) => {\n try {\n promise.resolve(convertBytesToJSValue(data))\n } catch (e) {\n errorSteps(e)\n }\n }\n\n // 5. If object’s body is null, then run successSteps with an\n // empty byte sequence.\n if (object[kState].body == null) {\n successSteps(new Uint8Array())\n return promise.promise\n }\n\n // 6. Otherwise, fully read object’s body given successSteps,\n // errorSteps, and object’s relevant global object.\n await fullyReadBody(object[kState].body, successSteps, errorSteps)\n\n // 7. Return promise.\n return promise.promise\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction bodyUnusable (body) {\n // An object including the Body interface mixin is\n // said to be unusable if its body is non-null and\n // its body’s stream is disturbed or locked.\n return body != null && (body.stream.locked || util.isDisturbed(body.stream))\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#utf-8-decode\n * @param {Buffer} buffer\n */\nfunction utf8DecodeBytes (buffer) {\n if (buffer.length === 0) {\n return ''\n }\n\n // 1. Let buffer be the result of peeking three bytes from\n // ioQueue, converted to a byte sequence.\n\n // 2. If buffer is 0xEF 0xBB 0xBF, then read three\n // bytes from ioQueue. (Do nothing with those bytes.)\n if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {\n buffer = buffer.subarray(3)\n }\n\n // 3. Process a queue with an instance of UTF-8’s\n // decoder, ioQueue, output, and \"replacement\".\n const output = textDecoder.decode(buffer)\n\n // 4. Return output.\n return output\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value\n * @param {Uint8Array} bytes\n */\nfunction parseJSONFromBytes (bytes) {\n return JSON.parse(utf8DecodeBytes(bytes))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-mime-type\n * @param {import('./response').Response|import('./request').Request} object\n */\nfunction bodyMimeType (object) {\n const { headersList } = object[kState]\n const contentType = headersList.get('content-type')\n\n if (contentType === null) {\n return 'failure'\n }\n\n return parseMIMEType(contentType)\n}\n\nmodule.exports = {\n extractBody,\n safelyExtractBody,\n cloneBody,\n mixinBody\n}\n","'use strict'\n\nconst { MessageChannel, receiveMessageOnPort } = require('worker_threads')\n\nconst corsSafeListedMethods = ['GET', 'HEAD', 'POST']\nconst corsSafeListedMethodsSet = new Set(corsSafeListedMethods)\n\nconst nullBodyStatus = [101, 204, 205, 304]\n\nconst redirectStatus = [301, 302, 303, 307, 308]\nconst redirectStatusSet = new Set(redirectStatus)\n\n// https://fetch.spec.whatwg.org/#block-bad-port\nconst badPorts = [\n '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',\n '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',\n '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',\n '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',\n '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',\n '10080'\n]\n\nconst badPortsSet = new Set(badPorts)\n\n// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies\nconst referrerPolicy = [\n '',\n 'no-referrer',\n 'no-referrer-when-downgrade',\n 'same-origin',\n 'origin',\n 'strict-origin',\n 'origin-when-cross-origin',\n 'strict-origin-when-cross-origin',\n 'unsafe-url'\n]\nconst referrerPolicySet = new Set(referrerPolicy)\n\nconst requestRedirect = ['follow', 'manual', 'error']\n\nconst safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']\nconst safeMethodsSet = new Set(safeMethods)\n\nconst requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']\n\nconst requestCredentials = ['omit', 'same-origin', 'include']\n\nconst requestCache = [\n 'default',\n 'no-store',\n 'reload',\n 'no-cache',\n 'force-cache',\n 'only-if-cached'\n]\n\n// https://fetch.spec.whatwg.org/#request-body-header-name\nconst requestBodyHeader = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n // See https://github.com/nodejs/undici/issues/2021\n // 'Content-Length' is a forbidden header name, which is typically\n // removed in the Headers implementation. However, undici doesn't\n // filter out headers, so we add it here.\n 'content-length'\n]\n\n// https://fetch.spec.whatwg.org/#enumdef-requestduplex\nconst requestDuplex = [\n 'half'\n]\n\n// http://fetch.spec.whatwg.org/#forbidden-method\nconst forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']\nconst forbiddenMethodsSet = new Set(forbiddenMethods)\n\nconst subresource = [\n 'audio',\n 'audioworklet',\n 'font',\n 'image',\n 'manifest',\n 'paintworklet',\n 'script',\n 'style',\n 'track',\n 'video',\n 'xslt',\n ''\n]\nconst subresourceSet = new Set(subresource)\n\n/** @type {globalThis['DOMException']} */\nconst DOMException = globalThis.DOMException ?? (() => {\n // DOMException was only made a global in Node v17.0.0,\n // but fetch supports >= v16.8.\n try {\n atob('~')\n } catch (err) {\n return Object.getPrototypeOf(err).constructor\n }\n})()\n\nlet channel\n\n/** @type {globalThis['structuredClone']} */\nconst structuredClone =\n globalThis.structuredClone ??\n // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js\n // structuredClone was added in v17.0.0, but fetch supports v16.8\n function structuredClone (value, options = undefined) {\n if (arguments.length === 0) {\n throw new TypeError('missing argument')\n }\n\n if (!channel) {\n channel = new MessageChannel()\n }\n channel.port1.unref()\n channel.port2.unref()\n channel.port1.postMessage(value, options?.transfer)\n return receiveMessageOnPort(channel.port2).message\n }\n\nmodule.exports = {\n DOMException,\n structuredClone,\n subresource,\n forbiddenMethods,\n requestBodyHeader,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n redirectStatus,\n corsSafeListedMethods,\n nullBodyStatus,\n safeMethods,\n badPorts,\n requestDuplex,\n subresourceSet,\n badPortsSet,\n redirectStatusSet,\n corsSafeListedMethodsSet,\n safeMethodsSet,\n forbiddenMethodsSet,\n referrerPolicySet\n}\n","const assert = require('assert')\nconst { atob } = require('buffer')\nconst { isomorphicDecode } = require('./util')\n\nconst encoder = new TextEncoder()\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-token-code-point\n */\nconst HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/\nconst HTTP_WHITESPACE_REGEX = /(\\u000A|\\u000D|\\u0009|\\u0020)/ // eslint-disable-line\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point\n */\nconst HTTP_QUOTED_STRING_TOKENS = /[\\u0009|\\u0020-\\u007E|\\u0080-\\u00FF]/ // eslint-disable-line\n\n// https://fetch.spec.whatwg.org/#data-url-processor\n/** @param {URL} dataURL */\nfunction dataURLProcessor (dataURL) {\n // 1. Assert: dataURL’s scheme is \"data\".\n assert(dataURL.protocol === 'data:')\n\n // 2. Let input be the result of running the URL\n // serializer on dataURL with exclude fragment\n // set to true.\n let input = URLSerializer(dataURL, true)\n\n // 3. Remove the leading \"data:\" string from input.\n input = input.slice(5)\n\n // 4. Let position point at the start of input.\n const position = { position: 0 }\n\n // 5. Let mimeType be the result of collecting a\n // sequence of code points that are not equal\n // to U+002C (,), given position.\n let mimeType = collectASequenceOfCodePointsFast(\n ',',\n input,\n position\n )\n\n // 6. Strip leading and trailing ASCII whitespace\n // from mimeType.\n // Undici implementation note: we need to store the\n // length because if the mimetype has spaces removed,\n // the wrong amount will be sliced from the input in\n // step #9\n const mimeTypeLength = mimeType.length\n mimeType = removeASCIIWhitespace(mimeType, true, true)\n\n // 7. If position is past the end of input, then\n // return failure\n if (position.position >= input.length) {\n return 'failure'\n }\n\n // 8. Advance position by 1.\n position.position++\n\n // 9. Let encodedBody be the remainder of input.\n const encodedBody = input.slice(mimeTypeLength + 1)\n\n // 10. Let body be the percent-decoding of encodedBody.\n let body = stringPercentDecode(encodedBody)\n\n // 11. If mimeType ends with U+003B (;), followed by\n // zero or more U+0020 SPACE, followed by an ASCII\n // case-insensitive match for \"base64\", then:\n if (/;(\\u0020){0,}base64$/i.test(mimeType)) {\n // 1. Let stringBody be the isomorphic decode of body.\n const stringBody = isomorphicDecode(body)\n\n // 2. Set body to the forgiving-base64 decode of\n // stringBody.\n body = forgivingBase64(stringBody)\n\n // 3. If body is failure, then return failure.\n if (body === 'failure') {\n return 'failure'\n }\n\n // 4. Remove the last 6 code points from mimeType.\n mimeType = mimeType.slice(0, -6)\n\n // 5. Remove trailing U+0020 SPACE code points from mimeType,\n // if any.\n mimeType = mimeType.replace(/(\\u0020)+$/, '')\n\n // 6. Remove the last U+003B (;) code point from mimeType.\n mimeType = mimeType.slice(0, -1)\n }\n\n // 12. If mimeType starts with U+003B (;), then prepend\n // \"text/plain\" to mimeType.\n if (mimeType.startsWith(';')) {\n mimeType = 'text/plain' + mimeType\n }\n\n // 13. Let mimeTypeRecord be the result of parsing\n // mimeType.\n let mimeTypeRecord = parseMIMEType(mimeType)\n\n // 14. If mimeTypeRecord is failure, then set\n // mimeTypeRecord to text/plain;charset=US-ASCII.\n if (mimeTypeRecord === 'failure') {\n mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')\n }\n\n // 15. Return a new data: URL struct whose MIME\n // type is mimeTypeRecord and body is body.\n // https://fetch.spec.whatwg.org/#data-url-struct\n return { mimeType: mimeTypeRecord, body }\n}\n\n// https://url.spec.whatwg.org/#concept-url-serializer\n/**\n * @param {URL} url\n * @param {boolean} excludeFragment\n */\nfunction URLSerializer (url, excludeFragment = false) {\n if (!excludeFragment) {\n return url.href\n }\n\n const href = url.href\n const hashLength = url.hash.length\n\n return hashLength === 0 ? href : href.substring(0, href.length - hashLength)\n}\n\n// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points\n/**\n * @param {(char: string) => boolean} condition\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePoints (condition, input, position) {\n // 1. Let result be the empty string.\n let result = ''\n\n // 2. While position doesn’t point past the end of input and the\n // code point at position within input meets the condition condition:\n while (position.position < input.length && condition(input[position.position])) {\n // 1. Append that code point to the end of result.\n result += input[position.position]\n\n // 2. Advance position by 1.\n position.position++\n }\n\n // 3. Return result.\n return result\n}\n\n/**\n * A faster collectASequenceOfCodePoints that only works when comparing a single character.\n * @param {string} char\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePointsFast (char, input, position) {\n const idx = input.indexOf(char, position.position)\n const start = position.position\n\n if (idx === -1) {\n position.position = input.length\n return input.slice(start)\n }\n\n position.position = idx\n return input.slice(start, position.position)\n}\n\n// https://url.spec.whatwg.org/#string-percent-decode\n/** @param {string} input */\nfunction stringPercentDecode (input) {\n // 1. Let bytes be the UTF-8 encoding of input.\n const bytes = encoder.encode(input)\n\n // 2. Return the percent-decoding of bytes.\n return percentDecode(bytes)\n}\n\n// https://url.spec.whatwg.org/#percent-decode\n/** @param {Uint8Array} input */\nfunction percentDecode (input) {\n // 1. Let output be an empty byte sequence.\n /** @type {number[]} */\n const output = []\n\n // 2. For each byte byte in input:\n for (let i = 0; i < input.length; i++) {\n const byte = input[i]\n\n // 1. If byte is not 0x25 (%), then append byte to output.\n if (byte !== 0x25) {\n output.push(byte)\n\n // 2. Otherwise, if byte is 0x25 (%) and the next two bytes\n // after byte in input are not in the ranges\n // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),\n // and 0x61 (a) to 0x66 (f), all inclusive, append byte\n // to output.\n } else if (\n byte === 0x25 &&\n !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))\n ) {\n output.push(0x25)\n\n // 3. Otherwise:\n } else {\n // 1. Let bytePoint be the two bytes after byte in input,\n // decoded, and then interpreted as hexadecimal number.\n const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])\n const bytePoint = Number.parseInt(nextTwoBytes, 16)\n\n // 2. Append a byte whose value is bytePoint to output.\n output.push(bytePoint)\n\n // 3. Skip the next two bytes in input.\n i += 2\n }\n }\n\n // 3. Return output.\n return Uint8Array.from(output)\n}\n\n// https://mimesniff.spec.whatwg.org/#parse-a-mime-type\n/** @param {string} input */\nfunction parseMIMEType (input) {\n // 1. Remove any leading and trailing HTTP whitespace\n // from input.\n input = removeHTTPWhitespace(input, true, true)\n\n // 2. Let position be a position variable for input,\n // initially pointing at the start of input.\n const position = { position: 0 }\n\n // 3. Let type be the result of collecting a sequence\n // of code points that are not U+002F (/) from\n // input, given position.\n const type = collectASequenceOfCodePointsFast(\n '/',\n input,\n position\n )\n\n // 4. If type is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n // https://mimesniff.spec.whatwg.org/#http-token-code-point\n if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {\n return 'failure'\n }\n\n // 5. If position is past the end of input, then return\n // failure\n if (position.position > input.length) {\n return 'failure'\n }\n\n // 6. Advance position by 1. (This skips past U+002F (/).)\n position.position++\n\n // 7. Let subtype be the result of collecting a sequence of\n // code points that are not U+003B (;) from input, given\n // position.\n let subtype = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 8. Remove any trailing HTTP whitespace from subtype.\n subtype = removeHTTPWhitespace(subtype, false, true)\n\n // 9. If subtype is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {\n return 'failure'\n }\n\n const typeLowercase = type.toLowerCase()\n const subtypeLowercase = subtype.toLowerCase()\n\n // 10. Let mimeType be a new MIME type record whose type\n // is type, in ASCII lowercase, and subtype is subtype,\n // in ASCII lowercase.\n // https://mimesniff.spec.whatwg.org/#mime-type\n const mimeType = {\n type: typeLowercase,\n subtype: subtypeLowercase,\n /** @type {Map} */\n parameters: new Map(),\n // https://mimesniff.spec.whatwg.org/#mime-type-essence\n essence: `${typeLowercase}/${subtypeLowercase}`\n }\n\n // 11. While position is not past the end of input:\n while (position.position < input.length) {\n // 1. Advance position by 1. (This skips past U+003B (;).)\n position.position++\n\n // 2. Collect a sequence of code points that are HTTP\n // whitespace from input given position.\n collectASequenceOfCodePoints(\n // https://fetch.spec.whatwg.org/#http-whitespace\n char => HTTP_WHITESPACE_REGEX.test(char),\n input,\n position\n )\n\n // 3. Let parameterName be the result of collecting a\n // sequence of code points that are not U+003B (;)\n // or U+003D (=) from input, given position.\n let parameterName = collectASequenceOfCodePoints(\n (char) => char !== ';' && char !== '=',\n input,\n position\n )\n\n // 4. Set parameterName to parameterName, in ASCII\n // lowercase.\n parameterName = parameterName.toLowerCase()\n\n // 5. If position is not past the end of input, then:\n if (position.position < input.length) {\n // 1. If the code point at position within input is\n // U+003B (;), then continue.\n if (input[position.position] === ';') {\n continue\n }\n\n // 2. Advance position by 1. (This skips past U+003D (=).)\n position.position++\n }\n\n // 6. If position is past the end of input, then break.\n if (position.position > input.length) {\n break\n }\n\n // 7. Let parameterValue be null.\n let parameterValue = null\n\n // 8. If the code point at position within input is\n // U+0022 (\"), then:\n if (input[position.position] === '\"') {\n // 1. Set parameterValue to the result of collecting\n // an HTTP quoted string from input, given position\n // and the extract-value flag.\n parameterValue = collectAnHTTPQuotedString(input, position, true)\n\n // 2. Collect a sequence of code points that are not\n // U+003B (;) from input, given position.\n collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 9. Otherwise:\n } else {\n // 1. Set parameterValue to the result of collecting\n // a sequence of code points that are not U+003B (;)\n // from input, given position.\n parameterValue = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 2. Remove any trailing HTTP whitespace from parameterValue.\n parameterValue = removeHTTPWhitespace(parameterValue, false, true)\n\n // 3. If parameterValue is the empty string, then continue.\n if (parameterValue.length === 0) {\n continue\n }\n }\n\n // 10. If all of the following are true\n // - parameterName is not the empty string\n // - parameterName solely contains HTTP token code points\n // - parameterValue solely contains HTTP quoted-string token code points\n // - mimeType’s parameters[parameterName] does not exist\n // then set mimeType’s parameters[parameterName] to parameterValue.\n if (\n parameterName.length !== 0 &&\n HTTP_TOKEN_CODEPOINTS.test(parameterName) &&\n (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&\n !mimeType.parameters.has(parameterName)\n ) {\n mimeType.parameters.set(parameterName, parameterValue)\n }\n }\n\n // 12. Return mimeType.\n return mimeType\n}\n\n// https://infra.spec.whatwg.org/#forgiving-base64-decode\n/** @param {string} data */\nfunction forgivingBase64 (data) {\n // 1. Remove all ASCII whitespace from data.\n data = data.replace(/[\\u0009\\u000A\\u000C\\u000D\\u0020]/g, '') // eslint-disable-line\n\n // 2. If data’s code point length divides by 4 leaving\n // no remainder, then:\n if (data.length % 4 === 0) {\n // 1. If data ends with one or two U+003D (=) code points,\n // then remove them from data.\n data = data.replace(/=?=$/, '')\n }\n\n // 3. If data’s code point length divides by 4 leaving\n // a remainder of 1, then return failure.\n if (data.length % 4 === 1) {\n return 'failure'\n }\n\n // 4. If data contains a code point that is not one of\n // U+002B (+)\n // U+002F (/)\n // ASCII alphanumeric\n // then return failure.\n if (/[^+/0-9A-Za-z]/.test(data)) {\n return 'failure'\n }\n\n const binary = atob(data)\n const bytes = new Uint8Array(binary.length)\n\n for (let byte = 0; byte < binary.length; byte++) {\n bytes[byte] = binary.charCodeAt(byte)\n }\n\n return bytes\n}\n\n// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string\n// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string\n/**\n * @param {string} input\n * @param {{ position: number }} position\n * @param {boolean?} extractValue\n */\nfunction collectAnHTTPQuotedString (input, position, extractValue) {\n // 1. Let positionStart be position.\n const positionStart = position.position\n\n // 2. Let value be the empty string.\n let value = ''\n\n // 3. Assert: the code point at position within input\n // is U+0022 (\").\n assert(input[position.position] === '\"')\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. While true:\n while (true) {\n // 1. Append the result of collecting a sequence of code points\n // that are not U+0022 (\") or U+005C (\\) from input, given\n // position, to value.\n value += collectASequenceOfCodePoints(\n (char) => char !== '\"' && char !== '\\\\',\n input,\n position\n )\n\n // 2. If position is past the end of input, then break.\n if (position.position >= input.length) {\n break\n }\n\n // 3. Let quoteOrBackslash be the code point at position within\n // input.\n const quoteOrBackslash = input[position.position]\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. If quoteOrBackslash is U+005C (\\), then:\n if (quoteOrBackslash === '\\\\') {\n // 1. If position is past the end of input, then append\n // U+005C (\\) to value and break.\n if (position.position >= input.length) {\n value += '\\\\'\n break\n }\n\n // 2. Append the code point at position within input to value.\n value += input[position.position]\n\n // 3. Advance position by 1.\n position.position++\n\n // 6. Otherwise:\n } else {\n // 1. Assert: quoteOrBackslash is U+0022 (\").\n assert(quoteOrBackslash === '\"')\n\n // 2. Break.\n break\n }\n }\n\n // 6. If the extract-value flag is set, then return value.\n if (extractValue) {\n return value\n }\n\n // 7. Return the code points from positionStart to position,\n // inclusive, within input.\n return input.slice(positionStart, position.position)\n}\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type\n */\nfunction serializeAMimeType (mimeType) {\n assert(mimeType !== 'failure')\n const { parameters, essence } = mimeType\n\n // 1. Let serialization be the concatenation of mimeType’s\n // type, U+002F (/), and mimeType’s subtype.\n let serialization = essence\n\n // 2. For each name → value of mimeType’s parameters:\n for (let [name, value] of parameters.entries()) {\n // 1. Append U+003B (;) to serialization.\n serialization += ';'\n\n // 2. Append name to serialization.\n serialization += name\n\n // 3. Append U+003D (=) to serialization.\n serialization += '='\n\n // 4. If value does not solely contain HTTP token code\n // points or value is the empty string, then:\n if (!HTTP_TOKEN_CODEPOINTS.test(value)) {\n // 1. Precede each occurence of U+0022 (\") or\n // U+005C (\\) in value with U+005C (\\).\n value = value.replace(/(\\\\|\")/g, '\\\\$1')\n\n // 2. Prepend U+0022 (\") to value.\n value = '\"' + value\n\n // 3. Append U+0022 (\") to value.\n value += '\"'\n }\n\n // 5. Append value to serialization.\n serialization += value\n }\n\n // 3. Return serialization.\n return serialization\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} char\n */\nfunction isHTTPWhiteSpace (char) {\n return char === '\\r' || char === '\\n' || char === '\\t' || char === ' '\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} str\n */\nfunction removeHTTPWhitespace (str, leading = true, trailing = true) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);\n }\n\n if (trailing) {\n for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);\n }\n\n return str.slice(lead, trail + 1)\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#ascii-whitespace\n * @param {string} char\n */\nfunction isASCIIWhitespace (char) {\n return char === '\\r' || char === '\\n' || char === '\\t' || char === '\\f' || char === ' '\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace\n */\nfunction removeASCIIWhitespace (str, leading = true, trailing = true) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);\n }\n\n if (trailing) {\n for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);\n }\n\n return str.slice(lead, trail + 1)\n}\n\nmodule.exports = {\n dataURLProcessor,\n URLSerializer,\n collectASequenceOfCodePoints,\n collectASequenceOfCodePointsFast,\n stringPercentDecode,\n parseMIMEType,\n collectAnHTTPQuotedString,\n serializeAMimeType\n}\n","'use strict'\n\nconst { Blob, File: NativeFile } = require('buffer')\nconst { types } = require('util')\nconst { kState } = require('./symbols')\nconst { isBlobLike } = require('./util')\nconst { webidl } = require('./webidl')\nconst { parseMIMEType, serializeAMimeType } = require('./dataURL')\nconst { kEnumerableProperty } = require('../core/util')\nconst encoder = new TextEncoder()\n\nclass File extends Blob {\n constructor (fileBits, fileName, options = {}) {\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })\n\n fileBits = webidl.converters['sequence'](fileBits)\n fileName = webidl.converters.USVString(fileName)\n options = webidl.converters.FilePropertyBag(options)\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n // Note: Blob handles this for us\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // 2. Convert every character in t to ASCII lowercase.\n let t = options.type\n let d\n\n // eslint-disable-next-line no-labels\n substep: {\n if (t) {\n t = parseMIMEType(t)\n\n if (t === 'failure') {\n t = ''\n // eslint-disable-next-line no-labels\n break substep\n }\n\n t = serializeAMimeType(t).toLowerCase()\n }\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n d = options.lastModified\n }\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n super(processBlobParts(fileBits, options), { type: t })\n this[kState] = {\n name: n,\n lastModified: d,\n type: t\n }\n }\n\n get name () {\n webidl.brandCheck(this, File)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, File)\n\n return this[kState].lastModified\n }\n\n get type () {\n webidl.brandCheck(this, File)\n\n return this[kState].type\n }\n}\n\nclass FileLike {\n constructor (blobLike, fileName, options = {}) {\n // TODO: argument idl type check\n\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // TODO\n const t = options.type\n\n // 2. Convert every character in t to ASCII lowercase.\n // TODO\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n const d = options.lastModified ?? Date.now()\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n this[kState] = {\n blobLike,\n name: n,\n type: t,\n lastModified: d\n }\n }\n\n stream (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.stream(...args)\n }\n\n arrayBuffer (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.arrayBuffer(...args)\n }\n\n slice (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.slice(...args)\n }\n\n text (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.text(...args)\n }\n\n get size () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.size\n }\n\n get type () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.type\n }\n\n get name () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n}\n\nObject.defineProperties(File.prototype, {\n [Symbol.toStringTag]: {\n value: 'File',\n configurable: true\n },\n name: kEnumerableProperty,\n lastModified: kEnumerableProperty\n})\n\nwebidl.converters.Blob = webidl.interfaceConverter(Blob)\n\nwebidl.converters.BlobPart = function (V, opts) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (\n ArrayBuffer.isView(V) ||\n types.isAnyArrayBuffer(V)\n ) {\n return webidl.converters.BufferSource(V, opts)\n }\n }\n\n return webidl.converters.USVString(V, opts)\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.BlobPart\n)\n\n// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag\nwebidl.converters.FilePropertyBag = webidl.dictionaryConverter([\n {\n key: 'lastModified',\n converter: webidl.converters['long long'],\n get defaultValue () {\n return Date.now()\n }\n },\n {\n key: 'type',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'endings',\n converter: (value) => {\n value = webidl.converters.DOMString(value)\n value = value.toLowerCase()\n\n if (value !== 'native') {\n value = 'transparent'\n }\n\n return value\n },\n defaultValue: 'transparent'\n }\n])\n\n/**\n * @see https://www.w3.org/TR/FileAPI/#process-blob-parts\n * @param {(NodeJS.TypedArray|Blob|string)[]} parts\n * @param {{ type: string, endings: string }} options\n */\nfunction processBlobParts (parts, options) {\n // 1. Let bytes be an empty sequence of bytes.\n /** @type {NodeJS.TypedArray[]} */\n const bytes = []\n\n // 2. For each element in parts:\n for (const element of parts) {\n // 1. If element is a USVString, run the following substeps:\n if (typeof element === 'string') {\n // 1. Let s be element.\n let s = element\n\n // 2. If the endings member of options is \"native\", set s\n // to the result of converting line endings to native\n // of element.\n if (options.endings === 'native') {\n s = convertLineEndingsNative(s)\n }\n\n // 3. Append the result of UTF-8 encoding s to bytes.\n bytes.push(encoder.encode(s))\n } else if (\n types.isAnyArrayBuffer(element) ||\n types.isTypedArray(element)\n ) {\n // 2. If element is a BufferSource, get a copy of the\n // bytes held by the buffer source, and append those\n // bytes to bytes.\n if (!element.buffer) { // ArrayBuffer\n bytes.push(new Uint8Array(element))\n } else {\n bytes.push(\n new Uint8Array(element.buffer, element.byteOffset, element.byteLength)\n )\n }\n } else if (isBlobLike(element)) {\n // 3. If element is a Blob, append the bytes it represents\n // to bytes.\n bytes.push(element)\n }\n }\n\n // 3. Return bytes.\n return bytes\n}\n\n/**\n * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native\n * @param {string} s\n */\nfunction convertLineEndingsNative (s) {\n // 1. Let native line ending be be the code point U+000A LF.\n let nativeLineEnding = '\\n'\n\n // 2. If the underlying platform’s conventions are to\n // represent newlines as a carriage return and line feed\n // sequence, set native line ending to the code point\n // U+000D CR followed by the code point U+000A LF.\n if (process.platform === 'win32') {\n nativeLineEnding = '\\r\\n'\n }\n\n return s.replace(/\\r?\\n/g, nativeLineEnding)\n}\n\n// If this function is moved to ./util.js, some tools (such as\n// rollup) will warn about circular dependencies. See:\n// https://github.com/nodejs/undici/issues/1629\nfunction isFileLike (object) {\n return (\n (NativeFile && object instanceof NativeFile) ||\n object instanceof File || (\n object &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n object[Symbol.toStringTag] === 'File'\n )\n )\n}\n\nmodule.exports = { File, FileLike, isFileLike }\n","'use strict'\n\nconst { isBlobLike, toUSVString, makeIterator } = require('./util')\nconst { kState } = require('./symbols')\nconst { File: UndiciFile, FileLike, isFileLike } = require('./file')\nconst { webidl } = require('./webidl')\nconst { Blob, File: NativeFile } = require('buffer')\n\n/** @type {globalThis['File']} */\nconst File = NativeFile ?? UndiciFile\n\n// https://xhr.spec.whatwg.org/#formdata\nclass FormData {\n constructor (form) {\n if (form !== undefined) {\n throw webidl.errors.conversionFailed({\n prefix: 'FormData constructor',\n argument: 'Argument 1',\n types: ['undefined']\n })\n }\n\n this[kState] = []\n }\n\n append (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name)\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, { strict: false })\n : webidl.converters.USVString(value)\n filename = arguments.length === 3\n ? webidl.converters.USVString(filename)\n : undefined\n\n // 2. Let entry be the result of creating an entry with\n // name, value, and filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. Append entry to this’s entry list.\n this[kState].push(entry)\n }\n\n delete (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })\n\n name = webidl.converters.USVString(name)\n\n // The delete(name) method steps are to remove all entries whose name\n // is name from this’s entry list.\n this[kState] = this[kState].filter(entry => entry.name !== name)\n }\n\n get (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })\n\n name = webidl.converters.USVString(name)\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return null.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx === -1) {\n return null\n }\n\n // 2. Return the value of the first entry whose name is name from\n // this’s entry list.\n return this[kState][idx].value\n }\n\n getAll (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })\n\n name = webidl.converters.USVString(name)\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return the empty list.\n // 2. Return the values of all entries whose name is name, in order,\n // from this’s entry list.\n return this[kState]\n .filter((entry) => entry.name === name)\n .map((entry) => entry.value)\n }\n\n has (name) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })\n\n name = webidl.converters.USVString(name)\n\n // The has(name) method steps are to return true if there is an entry\n // whose name is name in this’s entry list; otherwise false.\n return this[kState].findIndex((entry) => entry.name === name) !== -1\n }\n\n set (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // The set(name, value) and set(name, blobValue, filename) method steps\n // are:\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name)\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, { strict: false })\n : webidl.converters.USVString(value)\n filename = arguments.length === 3\n ? toUSVString(filename)\n : undefined\n\n // 2. Let entry be the result of creating an entry with name, value, and\n // filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. If there are entries in this’s entry list whose name is name, then\n // replace the first such entry with entry and remove the others.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx !== -1) {\n this[kState] = [\n ...this[kState].slice(0, idx),\n entry,\n ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)\n ]\n } else {\n // 4. Otherwise, append entry to this’s entry list.\n this[kState].push(entry)\n }\n }\n\n entries () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'key+value'\n )\n }\n\n keys () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'key'\n )\n }\n\n values () {\n webidl.brandCheck(this, FormData)\n\n return makeIterator(\n () => this[kState].map(pair => [pair.name, pair.value]),\n 'FormData',\n 'value'\n )\n }\n\n /**\n * @param {(value: string, key: string, self: FormData) => void} callbackFn\n * @param {unknown} thisArg\n */\n forEach (callbackFn, thisArg = globalThis) {\n webidl.brandCheck(this, FormData)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })\n\n if (typeof callbackFn !== 'function') {\n throw new TypeError(\n \"Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'.\"\n )\n }\n\n for (const [key, value] of this) {\n callbackFn.apply(thisArg, [value, key, this])\n }\n }\n}\n\nFormData.prototype[Symbol.iterator] = FormData.prototype.entries\n\nObject.defineProperties(FormData.prototype, {\n [Symbol.toStringTag]: {\n value: 'FormData',\n configurable: true\n }\n})\n\n/**\n * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry\n * @param {string} name\n * @param {string|Blob} value\n * @param {?string} filename\n * @returns\n */\nfunction makeEntry (name, value, filename) {\n // 1. Set name to the result of converting name into a scalar value string.\n // \"To convert a string into a scalar value string, replace any surrogates\n // with U+FFFD.\"\n // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end\n name = Buffer.from(name).toString('utf8')\n\n // 2. If value is a string, then set value to the result of converting\n // value into a scalar value string.\n if (typeof value === 'string') {\n value = Buffer.from(value).toString('utf8')\n } else {\n // 3. Otherwise:\n\n // 1. If value is not a File object, then set value to a new File object,\n // representing the same bytes, whose name attribute value is \"blob\"\n if (!isFileLike(value)) {\n value = value instanceof Blob\n ? new File([value], 'blob', { type: value.type })\n : new FileLike(value, 'blob', { type: value.type })\n }\n\n // 2. If filename is given, then set value to a new File object,\n // representing the same bytes, whose name attribute is filename.\n if (filename !== undefined) {\n /** @type {FilePropertyBag} */\n const options = {\n type: value.type,\n lastModified: value.lastModified\n }\n\n value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile\n ? new File([value], filename, options)\n : new FileLike(value, filename, options)\n }\n }\n\n // 4. Return an entry whose name is name and whose value is value.\n return { name, value }\n}\n\nmodule.exports = { FormData }\n","'use strict'\n\n// In case of breaking changes, increase the version\n// number to avoid conflicts.\nconst globalOrigin = Symbol.for('undici.globalOrigin.1')\n\nfunction getGlobalOrigin () {\n return globalThis[globalOrigin]\n}\n\nfunction setGlobalOrigin (newOrigin) {\n if (newOrigin === undefined) {\n Object.defineProperty(globalThis, globalOrigin, {\n value: undefined,\n writable: true,\n enumerable: false,\n configurable: false\n })\n\n return\n }\n\n const parsedURL = new URL(newOrigin)\n\n if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {\n throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)\n }\n\n Object.defineProperty(globalThis, globalOrigin, {\n value: parsedURL,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nmodule.exports = {\n getGlobalOrigin,\n setGlobalOrigin\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst { kGuard } = require('./symbols')\nconst { kEnumerableProperty } = require('../core/util')\nconst {\n makeIterator,\n isValidHeaderName,\n isValidHeaderValue\n} = require('./util')\nconst util = require('util')\nconst { webidl } = require('./webidl')\nconst assert = require('assert')\n\nconst kHeadersMap = Symbol('headers map')\nconst kHeadersSortedMap = Symbol('headers map sorted')\n\n/**\n * @param {number} code\n */\nfunction isHTTPWhiteSpaceCharCode (code) {\n return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n * @param {string} potentialValue\n */\nfunction headerValueNormalize (potentialValue) {\n // To normalize a byte sequence potentialValue, remove\n // any leading and trailing HTTP whitespace bytes from\n // potentialValue.\n let i = 0; let j = potentialValue.length\n\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i\n\n return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)\n}\n\nfunction fill (headers, object) {\n // To fill a Headers object headers with a given object object, run these steps:\n\n // 1. If object is a sequence, then for each header in object:\n // Note: webidl conversion to array has already been done.\n if (Array.isArray(object)) {\n for (let i = 0; i < object.length; ++i) {\n const header = object[i]\n // 1. If header does not contain exactly two items, then throw a TypeError.\n if (header.length !== 2) {\n throw webidl.errors.exception({\n header: 'Headers constructor',\n message: `expected name/value pair to be length 2, found ${header.length}.`\n })\n }\n\n // 2. Append (header’s first item, header’s second item) to headers.\n appendHeader(headers, header[0], header[1])\n }\n } else if (typeof object === 'object' && object !== null) {\n // Note: null should throw\n\n // 2. Otherwise, object is a record, then for each key → value in object,\n // append (key, value) to headers\n const keys = Object.keys(object)\n for (let i = 0; i < keys.length; ++i) {\n appendHeader(headers, keys[i], object[keys[i]])\n }\n } else {\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-headers-append\n */\nfunction appendHeader (headers, name, value) {\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value,\n type: 'header value'\n })\n }\n\n // 3. If headers’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if headers’s guard is \"request\" and name is a\n // forbidden header name, return.\n // Note: undici does not implement forbidden header names\n if (headers[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (headers[kGuard] === 'request-no-cors') {\n // 5. Otherwise, if headers’s guard is \"request-no-cors\":\n // TODO\n }\n\n // 6. Otherwise, if headers’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n\n // 7. Append (name, value) to headers’s header list.\n return headers[kHeadersList].append(name, value)\n\n // 8. If headers’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from headers\n}\n\nclass HeadersList {\n /** @type {[string, string][]|null} */\n cookies = null\n\n constructor (init) {\n if (init instanceof HeadersList) {\n this[kHeadersMap] = new Map(init[kHeadersMap])\n this[kHeadersSortedMap] = init[kHeadersSortedMap]\n this.cookies = init.cookies === null ? null : [...init.cookies]\n } else {\n this[kHeadersMap] = new Map(init)\n this[kHeadersSortedMap] = null\n }\n }\n\n // https://fetch.spec.whatwg.org/#header-list-contains\n contains (name) {\n // A header list list contains a header name name if list\n // contains a header whose name is a byte-case-insensitive\n // match for name.\n name = name.toLowerCase()\n\n return this[kHeadersMap].has(name)\n }\n\n clear () {\n this[kHeadersMap].clear()\n this[kHeadersSortedMap] = null\n this.cookies = null\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-append\n append (name, value) {\n this[kHeadersSortedMap] = null\n\n // 1. If list contains name, then set name to the first such\n // header’s name.\n const lowercaseName = name.toLowerCase()\n const exists = this[kHeadersMap].get(lowercaseName)\n\n // 2. Append (name, value) to list.\n if (exists) {\n const delimiter = lowercaseName === 'cookie' ? '; ' : ', '\n this[kHeadersMap].set(lowercaseName, {\n name: exists.name,\n value: `${exists.value}${delimiter}${value}`\n })\n } else {\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n if (lowercaseName === 'set-cookie') {\n this.cookies ??= []\n this.cookies.push(value)\n }\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-set\n set (name, value) {\n this[kHeadersSortedMap] = null\n const lowercaseName = name.toLowerCase()\n\n if (lowercaseName === 'set-cookie') {\n this.cookies = [value]\n }\n\n // 1. If list contains name, then set the value of\n // the first such header to value and remove the\n // others.\n // 2. Otherwise, append header (name, value) to list.\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-delete\n delete (name) {\n this[kHeadersSortedMap] = null\n\n name = name.toLowerCase()\n\n if (name === 'set-cookie') {\n this.cookies = null\n }\n\n this[kHeadersMap].delete(name)\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-get\n get (name) {\n const value = this[kHeadersMap].get(name.toLowerCase())\n\n // 1. If list does not contain name, then return null.\n // 2. Return the values of all headers in list whose name\n // is a byte-case-insensitive match for name,\n // separated from each other by 0x2C 0x20, in order.\n return value === undefined ? null : value.value\n }\n\n * [Symbol.iterator] () {\n // use the lowercased name\n for (const [name, { value }] of this[kHeadersMap]) {\n yield [name, value]\n }\n }\n\n get entries () {\n const headers = {}\n\n if (this[kHeadersMap].size) {\n for (const { name, value } of this[kHeadersMap].values()) {\n headers[name] = value\n }\n }\n\n return headers\n }\n}\n\n// https://fetch.spec.whatwg.org/#headers-class\nclass Headers {\n constructor (init = undefined) {\n if (init === kConstruct) {\n return\n }\n this[kHeadersList] = new HeadersList()\n\n // The new Headers(init) constructor steps are:\n\n // 1. Set this’s guard to \"none\".\n this[kGuard] = 'none'\n\n // 2. If init is given, then fill this with init.\n if (init !== undefined) {\n init = webidl.converters.HeadersInit(init)\n fill(this, init)\n }\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-append\n append (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })\n\n name = webidl.converters.ByteString(name)\n value = webidl.converters.ByteString(value)\n\n return appendHeader(this, name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-delete\n delete (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.delete',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. If this’s guard is \"immutable\", then throw a TypeError.\n // 3. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 4. Otherwise, if this’s guard is \"request-no-cors\", name\n // is not a no-CORS-safelisted request-header name, and\n // name is not a privileged no-CORS request-header name,\n // return.\n // 5. Otherwise, if this’s guard is \"response\" and name is\n // a forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (this[kGuard] === 'request-no-cors') {\n // TODO\n }\n\n // 6. If this’s header list does not contain name, then\n // return.\n if (!this[kHeadersList].contains(name)) {\n return\n }\n\n // 7. Delete name from this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this.\n this[kHeadersList].delete(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-get\n get (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.get',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return the result of getting name from this’s header\n // list.\n return this[kHeadersList].get(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-has\n has (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })\n\n name = webidl.converters.ByteString(name)\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.has',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return true if this’s header list contains name;\n // otherwise false.\n return this[kHeadersList].contains(name)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-set\n set (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })\n\n name = webidl.converters.ByteString(name)\n value = webidl.converters.ByteString(value)\n\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.set',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.set',\n value,\n type: 'header value'\n })\n }\n\n // 3. If this’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 5. Otherwise, if this’s guard is \"request-no-cors\" and\n // name/value is not a no-CORS-safelisted request-header,\n // return.\n // 6. Otherwise, if this’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this[kGuard] === 'immutable') {\n throw new TypeError('immutable')\n } else if (this[kGuard] === 'request-no-cors') {\n // TODO\n }\n\n // 7. Set (name, value) in this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this\n this[kHeadersList].set(name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie\n getSetCookie () {\n webidl.brandCheck(this, Headers)\n\n // 1. If this’s header list does not contain `Set-Cookie`, then return « ».\n // 2. Return the values of all headers in this’s header list whose name is\n // a byte-case-insensitive match for `Set-Cookie`, in order.\n\n const list = this[kHeadersList].cookies\n\n if (list) {\n return [...list]\n }\n\n return []\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n get [kHeadersSortedMap] () {\n if (this[kHeadersList][kHeadersSortedMap]) {\n return this[kHeadersList][kHeadersSortedMap]\n }\n\n // 1. Let headers be an empty list of headers with the key being the name\n // and value the value.\n const headers = []\n\n // 2. Let names be the result of convert header names to a sorted-lowercase\n // set with all the names of the headers in list.\n const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)\n const cookies = this[kHeadersList].cookies\n\n // 3. For each name of names:\n for (let i = 0; i < names.length; ++i) {\n const [name, value] = names[i]\n // 1. If name is `set-cookie`, then:\n if (name === 'set-cookie') {\n // 1. Let values be a list of all values of headers in list whose name\n // is a byte-case-insensitive match for name, in order.\n\n // 2. For each value of values:\n // 1. Append (name, value) to headers.\n for (let j = 0; j < cookies.length; ++j) {\n headers.push([name, cookies[j]])\n }\n } else {\n // 2. Otherwise:\n\n // 1. Let value be the result of getting name from list.\n\n // 2. Assert: value is non-null.\n assert(value !== null)\n\n // 3. Append (name, value) to headers.\n headers.push([name, value])\n }\n }\n\n this[kHeadersList][kHeadersSortedMap] = headers\n\n // 4. Return headers.\n return headers\n }\n\n keys () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'key')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'key'\n )\n }\n\n values () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'value')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'value'\n )\n }\n\n entries () {\n webidl.brandCheck(this, Headers)\n\n if (this[kGuard] === 'immutable') {\n const value = this[kHeadersSortedMap]\n return makeIterator(() => value, 'Headers',\n 'key+value')\n }\n\n return makeIterator(\n () => [...this[kHeadersSortedMap].values()],\n 'Headers',\n 'key+value'\n )\n }\n\n /**\n * @param {(value: string, key: string, self: Headers) => void} callbackFn\n * @param {unknown} thisArg\n */\n forEach (callbackFn, thisArg = globalThis) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })\n\n if (typeof callbackFn !== 'function') {\n throw new TypeError(\n \"Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'.\"\n )\n }\n\n for (const [key, value] of this) {\n callbackFn.apply(thisArg, [value, key, this])\n }\n }\n\n [Symbol.for('nodejs.util.inspect.custom')] () {\n webidl.brandCheck(this, Headers)\n\n return this[kHeadersList]\n }\n}\n\nHeaders.prototype[Symbol.iterator] = Headers.prototype.entries\n\nObject.defineProperties(Headers.prototype, {\n append: kEnumerableProperty,\n delete: kEnumerableProperty,\n get: kEnumerableProperty,\n has: kEnumerableProperty,\n set: kEnumerableProperty,\n getSetCookie: kEnumerableProperty,\n keys: kEnumerableProperty,\n values: kEnumerableProperty,\n entries: kEnumerableProperty,\n forEach: kEnumerableProperty,\n [Symbol.iterator]: { enumerable: false },\n [Symbol.toStringTag]: {\n value: 'Headers',\n configurable: true\n },\n [util.inspect.custom]: {\n enumerable: false\n }\n})\n\nwebidl.converters.HeadersInit = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (V[Symbol.iterator]) {\n return webidl.converters['sequence>'](V)\n }\n\n return webidl.converters['record'](V)\n }\n\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n}\n\nmodule.exports = {\n fill,\n Headers,\n HeadersList\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst {\n Response,\n makeNetworkError,\n makeAppropriateNetworkError,\n filterResponse,\n makeResponse\n} = require('./response')\nconst { Headers } = require('./headers')\nconst { Request, makeRequest } = require('./request')\nconst zlib = require('zlib')\nconst {\n bytesMatch,\n makePolicyContainer,\n clonePolicyContainer,\n requestBadPort,\n TAOCheck,\n appendRequestOriginHeader,\n responseLocationURL,\n requestCurrentURL,\n setRequestReferrerPolicyOnRedirect,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n createOpaqueTimingInfo,\n appendFetchMetadata,\n corsCheck,\n crossOriginResourcePolicyCheck,\n determineRequestsReferrer,\n coarsenedSharedCurrentTime,\n createDeferredPromise,\n isBlobLike,\n sameOrigin,\n isCancelled,\n isAborted,\n isErrorLike,\n fullyReadBody,\n readableStreamClose,\n isomorphicEncode,\n urlIsLocal,\n urlIsHttpHttpsScheme,\n urlHasHttpsScheme\n} = require('./util')\nconst { kState, kHeaders, kGuard, kRealm } = require('./symbols')\nconst assert = require('assert')\nconst { safelyExtractBody } = require('./body')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n safeMethodsSet,\n requestBodyHeader,\n subresourceSet,\n DOMException\n} = require('./constants')\nconst { kHeadersList } = require('../core/symbols')\nconst EE = require('events')\nconst { Readable, pipeline } = require('stream')\nconst { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util')\nconst { dataURLProcessor, serializeAMimeType } = require('./dataURL')\nconst { TransformStream } = require('stream/web')\nconst { getGlobalDispatcher } = require('../global')\nconst { webidl } = require('./webidl')\nconst { STATUS_CODES } = require('http')\nconst GET_OR_HEAD = ['GET', 'HEAD']\n\n/** @type {import('buffer').resolveObjectURL} */\nlet resolveObjectURL\nlet ReadableStream = globalThis.ReadableStream\n\nclass Fetch extends EE {\n constructor (dispatcher) {\n super()\n\n this.dispatcher = dispatcher\n this.connection = null\n this.dump = false\n this.state = 'ongoing'\n // 2 terminated listeners get added per request,\n // but only 1 gets removed. If there are 20 redirects,\n // 21 listeners will be added.\n // See https://github.com/nodejs/undici/issues/1711\n // TODO (fix): Find and fix root cause for leaked listener.\n this.setMaxListeners(21)\n }\n\n terminate (reason) {\n if (this.state !== 'ongoing') {\n return\n }\n\n this.state = 'terminated'\n this.connection?.destroy(reason)\n this.emit('terminated', reason)\n }\n\n // https://fetch.spec.whatwg.org/#fetch-controller-abort\n abort (error) {\n if (this.state !== 'ongoing') {\n return\n }\n\n // 1. Set controller’s state to \"aborted\".\n this.state = 'aborted'\n\n // 2. Let fallbackError be an \"AbortError\" DOMException.\n // 3. Set error to fallbackError if it is not given.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 4. Let serializedError be StructuredSerialize(error).\n // If that threw an exception, catch it, and let\n // serializedError be StructuredSerialize(fallbackError).\n\n // 5. Set controller’s serialized abort reason to serializedError.\n this.serializedAbortReason = error\n\n this.connection?.destroy(error)\n this.emit('terminated', error)\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-method\nfunction fetch (input, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })\n\n // 1. Let p be a new promise.\n const p = createDeferredPromise()\n\n // 2. Let requestObject be the result of invoking the initial value of\n // Request as constructor with input and init as arguments. If this throws\n // an exception, reject p with it and return p.\n let requestObject\n\n try {\n requestObject = new Request(input, init)\n } catch (e) {\n p.reject(e)\n return p.promise\n }\n\n // 3. Let request be requestObject’s request.\n const request = requestObject[kState]\n\n // 4. If requestObject’s signal’s aborted flag is set, then:\n if (requestObject.signal.aborted) {\n // 1. Abort the fetch() call with p, request, null, and\n // requestObject’s signal’s abort reason.\n abortFetch(p, request, null, requestObject.signal.reason)\n\n // 2. Return p.\n return p.promise\n }\n\n // 5. Let globalObject be request’s client’s global object.\n const globalObject = request.client.globalObject\n\n // 6. If globalObject is a ServiceWorkerGlobalScope object, then set\n // request’s service-workers mode to \"none\".\n if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {\n request.serviceWorkers = 'none'\n }\n\n // 7. Let responseObject be null.\n let responseObject = null\n\n // 8. Let relevantRealm be this’s relevant Realm.\n const relevantRealm = null\n\n // 9. Let locallyAborted be false.\n let locallyAborted = false\n\n // 10. Let controller be null.\n let controller = null\n\n // 11. Add the following abort steps to requestObject’s signal:\n addAbortListener(\n requestObject.signal,\n () => {\n // 1. Set locallyAborted to true.\n locallyAborted = true\n\n // 2. Assert: controller is non-null.\n assert(controller != null)\n\n // 3. Abort controller with requestObject’s signal’s abort reason.\n controller.abort(requestObject.signal.reason)\n\n // 4. Abort the fetch() call with p, request, responseObject,\n // and requestObject’s signal’s abort reason.\n abortFetch(p, request, responseObject, requestObject.signal.reason)\n }\n )\n\n // 12. Let handleFetchDone given response response be to finalize and\n // report timing with response, globalObject, and \"fetch\".\n const handleFetchDone = (response) =>\n finalizeAndReportTiming(response, 'fetch')\n\n // 13. Set controller to the result of calling fetch given request,\n // with processResponseEndOfBody set to handleFetchDone, and processResponse\n // given response being these substeps:\n\n const processResponse = (response) => {\n // 1. If locallyAborted is true, terminate these substeps.\n if (locallyAborted) {\n return Promise.resolve()\n }\n\n // 2. If response’s aborted flag is set, then:\n if (response.aborted) {\n // 1. Let deserializedError be the result of deserialize a serialized\n // abort reason given controller’s serialized abort reason and\n // relevantRealm.\n\n // 2. Abort the fetch() call with p, request, responseObject, and\n // deserializedError.\n\n abortFetch(p, request, responseObject, controller.serializedAbortReason)\n return Promise.resolve()\n }\n\n // 3. If response is a network error, then reject p with a TypeError\n // and terminate these substeps.\n if (response.type === 'error') {\n p.reject(\n Object.assign(new TypeError('fetch failed'), { cause: response.error })\n )\n return Promise.resolve()\n }\n\n // 4. Set responseObject to the result of creating a Response object,\n // given response, \"immutable\", and relevantRealm.\n responseObject = new Response()\n responseObject[kState] = response\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kHeadersList] = response.headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 5. Resolve p with responseObject.\n p.resolve(responseObject)\n }\n\n controller = fetching({\n request,\n processResponseEndOfBody: handleFetchDone,\n processResponse,\n dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici\n })\n\n // 14. Return p.\n return p.promise\n}\n\n// https://fetch.spec.whatwg.org/#finalize-and-report-timing\nfunction finalizeAndReportTiming (response, initiatorType = 'other') {\n // 1. If response is an aborted network error, then return.\n if (response.type === 'error' && response.aborted) {\n return\n }\n\n // 2. If response’s URL list is null or empty, then return.\n if (!response.urlList?.length) {\n return\n }\n\n // 3. Let originalURL be response’s URL list[0].\n const originalURL = response.urlList[0]\n\n // 4. Let timingInfo be response’s timing info.\n let timingInfo = response.timingInfo\n\n // 5. Let cacheState be response’s cache state.\n let cacheState = response.cacheState\n\n // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.\n if (!urlIsHttpHttpsScheme(originalURL)) {\n return\n }\n\n // 7. If timingInfo is null, then return.\n if (timingInfo === null) {\n return\n }\n\n // 8. If response’s timing allow passed flag is not set, then:\n if (!response.timingAllowPassed) {\n // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.\n timingInfo = createOpaqueTimingInfo({\n startTime: timingInfo.startTime\n })\n\n // 2. Set cacheState to the empty string.\n cacheState = ''\n }\n\n // 9. Set timingInfo’s end time to the coarsened shared current time\n // given global’s relevant settings object’s cross-origin isolated\n // capability.\n // TODO: given global’s relevant settings object’s cross-origin isolated\n // capability?\n timingInfo.endTime = coarsenedSharedCurrentTime()\n\n // 10. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 11. Mark resource timing for timingInfo, originalURL, initiatorType,\n // global, and cacheState.\n markResourceTiming(\n timingInfo,\n originalURL,\n initiatorType,\n globalThis,\n cacheState\n )\n}\n\n// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing\nfunction markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {\n if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {\n performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)\n }\n}\n\n// https://fetch.spec.whatwg.org/#abort-fetch\nfunction abortFetch (p, request, responseObject, error) {\n // Note: AbortSignal.reason was added in node v17.2.0\n // which would give us an undefined error to reject with.\n // Remove this once node v16 is no longer supported.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 1. Reject promise with error.\n p.reject(error)\n\n // 2. If request’s body is not null and is readable, then cancel request’s\n // body with error.\n if (request.body != null && isReadable(request.body?.stream)) {\n request.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n\n // 3. If responseObject is null, then return.\n if (responseObject == null) {\n return\n }\n\n // 4. Let response be responseObject’s response.\n const response = responseObject[kState]\n\n // 5. If response’s body is not null and is readable, then error response’s\n // body with error.\n if (response.body != null && isReadable(response.body?.stream)) {\n response.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetching\nfunction fetching ({\n request,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseEndOfBody,\n processResponseConsumeBody,\n useParallelQueue = false,\n dispatcher // undici\n}) {\n // 1. Let taskDestination be null.\n let taskDestination = null\n\n // 2. Let crossOriginIsolatedCapability be false.\n let crossOriginIsolatedCapability = false\n\n // 3. If request’s client is non-null, then:\n if (request.client != null) {\n // 1. Set taskDestination to request’s client’s global object.\n taskDestination = request.client.globalObject\n\n // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin\n // isolated capability.\n crossOriginIsolatedCapability =\n request.client.crossOriginIsolatedCapability\n }\n\n // 4. If useParallelQueue is true, then set taskDestination to the result of\n // starting a new parallel queue.\n // TODO\n\n // 5. Let timingInfo be a new fetch timing info whose start time and\n // post-redirect start time are the coarsened shared current time given\n // crossOriginIsolatedCapability.\n const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)\n const timingInfo = createOpaqueTimingInfo({\n startTime: currenTime\n })\n\n // 6. Let fetchParams be a new fetch params whose\n // request is request,\n // timing info is timingInfo,\n // process request body chunk length is processRequestBodyChunkLength,\n // process request end-of-body is processRequestEndOfBody,\n // process response is processResponse,\n // process response consume body is processResponseConsumeBody,\n // process response end-of-body is processResponseEndOfBody,\n // task destination is taskDestination,\n // and cross-origin isolated capability is crossOriginIsolatedCapability.\n const fetchParams = {\n controller: new Fetch(dispatcher),\n request,\n timingInfo,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseConsumeBody,\n processResponseEndOfBody,\n taskDestination,\n crossOriginIsolatedCapability\n }\n\n // 7. If request’s body is a byte sequence, then set request’s body to\n // request’s body as a body.\n // NOTE: Since fetching is only called from fetch, body should already be\n // extracted.\n assert(!request.body || request.body.stream)\n\n // 8. If request’s window is \"client\", then set request’s window to request’s\n // client, if request’s client’s global object is a Window object; otherwise\n // \"no-window\".\n if (request.window === 'client') {\n // TODO: What if request.client is null?\n request.window =\n request.client?.globalObject?.constructor?.name === 'Window'\n ? request.client\n : 'no-window'\n }\n\n // 9. If request’s origin is \"client\", then set request’s origin to request’s\n // client’s origin.\n if (request.origin === 'client') {\n // TODO: What if request.client is null?\n request.origin = request.client?.origin\n }\n\n // 10. If all of the following conditions are true:\n // TODO\n\n // 11. If request’s policy container is \"client\", then:\n if (request.policyContainer === 'client') {\n // 1. If request’s client is non-null, then set request’s policy\n // container to a clone of request’s client’s policy container. [HTML]\n if (request.client != null) {\n request.policyContainer = clonePolicyContainer(\n request.client.policyContainer\n )\n } else {\n // 2. Otherwise, set request’s policy container to a new policy\n // container.\n request.policyContainer = makePolicyContainer()\n }\n }\n\n // 12. If request’s header list does not contain `Accept`, then:\n if (!request.headersList.contains('accept')) {\n // 1. Let value be `*/*`.\n const value = '*/*'\n\n // 2. A user agent should set value to the first matching statement, if\n // any, switching on request’s destination:\n // \"document\"\n // \"frame\"\n // \"iframe\"\n // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`\n // \"image\"\n // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`\n // \"style\"\n // `text/css,*/*;q=0.1`\n // TODO\n\n // 3. Append `Accept`/value to request’s header list.\n request.headersList.append('accept', value)\n }\n\n // 13. If request’s header list does not contain `Accept-Language`, then\n // user agents should append `Accept-Language`/an appropriate value to\n // request’s header list.\n if (!request.headersList.contains('accept-language')) {\n request.headersList.append('accept-language', '*')\n }\n\n // 14. If request’s priority is null, then use request’s initiator and\n // destination appropriately in setting request’s priority to a\n // user-agent-defined object.\n if (request.priority === null) {\n // TODO\n }\n\n // 15. If request is a subresource request, then:\n if (subresourceSet.has(request.destination)) {\n // TODO\n }\n\n // 16. Run main fetch given fetchParams.\n mainFetch(fetchParams)\n .catch(err => {\n fetchParams.controller.terminate(err)\n })\n\n // 17. Return fetchParam's controller\n return fetchParams.controller\n}\n\n// https://fetch.spec.whatwg.org/#concept-main-fetch\nasync function mainFetch (fetchParams, recursive = false) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. If request’s local-URLs-only flag is set and request’s current URL is\n // not local, then set response to a network error.\n if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {\n response = makeNetworkError('local URLs only')\n }\n\n // 4. Run report Content Security Policy violations for request.\n // TODO\n\n // 5. Upgrade request to a potentially trustworthy URL, if appropriate.\n tryUpgradeRequestToAPotentiallyTrustworthyURL(request)\n\n // 6. If should request be blocked due to a bad port, should fetching request\n // be blocked as mixed content, or should request be blocked by Content\n // Security Policy returns blocked, then set response to a network error.\n if (requestBadPort(request) === 'blocked') {\n response = makeNetworkError('bad port')\n }\n // TODO: should fetching request be blocked as mixed content?\n // TODO: should request be blocked by Content Security Policy?\n\n // 7. If request’s referrer policy is the empty string, then set request’s\n // referrer policy to request’s policy container’s referrer policy.\n if (request.referrerPolicy === '') {\n request.referrerPolicy = request.policyContainer.referrerPolicy\n }\n\n // 8. If request’s referrer is not \"no-referrer\", then set request’s\n // referrer to the result of invoking determine request’s referrer.\n if (request.referrer !== 'no-referrer') {\n request.referrer = determineRequestsReferrer(request)\n }\n\n // 9. Set request’s current URL’s scheme to \"https\" if all of the following\n // conditions are true:\n // - request’s current URL’s scheme is \"http\"\n // - request’s current URL’s host is a domain\n // - Matching request’s current URL’s host per Known HSTS Host Domain Name\n // Matching results in either a superdomain match with an asserted\n // includeSubDomains directive or a congruent match (with or without an\n // asserted includeSubDomains directive). [HSTS]\n // TODO\n\n // 10. If recursive is false, then run the remaining steps in parallel.\n // TODO\n\n // 11. If response is null, then set response to the result of running\n // the steps corresponding to the first matching statement:\n if (response === null) {\n response = await (async () => {\n const currentURL = requestCurrentURL(request)\n\n if (\n // - request’s current URL’s origin is same origin with request’s origin,\n // and request’s response tainting is \"basic\"\n (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||\n // request’s current URL’s scheme is \"data\"\n (currentURL.protocol === 'data:') ||\n // - request’s mode is \"navigate\" or \"websocket\"\n (request.mode === 'navigate' || request.mode === 'websocket')\n ) {\n // 1. Set request’s response tainting to \"basic\".\n request.responseTainting = 'basic'\n\n // 2. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s mode is \"same-origin\"\n if (request.mode === 'same-origin') {\n // 1. Return a network error.\n return makeNetworkError('request mode cannot be \"same-origin\"')\n }\n\n // request’s mode is \"no-cors\"\n if (request.mode === 'no-cors') {\n // 1. If request’s redirect mode is not \"follow\", then return a network\n // error.\n if (request.redirect !== 'follow') {\n return makeNetworkError(\n 'redirect mode cannot be \"follow\" for \"no-cors\" request'\n )\n }\n\n // 2. Set request’s response tainting to \"opaque\".\n request.responseTainting = 'opaque'\n\n // 3. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s current URL’s scheme is not an HTTP(S) scheme\n if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {\n // Return a network error.\n return makeNetworkError('URL scheme must be a HTTP(S) scheme')\n }\n\n // - request’s use-CORS-preflight flag is set\n // - request’s unsafe-request flag is set and either request’s method is\n // not a CORS-safelisted method or CORS-unsafe request-header names with\n // request’s header list is not empty\n // 1. Set request’s response tainting to \"cors\".\n // 2. Let corsWithPreflightResponse be the result of running HTTP fetch\n // given fetchParams and true.\n // 3. If corsWithPreflightResponse is a network error, then clear cache\n // entries using request.\n // 4. Return corsWithPreflightResponse.\n // TODO\n\n // Otherwise\n // 1. Set request’s response tainting to \"cors\".\n request.responseTainting = 'cors'\n\n // 2. Return the result of running HTTP fetch given fetchParams.\n return await httpFetch(fetchParams)\n })()\n }\n\n // 12. If recursive is true, then return response.\n if (recursive) {\n return response\n }\n\n // 13. If response is not a network error and response is not a filtered\n // response, then:\n if (response.status !== 0 && !response.internalResponse) {\n // If request’s response tainting is \"cors\", then:\n if (request.responseTainting === 'cors') {\n // 1. Let headerNames be the result of extracting header list values\n // given `Access-Control-Expose-Headers` and response’s header list.\n // TODO\n // 2. If request’s credentials mode is not \"include\" and headerNames\n // contains `*`, then set response’s CORS-exposed header-name list to\n // all unique header names in response’s header list.\n // TODO\n // 3. Otherwise, if headerNames is not null or failure, then set\n // response’s CORS-exposed header-name list to headerNames.\n // TODO\n }\n\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (request.responseTainting === 'basic') {\n response = filterResponse(response, 'basic')\n } else if (request.responseTainting === 'cors') {\n response = filterResponse(response, 'cors')\n } else if (request.responseTainting === 'opaque') {\n response = filterResponse(response, 'opaque')\n } else {\n assert(false)\n }\n }\n\n // 14. Let internalResponse be response, if response is a network error,\n // and response’s internal response otherwise.\n let internalResponse =\n response.status === 0 ? response : response.internalResponse\n\n // 15. If internalResponse’s URL list is empty, then set it to a clone of\n // request’s URL list.\n if (internalResponse.urlList.length === 0) {\n internalResponse.urlList.push(...request.urlList)\n }\n\n // 16. If request’s timing allow failed flag is unset, then set\n // internalResponse’s timing allow passed flag.\n if (!request.timingAllowFailed) {\n response.timingAllowPassed = true\n }\n\n // 17. If response is not a network error and any of the following returns\n // blocked\n // - should internalResponse to request be blocked as mixed content\n // - should internalResponse to request be blocked by Content Security Policy\n // - should internalResponse to request be blocked due to its MIME type\n // - should internalResponse to request be blocked due to nosniff\n // TODO\n\n // 18. If response’s type is \"opaque\", internalResponse’s status is 206,\n // internalResponse’s range-requested flag is set, and request’s header\n // list does not contain `Range`, then set response and internalResponse\n // to a network error.\n if (\n response.type === 'opaque' &&\n internalResponse.status === 206 &&\n internalResponse.rangeRequested &&\n !request.headers.contains('range')\n ) {\n response = internalResponse = makeNetworkError()\n }\n\n // 19. If response is not a network error and either request’s method is\n // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,\n // set internalResponse’s body to null and disregard any enqueuing toward\n // it (if any).\n if (\n response.status !== 0 &&\n (request.method === 'HEAD' ||\n request.method === 'CONNECT' ||\n nullBodyStatus.includes(internalResponse.status))\n ) {\n internalResponse.body = null\n fetchParams.controller.dump = true\n }\n\n // 20. If request’s integrity metadata is not the empty string, then:\n if (request.integrity) {\n // 1. Let processBodyError be this step: run fetch finale given fetchParams\n // and a network error.\n const processBodyError = (reason) =>\n fetchFinale(fetchParams, makeNetworkError(reason))\n\n // 2. If request’s response tainting is \"opaque\", or response’s body is null,\n // then run processBodyError and abort these steps.\n if (request.responseTainting === 'opaque' || response.body == null) {\n processBodyError(response.error)\n return\n }\n\n // 3. Let processBody given bytes be these steps:\n const processBody = (bytes) => {\n // 1. If bytes do not match request’s integrity metadata,\n // then run processBodyError and abort these steps. [SRI]\n if (!bytesMatch(bytes, request.integrity)) {\n processBodyError('integrity mismatch')\n return\n }\n\n // 2. Set response’s body to bytes as a body.\n response.body = safelyExtractBody(bytes)[0]\n\n // 3. Run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n\n // 4. Fully read response’s body given processBody and processBodyError.\n await fullyReadBody(response.body, processBody, processBodyError)\n } else {\n // 21. Otherwise, run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n}\n\n// https://fetch.spec.whatwg.org/#concept-scheme-fetch\n// given a fetch params fetchParams\nfunction schemeFetch (fetchParams) {\n // Note: since the connection is destroyed on redirect, which sets fetchParams to a\n // cancelled state, we do not want this condition to trigger *unless* there have been\n // no redirects. See https://github.com/nodejs/undici/issues/1776\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {\n return Promise.resolve(makeAppropriateNetworkError(fetchParams))\n }\n\n // 2. Let request be fetchParams’s request.\n const { request } = fetchParams\n\n const { protocol: scheme } = requestCurrentURL(request)\n\n // 3. Switch on request’s current URL’s scheme and run the associated steps:\n switch (scheme) {\n case 'about:': {\n // If request’s current URL’s path is the string \"blank\", then return a new response\n // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,\n // and body is the empty byte sequence as a body.\n\n // Otherwise, return a network error.\n return Promise.resolve(makeNetworkError('about scheme is not supported'))\n }\n case 'blob:': {\n if (!resolveObjectURL) {\n resolveObjectURL = require('buffer').resolveObjectURL\n }\n\n // 1. Let blobURLEntry be request’s current URL’s blob URL entry.\n const blobURLEntry = requestCurrentURL(request)\n\n // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56\n // Buffer.resolveObjectURL does not ignore URL queries.\n if (blobURLEntry.search.length !== 0) {\n return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))\n }\n\n const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())\n\n // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s\n // object is not a Blob object, then return a network error.\n if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {\n return Promise.resolve(makeNetworkError('invalid method'))\n }\n\n // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.\n const bodyWithType = safelyExtractBody(blobURLEntryObject)\n\n // 4. Let body be bodyWithType’s body.\n const body = bodyWithType[0]\n\n // 5. Let length be body’s length, serialized and isomorphic encoded.\n const length = isomorphicEncode(`${body.length}`)\n\n // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.\n const type = bodyWithType[1] ?? ''\n\n // 7. Return a new response whose status message is `OK`, header list is\n // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.\n const response = makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-length', { name: 'Content-Length', value: length }],\n ['content-type', { name: 'Content-Type', value: type }]\n ]\n })\n\n response.body = body\n\n return Promise.resolve(response)\n }\n case 'data:': {\n // 1. Let dataURLStruct be the result of running the\n // data: URL processor on request’s current URL.\n const currentURL = requestCurrentURL(request)\n const dataURLStruct = dataURLProcessor(currentURL)\n\n // 2. If dataURLStruct is failure, then return a\n // network error.\n if (dataURLStruct === 'failure') {\n return Promise.resolve(makeNetworkError('failed to fetch the data URL'))\n }\n\n // 3. Let mimeType be dataURLStruct’s MIME type, serialized.\n const mimeType = serializeAMimeType(dataURLStruct.mimeType)\n\n // 4. Return a response whose status message is `OK`,\n // header list is « (`Content-Type`, mimeType) »,\n // and body is dataURLStruct’s body as a body.\n return Promise.resolve(makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-type', { name: 'Content-Type', value: mimeType }]\n ],\n body: safelyExtractBody(dataURLStruct.body)[0]\n }))\n }\n case 'file:': {\n // For now, unfortunate as it is, file URLs are left as an exercise for the reader.\n // When in doubt, return a network error.\n return Promise.resolve(makeNetworkError('not implemented... yet...'))\n }\n case 'http:':\n case 'https:': {\n // Return the result of running HTTP fetch given fetchParams.\n\n return httpFetch(fetchParams)\n .catch((err) => makeNetworkError(err))\n }\n default: {\n return Promise.resolve(makeNetworkError('unknown scheme'))\n }\n }\n}\n\n// https://fetch.spec.whatwg.org/#finalize-response\nfunction finalizeResponse (fetchParams, response) {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // 2, If fetchParams’s process response done is not null, then queue a fetch\n // task to run fetchParams’s process response done given response, with\n // fetchParams’s task destination.\n if (fetchParams.processResponseDone != null) {\n queueMicrotask(() => fetchParams.processResponseDone(response))\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-finale\nfunction fetchFinale (fetchParams, response) {\n // 1. If response is a network error, then:\n if (response.type === 'error') {\n // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».\n response.urlList = [fetchParams.request.urlList[0]]\n\n // 2. Set response’s timing info to the result of creating an opaque timing\n // info for fetchParams’s timing info.\n response.timingInfo = createOpaqueTimingInfo({\n startTime: fetchParams.timingInfo.startTime\n })\n }\n\n // 2. Let processResponseEndOfBody be the following steps:\n const processResponseEndOfBody = () => {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // If fetchParams’s process response end-of-body is not null,\n // then queue a fetch task to run fetchParams’s process response\n // end-of-body given response with fetchParams’s task destination.\n if (fetchParams.processResponseEndOfBody != null) {\n queueMicrotask(() => fetchParams.processResponseEndOfBody(response))\n }\n }\n\n // 3. If fetchParams’s process response is non-null, then queue a fetch task\n // to run fetchParams’s process response given response, with fetchParams’s\n // task destination.\n if (fetchParams.processResponse != null) {\n queueMicrotask(() => fetchParams.processResponse(response))\n }\n\n // 4. If response’s body is null, then run processResponseEndOfBody.\n if (response.body == null) {\n processResponseEndOfBody()\n } else {\n // 5. Otherwise:\n\n // 1. Let transformStream be a new a TransformStream.\n\n // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,\n // enqueues chunk in transformStream.\n const identityTransformAlgorithm = (chunk, controller) => {\n controller.enqueue(chunk)\n }\n\n // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm\n // and flushAlgorithm set to processResponseEndOfBody.\n const transformStream = new TransformStream({\n start () {},\n transform: identityTransformAlgorithm,\n flush: processResponseEndOfBody\n }, {\n size () {\n return 1\n }\n }, {\n size () {\n return 1\n }\n })\n\n // 4. Set response’s body to the result of piping response’s body through transformStream.\n response.body = { stream: response.body.stream.pipeThrough(transformStream) }\n }\n\n // 6. If fetchParams’s process response consume body is non-null, then:\n if (fetchParams.processResponseConsumeBody != null) {\n // 1. Let processBody given nullOrBytes be this step: run fetchParams’s\n // process response consume body given response and nullOrBytes.\n const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)\n\n // 2. Let processBodyError be this step: run fetchParams’s process\n // response consume body given response and failure.\n const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)\n\n // 3. If response’s body is null, then queue a fetch task to run processBody\n // given null, with fetchParams’s task destination.\n if (response.body == null) {\n queueMicrotask(() => processBody(null))\n } else {\n // 4. Otherwise, fully read response’s body given processBody, processBodyError,\n // and fetchParams’s task destination.\n return fullyReadBody(response.body, processBody, processBodyError)\n }\n return Promise.resolve()\n }\n}\n\n// https://fetch.spec.whatwg.org/#http-fetch\nasync function httpFetch (fetchParams) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let actualResponse be null.\n let actualResponse = null\n\n // 4. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 5. If request’s service-workers mode is \"all\", then:\n if (request.serviceWorkers === 'all') {\n // TODO\n }\n\n // 6. If response is null, then:\n if (response === null) {\n // 1. If makeCORSPreflight is true and one of these conditions is true:\n // TODO\n\n // 2. If request’s redirect mode is \"follow\", then set request’s\n // service-workers mode to \"none\".\n if (request.redirect === 'follow') {\n request.serviceWorkers = 'none'\n }\n\n // 3. Set response and actualResponse to the result of running\n // HTTP-network-or-cache fetch given fetchParams.\n actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)\n\n // 4. If request’s response tainting is \"cors\" and a CORS check\n // for request and response returns failure, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n corsCheck(request, response) === 'failure'\n ) {\n return makeNetworkError('cors failure')\n }\n\n // 5. If the TAO check for request and response returns failure, then set\n // request’s timing allow failed flag.\n if (TAOCheck(request, response) === 'failure') {\n request.timingAllowFailed = true\n }\n }\n\n // 7. If either request’s response tainting or response’s type\n // is \"opaque\", and the cross-origin resource policy check with\n // request’s origin, request’s client, request’s destination,\n // and actualResponse returns blocked, then return a network error.\n if (\n (request.responseTainting === 'opaque' || response.type === 'opaque') &&\n crossOriginResourcePolicyCheck(\n request.origin,\n request.client,\n request.destination,\n actualResponse\n ) === 'blocked'\n ) {\n return makeNetworkError('blocked')\n }\n\n // 8. If actualResponse’s status is a redirect status, then:\n if (redirectStatusSet.has(actualResponse.status)) {\n // 1. If actualResponse’s status is not 303, request’s body is not null,\n // and the connection uses HTTP/2, then user agents may, and are even\n // encouraged to, transmit an RST_STREAM frame.\n // See, https://github.com/whatwg/fetch/issues/1288\n if (request.redirect !== 'manual') {\n fetchParams.controller.connection.destroy()\n }\n\n // 2. Switch on request’s redirect mode:\n if (request.redirect === 'error') {\n // Set response to a network error.\n response = makeNetworkError('unexpected redirect')\n } else if (request.redirect === 'manual') {\n // Set response to an opaque-redirect filtered response whose internal\n // response is actualResponse.\n // NOTE(spec): On the web this would return an `opaqueredirect` response,\n // but that doesn't make sense server side.\n // See https://github.com/nodejs/undici/issues/1193.\n response = actualResponse\n } else if (request.redirect === 'follow') {\n // Set response to the result of running HTTP-redirect fetch given\n // fetchParams and response.\n response = await httpRedirectFetch(fetchParams, response)\n } else {\n assert(false)\n }\n }\n\n // 9. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 10. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-redirect-fetch\nfunction httpRedirectFetch (fetchParams, response) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let actualResponse be response, if response is not a filtered response,\n // and response’s internal response otherwise.\n const actualResponse = response.internalResponse\n ? response.internalResponse\n : response\n\n // 3. Let locationURL be actualResponse’s location URL given request’s current\n // URL’s fragment.\n let locationURL\n\n try {\n locationURL = responseLocationURL(\n actualResponse,\n requestCurrentURL(request).hash\n )\n\n // 4. If locationURL is null, then return response.\n if (locationURL == null) {\n return response\n }\n } catch (err) {\n // 5. If locationURL is failure, then return a network error.\n return Promise.resolve(makeNetworkError(err))\n }\n\n // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network\n // error.\n if (!urlIsHttpHttpsScheme(locationURL)) {\n return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))\n }\n\n // 7. If request’s redirect count is 20, then return a network error.\n if (request.redirectCount === 20) {\n return Promise.resolve(makeNetworkError('redirect count exceeded'))\n }\n\n // 8. Increase request’s redirect count by 1.\n request.redirectCount += 1\n\n // 9. If request’s mode is \"cors\", locationURL includes credentials, and\n // request’s origin is not same origin with locationURL’s origin, then return\n // a network error.\n if (\n request.mode === 'cors' &&\n (locationURL.username || locationURL.password) &&\n !sameOrigin(request, locationURL)\n ) {\n return Promise.resolve(makeNetworkError('cross origin not allowed for request mode \"cors\"'))\n }\n\n // 10. If request’s response tainting is \"cors\" and locationURL includes\n // credentials, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n (locationURL.username || locationURL.password)\n ) {\n return Promise.resolve(makeNetworkError(\n 'URL cannot contain credentials for request mode \"cors\"'\n ))\n }\n\n // 11. If actualResponse’s status is not 303, request’s body is non-null,\n // and request’s body’s source is null, then return a network error.\n if (\n actualResponse.status !== 303 &&\n request.body != null &&\n request.body.source == null\n ) {\n return Promise.resolve(makeNetworkError())\n }\n\n // 12. If one of the following is true\n // - actualResponse’s status is 301 or 302 and request’s method is `POST`\n // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`\n if (\n ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||\n (actualResponse.status === 303 &&\n !GET_OR_HEAD.includes(request.method))\n ) {\n // then:\n // 1. Set request’s method to `GET` and request’s body to null.\n request.method = 'GET'\n request.body = null\n\n // 2. For each headerName of request-body-header name, delete headerName from\n // request’s header list.\n for (const headerName of requestBodyHeader) {\n request.headersList.delete(headerName)\n }\n }\n\n // 13. If request’s current URL’s origin is not same origin with locationURL’s\n // origin, then for each headerName of CORS non-wildcard request-header name,\n // delete headerName from request’s header list.\n if (!sameOrigin(requestCurrentURL(request), locationURL)) {\n // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name\n request.headersList.delete('authorization')\n\n // https://fetch.spec.whatwg.org/#authentication-entries\n request.headersList.delete('proxy-authorization', true)\n\n // \"Cookie\" and \"Host\" are forbidden request-headers, which undici doesn't implement.\n request.headersList.delete('cookie')\n request.headersList.delete('host')\n }\n\n // 14. If request’s body is non-null, then set request’s body to the first return\n // value of safely extracting request’s body’s source.\n if (request.body != null) {\n assert(request.body.source != null)\n request.body = safelyExtractBody(request.body.source)[0]\n }\n\n // 15. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 16. Set timingInfo’s redirect end time and post-redirect start time to the\n // coarsened shared current time given fetchParams’s cross-origin isolated\n // capability.\n timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =\n coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)\n\n // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s\n // redirect start time to timingInfo’s start time.\n if (timingInfo.redirectStartTime === 0) {\n timingInfo.redirectStartTime = timingInfo.startTime\n }\n\n // 18. Append locationURL to request’s URL list.\n request.urlList.push(locationURL)\n\n // 19. Invoke set request’s referrer policy on redirect on request and\n // actualResponse.\n setRequestReferrerPolicyOnRedirect(request, actualResponse)\n\n // 20. Return the result of running main fetch given fetchParams and true.\n return mainFetch(fetchParams, true)\n}\n\n// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch\nasync function httpNetworkOrCacheFetch (\n fetchParams,\n isAuthenticationFetch = false,\n isNewConnectionFetch = false\n) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let httpFetchParams be null.\n let httpFetchParams = null\n\n // 3. Let httpRequest be null.\n let httpRequest = null\n\n // 4. Let response be null.\n let response = null\n\n // 5. Let storedResponse be null.\n // TODO: cache\n\n // 6. Let httpCache be null.\n const httpCache = null\n\n // 7. Let the revalidatingFlag be unset.\n const revalidatingFlag = false\n\n // 8. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If request’s window is \"no-window\" and request’s redirect mode is\n // \"error\", then set httpFetchParams to fetchParams and httpRequest to\n // request.\n if (request.window === 'no-window' && request.redirect === 'error') {\n httpFetchParams = fetchParams\n httpRequest = request\n } else {\n // Otherwise:\n\n // 1. Set httpRequest to a clone of request.\n httpRequest = makeRequest(request)\n\n // 2. Set httpFetchParams to a copy of fetchParams.\n httpFetchParams = { ...fetchParams }\n\n // 3. Set httpFetchParams’s request to httpRequest.\n httpFetchParams.request = httpRequest\n }\n\n // 3. Let includeCredentials be true if one of\n const includeCredentials =\n request.credentials === 'include' ||\n (request.credentials === 'same-origin' &&\n request.responseTainting === 'basic')\n\n // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s\n // body is non-null; otherwise null.\n const contentLength = httpRequest.body ? httpRequest.body.length : null\n\n // 5. Let contentLengthHeaderValue be null.\n let contentLengthHeaderValue = null\n\n // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or\n // `PUT`, then set contentLengthHeaderValue to `0`.\n if (\n httpRequest.body == null &&\n ['POST', 'PUT'].includes(httpRequest.method)\n ) {\n contentLengthHeaderValue = '0'\n }\n\n // 7. If contentLength is non-null, then set contentLengthHeaderValue to\n // contentLength, serialized and isomorphic encoded.\n if (contentLength != null) {\n contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)\n }\n\n // 8. If contentLengthHeaderValue is non-null, then append\n // `Content-Length`/contentLengthHeaderValue to httpRequest’s header\n // list.\n if (contentLengthHeaderValue != null) {\n httpRequest.headersList.append('content-length', contentLengthHeaderValue)\n }\n\n // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,\n // contentLengthHeaderValue) to httpRequest’s header list.\n\n // 10. If contentLength is non-null and httpRequest’s keepalive is true,\n // then:\n if (contentLength != null && httpRequest.keepalive) {\n // NOTE: keepalive is a noop outside of browser context.\n }\n\n // 11. If httpRequest’s referrer is a URL, then append\n // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,\n // to httpRequest’s header list.\n if (httpRequest.referrer instanceof URL) {\n httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))\n }\n\n // 12. Append a request `Origin` header for httpRequest.\n appendRequestOriginHeader(httpRequest)\n\n // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]\n appendFetchMetadata(httpRequest)\n\n // 14. If httpRequest’s header list does not contain `User-Agent`, then\n // user agents should append `User-Agent`/default `User-Agent` value to\n // httpRequest’s header list.\n if (!httpRequest.headersList.contains('user-agent')) {\n httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')\n }\n\n // 15. If httpRequest’s cache mode is \"default\" and httpRequest’s header\n // list contains `If-Modified-Since`, `If-None-Match`,\n // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set\n // httpRequest’s cache mode to \"no-store\".\n if (\n httpRequest.cache === 'default' &&\n (httpRequest.headersList.contains('if-modified-since') ||\n httpRequest.headersList.contains('if-none-match') ||\n httpRequest.headersList.contains('if-unmodified-since') ||\n httpRequest.headersList.contains('if-match') ||\n httpRequest.headersList.contains('if-range'))\n ) {\n httpRequest.cache = 'no-store'\n }\n\n // 16. If httpRequest’s cache mode is \"no-cache\", httpRequest’s prevent\n // no-cache cache-control header modification flag is unset, and\n // httpRequest’s header list does not contain `Cache-Control`, then append\n // `Cache-Control`/`max-age=0` to httpRequest’s header list.\n if (\n httpRequest.cache === 'no-cache' &&\n !httpRequest.preventNoCacheCacheControlHeaderModification &&\n !httpRequest.headersList.contains('cache-control')\n ) {\n httpRequest.headersList.append('cache-control', 'max-age=0')\n }\n\n // 17. If httpRequest’s cache mode is \"no-store\" or \"reload\", then:\n if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {\n // 1. If httpRequest’s header list does not contain `Pragma`, then append\n // `Pragma`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('pragma')) {\n httpRequest.headersList.append('pragma', 'no-cache')\n }\n\n // 2. If httpRequest’s header list does not contain `Cache-Control`,\n // then append `Cache-Control`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('cache-control')) {\n httpRequest.headersList.append('cache-control', 'no-cache')\n }\n }\n\n // 18. If httpRequest’s header list contains `Range`, then append\n // `Accept-Encoding`/`identity` to httpRequest’s header list.\n if (httpRequest.headersList.contains('range')) {\n httpRequest.headersList.append('accept-encoding', 'identity')\n }\n\n // 19. Modify httpRequest’s header list per HTTP. Do not append a given\n // header if httpRequest’s header list contains that header’s name.\n // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129\n if (!httpRequest.headersList.contains('accept-encoding')) {\n if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {\n httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')\n } else {\n httpRequest.headersList.append('accept-encoding', 'gzip, deflate')\n }\n }\n\n httpRequest.headersList.delete('host')\n\n // 20. If includeCredentials is true, then:\n if (includeCredentials) {\n // 1. If the user agent is not configured to block cookies for httpRequest\n // (see section 7 of [COOKIES]), then:\n // TODO: credentials\n // 2. If httpRequest’s header list does not contain `Authorization`, then:\n // TODO: credentials\n }\n\n // 21. If there’s a proxy-authentication entry, use it as appropriate.\n // TODO: proxy-authentication\n\n // 22. Set httpCache to the result of determining the HTTP cache\n // partition, given httpRequest.\n // TODO: cache\n\n // 23. If httpCache is null, then set httpRequest’s cache mode to\n // \"no-store\".\n if (httpCache == null) {\n httpRequest.cache = 'no-store'\n }\n\n // 24. If httpRequest’s cache mode is neither \"no-store\" nor \"reload\",\n // then:\n if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {\n // TODO: cache\n }\n\n // 9. If aborted, then return the appropriate network error for fetchParams.\n // TODO\n\n // 10. If response is null, then:\n if (response == null) {\n // 1. If httpRequest’s cache mode is \"only-if-cached\", then return a\n // network error.\n if (httpRequest.mode === 'only-if-cached') {\n return makeNetworkError('only if cached')\n }\n\n // 2. Let forwardResponse be the result of running HTTP-network fetch\n // given httpFetchParams, includeCredentials, and isNewConnectionFetch.\n const forwardResponse = await httpNetworkFetch(\n httpFetchParams,\n includeCredentials,\n isNewConnectionFetch\n )\n\n // 3. If httpRequest’s method is unsafe and forwardResponse’s status is\n // in the range 200 to 399, inclusive, invalidate appropriate stored\n // responses in httpCache, as per the \"Invalidation\" chapter of HTTP\n // Caching, and set storedResponse to null. [HTTP-CACHING]\n if (\n !safeMethodsSet.has(httpRequest.method) &&\n forwardResponse.status >= 200 &&\n forwardResponse.status <= 399\n ) {\n // TODO: cache\n }\n\n // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,\n // then:\n if (revalidatingFlag && forwardResponse.status === 304) {\n // TODO: cache\n }\n\n // 5. If response is null, then:\n if (response == null) {\n // 1. Set response to forwardResponse.\n response = forwardResponse\n\n // 2. Store httpRequest and forwardResponse in httpCache, as per the\n // \"Storing Responses in Caches\" chapter of HTTP Caching. [HTTP-CACHING]\n // TODO: cache\n }\n }\n\n // 11. Set response’s URL list to a clone of httpRequest’s URL list.\n response.urlList = [...httpRequest.urlList]\n\n // 12. If httpRequest’s header list contains `Range`, then set response’s\n // range-requested flag.\n if (httpRequest.headersList.contains('range')) {\n response.rangeRequested = true\n }\n\n // 13. Set response’s request-includes-credentials to includeCredentials.\n response.requestIncludesCredentials = includeCredentials\n\n // 14. If response’s status is 401, httpRequest’s response tainting is not\n // \"cors\", includeCredentials is true, and request’s window is an environment\n // settings object, then:\n // TODO\n\n // 15. If response’s status is 407, then:\n if (response.status === 407) {\n // 1. If request’s window is \"no-window\", then return a network error.\n if (request.window === 'no-window') {\n return makeNetworkError()\n }\n\n // 2. ???\n\n // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 4. Prompt the end user as appropriate in request’s window and store\n // the result as a proxy-authentication entry. [HTTP-AUTH]\n // TODO: Invoke some kind of callback?\n\n // 5. Set response to the result of running HTTP-network-or-cache fetch given\n // fetchParams.\n // TODO\n return makeNetworkError('proxy authentication required')\n }\n\n // 16. If all of the following are true\n if (\n // response’s status is 421\n response.status === 421 &&\n // isNewConnectionFetch is false\n !isNewConnectionFetch &&\n // request’s body is null, or request’s body is non-null and request’s body’s source is non-null\n (request.body == null || request.body.source != null)\n ) {\n // then:\n\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 2. Set response to the result of running HTTP-network-or-cache\n // fetch given fetchParams, isAuthenticationFetch, and true.\n\n // TODO (spec): The spec doesn't specify this but we need to cancel\n // the active response before we can start a new one.\n // https://github.com/whatwg/fetch/issues/1293\n fetchParams.controller.connection.destroy()\n\n response = await httpNetworkOrCacheFetch(\n fetchParams,\n isAuthenticationFetch,\n true\n )\n }\n\n // 17. If isAuthenticationFetch is true, then create an authentication entry\n if (isAuthenticationFetch) {\n // TODO\n }\n\n // 18. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-network-fetch\nasync function httpNetworkFetch (\n fetchParams,\n includeCredentials = false,\n forceNewConnection = false\n) {\n assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)\n\n fetchParams.controller.connection = {\n abort: null,\n destroyed: false,\n destroy (err) {\n if (!this.destroyed) {\n this.destroyed = true\n this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))\n }\n }\n }\n\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 4. Let httpCache be the result of determining the HTTP cache partition,\n // given request.\n // TODO: cache\n const httpCache = null\n\n // 5. If httpCache is null, then set request’s cache mode to \"no-store\".\n if (httpCache == null) {\n request.cache = 'no-store'\n }\n\n // 6. Let networkPartitionKey be the result of determining the network\n // partition key given request.\n // TODO\n\n // 7. Let newConnection be \"yes\" if forceNewConnection is true; otherwise\n // \"no\".\n const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars\n\n // 8. Switch on request’s mode:\n if (request.mode === 'websocket') {\n // Let connection be the result of obtaining a WebSocket connection,\n // given request’s current URL.\n // TODO\n } else {\n // Let connection be the result of obtaining a connection, given\n // networkPartitionKey, request’s current URL’s origin,\n // includeCredentials, and forceNewConnection.\n // TODO\n }\n\n // 9. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If connection is failure, then return a network error.\n\n // 2. Set timingInfo’s final connection timing info to the result of\n // calling clamp and coarsen connection timing info with connection’s\n // timing info, timingInfo’s post-redirect start time, and fetchParams’s\n // cross-origin isolated capability.\n\n // 3. If connection is not an HTTP/2 connection, request’s body is non-null,\n // and request’s body’s source is null, then append (`Transfer-Encoding`,\n // `chunked`) to request’s header list.\n\n // 4. Set timingInfo’s final network-request start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated\n // capability.\n\n // 5. Set response to the result of making an HTTP request over connection\n // using request with the following caveats:\n\n // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]\n // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]\n\n // - If request’s body is non-null, and request’s body’s source is null,\n // then the user agent may have a buffer of up to 64 kibibytes and store\n // a part of request’s body in that buffer. If the user agent reads from\n // request’s body beyond that buffer’s size and the user agent needs to\n // resend request, then instead return a network error.\n\n // - Set timingInfo’s final network-response start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated capability,\n // immediately after the user agent’s HTTP parser receives the first byte\n // of the response (e.g., frame header bytes for HTTP/2 or response status\n // line for HTTP/1.x).\n\n // - Wait until all the headers are transmitted.\n\n // - Any responses whose status is in the range 100 to 199, inclusive,\n // and is not 101, are to be ignored, except for the purposes of setting\n // timingInfo’s final network-response start time above.\n\n // - If request’s header list contains `Transfer-Encoding`/`chunked` and\n // response is transferred via HTTP/1.0 or older, then return a network\n // error.\n\n // - If the HTTP request results in a TLS client certificate dialog, then:\n\n // 1. If request’s window is an environment settings object, make the\n // dialog available in request’s window.\n\n // 2. Otherwise, return a network error.\n\n // To transmit request’s body body, run these steps:\n let requestBody = null\n // 1. If body is null and fetchParams’s process request end-of-body is\n // non-null, then queue a fetch task given fetchParams’s process request\n // end-of-body and fetchParams’s task destination.\n if (request.body == null && fetchParams.processRequestEndOfBody) {\n queueMicrotask(() => fetchParams.processRequestEndOfBody())\n } else if (request.body != null) {\n // 2. Otherwise, if body is non-null:\n\n // 1. Let processBodyChunk given bytes be these steps:\n const processBodyChunk = async function * (bytes) {\n // 1. If the ongoing fetch is terminated, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. Run this step in parallel: transmit bytes.\n yield bytes\n\n // 3. If fetchParams’s process request body is non-null, then run\n // fetchParams’s process request body given bytes’s length.\n fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)\n }\n\n // 2. Let processEndOfBody be these steps:\n const processEndOfBody = () => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If fetchParams’s process request end-of-body is non-null,\n // then run fetchParams’s process request end-of-body.\n if (fetchParams.processRequestEndOfBody) {\n fetchParams.processRequestEndOfBody()\n }\n }\n\n // 3. Let processBodyError given e be these steps:\n const processBodyError = (e) => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If e is an \"AbortError\" DOMException, then abort fetchParams’s controller.\n if (e.name === 'AbortError') {\n fetchParams.controller.abort()\n } else {\n fetchParams.controller.terminate(e)\n }\n }\n\n // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,\n // processBodyError, and fetchParams’s task destination.\n requestBody = (async function * () {\n try {\n for await (const bytes of request.body.stream) {\n yield * processBodyChunk(bytes)\n }\n processEndOfBody()\n } catch (err) {\n processBodyError(err)\n }\n })()\n }\n\n try {\n // socket is only provided for websockets\n const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })\n\n if (socket) {\n response = makeResponse({ status, statusText, headersList, socket })\n } else {\n const iterator = body[Symbol.asyncIterator]()\n fetchParams.controller.next = () => iterator.next()\n\n response = makeResponse({ status, statusText, headersList })\n }\n } catch (err) {\n // 10. If aborted, then:\n if (err.name === 'AbortError') {\n // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n fetchParams.controller.connection.destroy()\n\n // 2. Return the appropriate network error for fetchParams.\n return makeAppropriateNetworkError(fetchParams, err)\n }\n\n return makeNetworkError(err)\n }\n\n // 11. Let pullAlgorithm be an action that resumes the ongoing fetch\n // if it is suspended.\n const pullAlgorithm = () => {\n fetchParams.controller.resume()\n }\n\n // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s\n // controller with reason, given reason.\n const cancelAlgorithm = (reason) => {\n fetchParams.controller.abort(reason)\n }\n\n // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by\n // the user agent.\n // TODO\n\n // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object\n // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.\n // TODO\n\n // 15. Let stream be a new ReadableStream.\n // 16. Set up stream with pullAlgorithm set to pullAlgorithm,\n // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to\n // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n const stream = new ReadableStream(\n {\n async start (controller) {\n fetchParams.controller.controller = controller\n },\n async pull (controller) {\n await pullAlgorithm(controller)\n },\n async cancel (reason) {\n await cancelAlgorithm(reason)\n }\n },\n {\n highWaterMark: 0,\n size () {\n return 1\n }\n }\n )\n\n // 17. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. Set response’s body to a new body whose stream is stream.\n response.body = { stream }\n\n // 2. If response is not a network error and request’s cache mode is\n // not \"no-store\", then update response in httpCache for request.\n // TODO\n\n // 3. If includeCredentials is true and the user agent is not configured\n // to block cookies for request (see section 7 of [COOKIES]), then run the\n // \"set-cookie-string\" parsing algorithm (see section 5.2 of [COOKIES]) on\n // the value of each header whose name is a byte-case-insensitive match for\n // `Set-Cookie` in response’s header list, if any, and request’s current URL.\n // TODO\n\n // 18. If aborted, then:\n // TODO\n\n // 19. Run these steps in parallel:\n\n // 1. Run these steps, but abort when fetchParams is canceled:\n fetchParams.controller.on('terminated', onAborted)\n fetchParams.controller.resume = async () => {\n // 1. While true\n while (true) {\n // 1-3. See onData...\n\n // 4. Set bytes to the result of handling content codings given\n // codings and bytes.\n let bytes\n let isFailure\n try {\n const { done, value } = await fetchParams.controller.next()\n\n if (isAborted(fetchParams)) {\n break\n }\n\n bytes = done ? undefined : value\n } catch (err) {\n if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {\n // zlib doesn't like empty streams.\n bytes = undefined\n } else {\n bytes = err\n\n // err may be propagated from the result of calling readablestream.cancel,\n // which might not be an error. https://github.com/nodejs/undici/issues/2009\n isFailure = true\n }\n }\n\n if (bytes === undefined) {\n // 2. Otherwise, if the bytes transmission for response’s message\n // body is done normally and stream is readable, then close\n // stream, finalize response for fetchParams and response, and\n // abort these in-parallel steps.\n readableStreamClose(fetchParams.controller.controller)\n\n finalizeResponse(fetchParams, response)\n\n return\n }\n\n // 5. Increase timingInfo’s decoded body size by bytes’s length.\n timingInfo.decodedBodySize += bytes?.byteLength ?? 0\n\n // 6. If bytes is failure, then terminate fetchParams’s controller.\n if (isFailure) {\n fetchParams.controller.terminate(bytes)\n return\n }\n\n // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes\n // into stream.\n fetchParams.controller.controller.enqueue(new Uint8Array(bytes))\n\n // 8. If stream is errored, then terminate the ongoing fetch.\n if (isErrored(stream)) {\n fetchParams.controller.terminate()\n return\n }\n\n // 9. If stream doesn’t need more data ask the user agent to suspend\n // the ongoing fetch.\n if (!fetchParams.controller.controller.desiredSize) {\n return\n }\n }\n }\n\n // 2. If aborted, then:\n function onAborted (reason) {\n // 2. If fetchParams is aborted, then:\n if (isAborted(fetchParams)) {\n // 1. Set response’s aborted flag.\n response.aborted = true\n\n // 2. If stream is readable, then error stream with the result of\n // deserialize a serialized abort reason given fetchParams’s\n // controller’s serialized abort reason and an\n // implementation-defined realm.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(\n fetchParams.controller.serializedAbortReason\n )\n }\n } else {\n // 3. Otherwise, if stream is readable, error stream with a TypeError.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(new TypeError('terminated', {\n cause: isErrorLike(reason) ? reason : undefined\n }))\n }\n }\n\n // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.\n fetchParams.controller.connection.destroy()\n }\n\n // 20. Return response.\n return response\n\n async function dispatch ({ body }) {\n const url = requestCurrentURL(request)\n /** @type {import('../..').Agent} */\n const agent = fetchParams.controller.dispatcher\n\n return new Promise((resolve, reject) => agent.dispatch(\n {\n path: url.pathname + url.search,\n origin: url.origin,\n method: request.method,\n body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,\n headers: request.headersList.entries,\n maxRedirections: 0,\n upgrade: request.mode === 'websocket' ? 'websocket' : undefined\n },\n {\n body: null,\n abort: null,\n\n onConnect (abort) {\n // TODO (fix): Do we need connection here?\n const { connection } = fetchParams.controller\n\n if (connection.destroyed) {\n abort(new DOMException('The operation was aborted.', 'AbortError'))\n } else {\n fetchParams.controller.on('terminated', abort)\n this.abort = connection.abort = abort\n }\n },\n\n onHeaders (status, headersList, resume, statusText) {\n if (status < 200) {\n return\n }\n\n let codings = []\n let location = ''\n\n const headers = new Headers()\n\n // For H2, the headers are a plain JS object\n // We distinguish between them and iterate accordingly\n if (Array.isArray(headersList)) {\n for (let n = 0; n < headersList.length; n += 2) {\n const key = headersList[n + 0].toString('latin1')\n const val = headersList[n + 1].toString('latin1')\n if (key.toLowerCase() === 'content-encoding') {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n // \"All content-coding values are case-insensitive...\"\n codings = val.toLowerCase().split(',').map((x) => x.trim())\n } else if (key.toLowerCase() === 'location') {\n location = val\n }\n\n headers[kHeadersList].append(key, val)\n }\n } else {\n const keys = Object.keys(headersList)\n for (const key of keys) {\n const val = headersList[key]\n if (key.toLowerCase() === 'content-encoding') {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n // \"All content-coding values are case-insensitive...\"\n codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()\n } else if (key.toLowerCase() === 'location') {\n location = val\n }\n\n headers[kHeadersList].append(key, val)\n }\n }\n\n this.body = new Readable({ read: resume })\n\n const decoders = []\n\n const willFollow = request.redirect === 'follow' &&\n location &&\n redirectStatusSet.has(status)\n\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding\n if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {\n for (const coding of codings) {\n // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2\n if (coding === 'x-gzip' || coding === 'gzip') {\n decoders.push(zlib.createGunzip({\n // Be less strict when decoding compressed responses, since sometimes\n // servers send slightly invalid responses that are still accepted\n // by common browsers.\n // Always using Z_SYNC_FLUSH is what cURL does.\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH\n }))\n } else if (coding === 'deflate') {\n decoders.push(zlib.createInflate())\n } else if (coding === 'br') {\n decoders.push(zlib.createBrotliDecompress())\n } else {\n decoders.length = 0\n break\n }\n }\n }\n\n resolve({\n status,\n statusText,\n headersList: headers[kHeadersList],\n body: decoders.length\n ? pipeline(this.body, ...decoders, () => { })\n : this.body.on('error', () => {})\n })\n\n return true\n },\n\n onData (chunk) {\n if (fetchParams.controller.dump) {\n return\n }\n\n // 1. If one or more bytes have been transmitted from response’s\n // message body, then:\n\n // 1. Let bytes be the transmitted bytes.\n const bytes = chunk\n\n // 2. Let codings be the result of extracting header list values\n // given `Content-Encoding` and response’s header list.\n // See pullAlgorithm.\n\n // 3. Increase timingInfo’s encoded body size by bytes’s length.\n timingInfo.encodedBodySize += bytes.byteLength\n\n // 4. See pullAlgorithm...\n\n return this.body.push(bytes)\n },\n\n onComplete () {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n fetchParams.controller.ended = true\n\n this.body.push(null)\n },\n\n onError (error) {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n this.body?.destroy(error)\n\n fetchParams.controller.terminate(error)\n\n reject(error)\n },\n\n onUpgrade (status, headersList, socket) {\n if (status !== 101) {\n return\n }\n\n const headers = new Headers()\n\n for (let n = 0; n < headersList.length; n += 2) {\n const key = headersList[n + 0].toString('latin1')\n const val = headersList[n + 1].toString('latin1')\n\n headers[kHeadersList].append(key, val)\n }\n\n resolve({\n status,\n statusText: STATUS_CODES[status],\n headersList: headers[kHeadersList],\n socket\n })\n\n return true\n }\n }\n ))\n }\n}\n\nmodule.exports = {\n fetch,\n Fetch,\n fetching,\n finalizeAndReportTiming\n}\n","/* globals AbortController */\n\n'use strict'\n\nconst { extractBody, mixinBody, cloneBody } = require('./body')\nconst { Headers, fill: fillHeaders, HeadersList } = require('./headers')\nconst { FinalizationRegistry } = require('../compat/dispatcher-weakref')()\nconst util = require('../core/util')\nconst {\n isValidHTTPToken,\n sameOrigin,\n normalizeMethod,\n makePolicyContainer,\n normalizeMethodRecord\n} = require('./util')\nconst {\n forbiddenMethodsSet,\n corsSafeListedMethodsSet,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n requestDuplex\n} = require('./constants')\nconst { kEnumerableProperty } = util\nconst { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { getGlobalOrigin } = require('./global')\nconst { URLSerializer } = require('./dataURL')\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst assert = require('assert')\nconst { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('events')\n\nlet TransformStream = globalThis.TransformStream\n\nconst kAbortController = Symbol('abortController')\n\nconst requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {\n signal.removeEventListener('abort', abort)\n})\n\n// https://fetch.spec.whatwg.org/#request-class\nclass Request {\n // https://fetch.spec.whatwg.org/#dom-request\n constructor (input, init = {}) {\n if (input === kConstruct) {\n return\n }\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })\n\n input = webidl.converters.RequestInfo(input)\n init = webidl.converters.RequestInit(init)\n\n // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object\n this[kRealm] = {\n settingsObject: {\n baseUrl: getGlobalOrigin(),\n get origin () {\n return this.baseUrl?.origin\n },\n policyContainer: makePolicyContainer()\n }\n }\n\n // 1. Let request be null.\n let request = null\n\n // 2. Let fallbackMode be null.\n let fallbackMode = null\n\n // 3. Let baseURL be this’s relevant settings object’s API base URL.\n const baseUrl = this[kRealm].settingsObject.baseUrl\n\n // 4. Let signal be null.\n let signal = null\n\n // 5. If input is a string, then:\n if (typeof input === 'string') {\n // 1. Let parsedURL be the result of parsing input with baseURL.\n // 2. If parsedURL is failure, then throw a TypeError.\n let parsedURL\n try {\n parsedURL = new URL(input, baseUrl)\n } catch (err) {\n throw new TypeError('Failed to parse URL from ' + input, { cause: err })\n }\n\n // 3. If parsedURL includes credentials, then throw a TypeError.\n if (parsedURL.username || parsedURL.password) {\n throw new TypeError(\n 'Request cannot be constructed from a URL that includes credentials: ' +\n input\n )\n }\n\n // 4. Set request to a new request whose URL is parsedURL.\n request = makeRequest({ urlList: [parsedURL] })\n\n // 5. Set fallbackMode to \"cors\".\n fallbackMode = 'cors'\n } else {\n // 6. Otherwise:\n\n // 7. Assert: input is a Request object.\n assert(input instanceof Request)\n\n // 8. Set request to input’s request.\n request = input[kState]\n\n // 9. Set signal to input’s signal.\n signal = input[kSignal]\n }\n\n // 7. Let origin be this’s relevant settings object’s origin.\n const origin = this[kRealm].settingsObject.origin\n\n // 8. Let window be \"client\".\n let window = 'client'\n\n // 9. If request’s window is an environment settings object and its origin\n // is same origin with origin, then set window to request’s window.\n if (\n request.window?.constructor?.name === 'EnvironmentSettingsObject' &&\n sameOrigin(request.window, origin)\n ) {\n window = request.window\n }\n\n // 10. If init[\"window\"] exists and is non-null, then throw a TypeError.\n if (init.window != null) {\n throw new TypeError(`'window' option '${window}' must be null`)\n }\n\n // 11. If init[\"window\"] exists, then set window to \"no-window\".\n if ('window' in init) {\n window = 'no-window'\n }\n\n // 12. Set request to a new request with the following properties:\n request = makeRequest({\n // URL request’s URL.\n // undici implementation note: this is set as the first item in request's urlList in makeRequest\n // method request’s method.\n method: request.method,\n // header list A copy of request’s header list.\n // undici implementation note: headersList is cloned in makeRequest\n headersList: request.headersList,\n // unsafe-request flag Set.\n unsafeRequest: request.unsafeRequest,\n // client This’s relevant settings object.\n client: this[kRealm].settingsObject,\n // window window.\n window,\n // priority request’s priority.\n priority: request.priority,\n // origin request’s origin. The propagation of the origin is only significant for navigation requests\n // being handled by a service worker. In this scenario a request can have an origin that is different\n // from the current client.\n origin: request.origin,\n // referrer request’s referrer.\n referrer: request.referrer,\n // referrer policy request’s referrer policy.\n referrerPolicy: request.referrerPolicy,\n // mode request’s mode.\n mode: request.mode,\n // credentials mode request’s credentials mode.\n credentials: request.credentials,\n // cache mode request’s cache mode.\n cache: request.cache,\n // redirect mode request’s redirect mode.\n redirect: request.redirect,\n // integrity metadata request’s integrity metadata.\n integrity: request.integrity,\n // keepalive request’s keepalive.\n keepalive: request.keepalive,\n // reload-navigation flag request’s reload-navigation flag.\n reloadNavigation: request.reloadNavigation,\n // history-navigation flag request’s history-navigation flag.\n historyNavigation: request.historyNavigation,\n // URL list A clone of request’s URL list.\n urlList: [...request.urlList]\n })\n\n const initHasKey = Object.keys(init).length !== 0\n\n // 13. If init is not empty, then:\n if (initHasKey) {\n // 1. If request’s mode is \"navigate\", then set it to \"same-origin\".\n if (request.mode === 'navigate') {\n request.mode = 'same-origin'\n }\n\n // 2. Unset request’s reload-navigation flag.\n request.reloadNavigation = false\n\n // 3. Unset request’s history-navigation flag.\n request.historyNavigation = false\n\n // 4. Set request’s origin to \"client\".\n request.origin = 'client'\n\n // 5. Set request’s referrer to \"client\"\n request.referrer = 'client'\n\n // 6. Set request’s referrer policy to the empty string.\n request.referrerPolicy = ''\n\n // 7. Set request’s URL to request’s current URL.\n request.url = request.urlList[request.urlList.length - 1]\n\n // 8. Set request’s URL list to « request’s URL ».\n request.urlList = [request.url]\n }\n\n // 14. If init[\"referrer\"] exists, then:\n if (init.referrer !== undefined) {\n // 1. Let referrer be init[\"referrer\"].\n const referrer = init.referrer\n\n // 2. If referrer is the empty string, then set request’s referrer to \"no-referrer\".\n if (referrer === '') {\n request.referrer = 'no-referrer'\n } else {\n // 1. Let parsedReferrer be the result of parsing referrer with\n // baseURL.\n // 2. If parsedReferrer is failure, then throw a TypeError.\n let parsedReferrer\n try {\n parsedReferrer = new URL(referrer, baseUrl)\n } catch (err) {\n throw new TypeError(`Referrer \"${referrer}\" is not a valid URL.`, { cause: err })\n }\n\n // 3. If one of the following is true\n // - parsedReferrer’s scheme is \"about\" and path is the string \"client\"\n // - parsedReferrer’s origin is not same origin with origin\n // then set request’s referrer to \"client\".\n if (\n (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||\n (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))\n ) {\n request.referrer = 'client'\n } else {\n // 4. Otherwise, set request’s referrer to parsedReferrer.\n request.referrer = parsedReferrer\n }\n }\n }\n\n // 15. If init[\"referrerPolicy\"] exists, then set request’s referrer policy\n // to it.\n if (init.referrerPolicy !== undefined) {\n request.referrerPolicy = init.referrerPolicy\n }\n\n // 16. Let mode be init[\"mode\"] if it exists, and fallbackMode otherwise.\n let mode\n if (init.mode !== undefined) {\n mode = init.mode\n } else {\n mode = fallbackMode\n }\n\n // 17. If mode is \"navigate\", then throw a TypeError.\n if (mode === 'navigate') {\n throw webidl.errors.exception({\n header: 'Request constructor',\n message: 'invalid request mode navigate.'\n })\n }\n\n // 18. If mode is non-null, set request’s mode to mode.\n if (mode != null) {\n request.mode = mode\n }\n\n // 19. If init[\"credentials\"] exists, then set request’s credentials mode\n // to it.\n if (init.credentials !== undefined) {\n request.credentials = init.credentials\n }\n\n // 18. If init[\"cache\"] exists, then set request’s cache mode to it.\n if (init.cache !== undefined) {\n request.cache = init.cache\n }\n\n // 21. If request’s cache mode is \"only-if-cached\" and request’s mode is\n // not \"same-origin\", then throw a TypeError.\n if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n throw new TypeError(\n \"'only-if-cached' can be set only with 'same-origin' mode\"\n )\n }\n\n // 22. If init[\"redirect\"] exists, then set request’s redirect mode to it.\n if (init.redirect !== undefined) {\n request.redirect = init.redirect\n }\n\n // 23. If init[\"integrity\"] exists, then set request’s integrity metadata to it.\n if (init.integrity != null) {\n request.integrity = String(init.integrity)\n }\n\n // 24. If init[\"keepalive\"] exists, then set request’s keepalive to it.\n if (init.keepalive !== undefined) {\n request.keepalive = Boolean(init.keepalive)\n }\n\n // 25. If init[\"method\"] exists, then:\n if (init.method !== undefined) {\n // 1. Let method be init[\"method\"].\n let method = init.method\n\n // 2. If method is not a method or method is a forbidden method, then\n // throw a TypeError.\n if (!isValidHTTPToken(method)) {\n throw new TypeError(`'${method}' is not a valid HTTP method.`)\n }\n\n if (forbiddenMethodsSet.has(method.toUpperCase())) {\n throw new TypeError(`'${method}' HTTP method is unsupported.`)\n }\n\n // 3. Normalize method.\n method = normalizeMethodRecord[method] ?? normalizeMethod(method)\n\n // 4. Set request’s method to method.\n request.method = method\n }\n\n // 26. If init[\"signal\"] exists, then set signal to it.\n if (init.signal !== undefined) {\n signal = init.signal\n }\n\n // 27. Set this’s request to request.\n this[kState] = request\n\n // 28. Set this’s signal to a new AbortSignal object with this’s relevant\n // Realm.\n // TODO: could this be simplified with AbortSignal.any\n // (https://dom.spec.whatwg.org/#dom-abortsignal-any)\n const ac = new AbortController()\n this[kSignal] = ac.signal\n this[kSignal][kRealm] = this[kRealm]\n\n // 29. If signal is not null, then make this’s signal follow signal.\n if (signal != null) {\n if (\n !signal ||\n typeof signal.aborted !== 'boolean' ||\n typeof signal.addEventListener !== 'function'\n ) {\n throw new TypeError(\n \"Failed to construct 'Request': member signal is not of type AbortSignal.\"\n )\n }\n\n if (signal.aborted) {\n ac.abort(signal.reason)\n } else {\n // Keep a strong ref to ac while request object\n // is alive. This is needed to prevent AbortController\n // from being prematurely garbage collected.\n // See, https://github.com/nodejs/undici/issues/1926.\n this[kAbortController] = ac\n\n const acRef = new WeakRef(ac)\n const abort = function () {\n const ac = acRef.deref()\n if (ac !== undefined) {\n ac.abort(this.reason)\n }\n }\n\n // Third-party AbortControllers may not work with these.\n // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.\n try {\n // If the max amount of listeners is equal to the default, increase it\n // This is only available in node >= v19.9.0\n if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {\n setMaxListeners(100, signal)\n } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {\n setMaxListeners(100, signal)\n }\n } catch {}\n\n util.addAbortListener(signal, abort)\n requestFinalizer.register(ac, { signal, abort })\n }\n }\n\n // 30. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is request’s header list and guard is\n // \"request\".\n this[kHeaders] = new Headers(kConstruct)\n this[kHeaders][kHeadersList] = request.headersList\n this[kHeaders][kGuard] = 'request'\n this[kHeaders][kRealm] = this[kRealm]\n\n // 31. If this’s request’s mode is \"no-cors\", then:\n if (mode === 'no-cors') {\n // 1. If this’s request’s method is not a CORS-safelisted method,\n // then throw a TypeError.\n if (!corsSafeListedMethodsSet.has(request.method)) {\n throw new TypeError(\n `'${request.method} is unsupported in no-cors mode.`\n )\n }\n\n // 2. Set this’s headers’s guard to \"request-no-cors\".\n this[kHeaders][kGuard] = 'request-no-cors'\n }\n\n // 32. If init is not empty, then:\n if (initHasKey) {\n /** @type {HeadersList} */\n const headersList = this[kHeaders][kHeadersList]\n // 1. Let headers be a copy of this’s headers and its associated header\n // list.\n // 2. If init[\"headers\"] exists, then set headers to init[\"headers\"].\n const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)\n\n // 3. Empty this’s headers’s header list.\n headersList.clear()\n\n // 4. If headers is a Headers object, then for each header in its header\n // list, append header’s name/header’s value to this’s headers.\n if (headers instanceof HeadersList) {\n for (const [key, val] of headers) {\n headersList.append(key, val)\n }\n // Note: Copy the `set-cookie` meta-data.\n headersList.cookies = headers.cookies\n } else {\n // 5. Otherwise, fill this’s headers with headers.\n fillHeaders(this[kHeaders], headers)\n }\n }\n\n // 33. Let inputBody be input’s request’s body if input is a Request\n // object; otherwise null.\n const inputBody = input instanceof Request ? input[kState].body : null\n\n // 34. If either init[\"body\"] exists and is non-null or inputBody is\n // non-null, and request’s method is `GET` or `HEAD`, then throw a\n // TypeError.\n if (\n (init.body != null || inputBody != null) &&\n (request.method === 'GET' || request.method === 'HEAD')\n ) {\n throw new TypeError('Request with GET/HEAD method cannot have body.')\n }\n\n // 35. Let initBody be null.\n let initBody = null\n\n // 36. If init[\"body\"] exists and is non-null, then:\n if (init.body != null) {\n // 1. Let Content-Type be null.\n // 2. Set initBody and Content-Type to the result of extracting\n // init[\"body\"], with keepalive set to request’s keepalive.\n const [extractedBody, contentType] = extractBody(\n init.body,\n request.keepalive\n )\n initBody = extractedBody\n\n // 3, If Content-Type is non-null and this’s headers’s header list does\n // not contain `Content-Type`, then append `Content-Type`/Content-Type to\n // this’s headers.\n if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {\n this[kHeaders].append('content-type', contentType)\n }\n }\n\n // 37. Let inputOrInitBody be initBody if it is non-null; otherwise\n // inputBody.\n const inputOrInitBody = initBody ?? inputBody\n\n // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is\n // null, then:\n if (inputOrInitBody != null && inputOrInitBody.source == null) {\n // 1. If initBody is non-null and init[\"duplex\"] does not exist,\n // then throw a TypeError.\n if (initBody != null && init.duplex == null) {\n throw new TypeError('RequestInit: duplex option is required when sending a body.')\n }\n\n // 2. If this’s request’s mode is neither \"same-origin\" nor \"cors\",\n // then throw a TypeError.\n if (request.mode !== 'same-origin' && request.mode !== 'cors') {\n throw new TypeError(\n 'If request is made from ReadableStream, mode should be \"same-origin\" or \"cors\"'\n )\n }\n\n // 3. Set this’s request’s use-CORS-preflight flag.\n request.useCORSPreflightFlag = true\n }\n\n // 39. Let finalBody be inputOrInitBody.\n let finalBody = inputOrInitBody\n\n // 40. If initBody is null and inputBody is non-null, then:\n if (initBody == null && inputBody != null) {\n // 1. If input is unusable, then throw a TypeError.\n if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {\n throw new TypeError(\n 'Cannot construct a Request with a Request object that has already been used.'\n )\n }\n\n // 2. Set finalBody to the result of creating a proxy for inputBody.\n if (!TransformStream) {\n TransformStream = require('stream/web').TransformStream\n }\n\n // https://streams.spec.whatwg.org/#readablestream-create-a-proxy\n const identityTransform = new TransformStream()\n inputBody.stream.pipeThrough(identityTransform)\n finalBody = {\n source: inputBody.source,\n length: inputBody.length,\n stream: identityTransform.readable\n }\n }\n\n // 41. Set this’s request’s body to finalBody.\n this[kState].body = finalBody\n }\n\n // Returns request’s HTTP method, which is \"GET\" by default.\n get method () {\n webidl.brandCheck(this, Request)\n\n // The method getter steps are to return this’s request’s method.\n return this[kState].method\n }\n\n // Returns the URL of request as a string.\n get url () {\n webidl.brandCheck(this, Request)\n\n // The url getter steps are to return this’s request’s URL, serialized.\n return URLSerializer(this[kState].url)\n }\n\n // Returns a Headers object consisting of the headers associated with request.\n // Note that headers added in the network layer by the user agent will not\n // be accounted for in this object, e.g., the \"Host\" header.\n get headers () {\n webidl.brandCheck(this, Request)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n // Returns the kind of resource requested by request, e.g., \"document\"\n // or \"script\".\n get destination () {\n webidl.brandCheck(this, Request)\n\n // The destination getter are to return this’s request’s destination.\n return this[kState].destination\n }\n\n // Returns the referrer of request. Its value can be a same-origin URL if\n // explicitly set in init, the empty string to indicate no referrer, and\n // \"about:client\" when defaulting to the global’s default. This is used\n // during fetching to determine the value of the `Referer` header of the\n // request being made.\n get referrer () {\n webidl.brandCheck(this, Request)\n\n // 1. If this’s request’s referrer is \"no-referrer\", then return the\n // empty string.\n if (this[kState].referrer === 'no-referrer') {\n return ''\n }\n\n // 2. If this’s request’s referrer is \"client\", then return\n // \"about:client\".\n if (this[kState].referrer === 'client') {\n return 'about:client'\n }\n\n // Return this’s request’s referrer, serialized.\n return this[kState].referrer.toString()\n }\n\n // Returns the referrer policy associated with request.\n // This is used during fetching to compute the value of the request’s\n // referrer.\n get referrerPolicy () {\n webidl.brandCheck(this, Request)\n\n // The referrerPolicy getter steps are to return this’s request’s referrer policy.\n return this[kState].referrerPolicy\n }\n\n // Returns the mode associated with request, which is a string indicating\n // whether the request will use CORS, or will be restricted to same-origin\n // URLs.\n get mode () {\n webidl.brandCheck(this, Request)\n\n // The mode getter steps are to return this’s request’s mode.\n return this[kState].mode\n }\n\n // Returns the credentials mode associated with request,\n // which is a string indicating whether credentials will be sent with the\n // request always, never, or only when sent to a same-origin URL.\n get credentials () {\n // The credentials getter steps are to return this’s request’s credentials mode.\n return this[kState].credentials\n }\n\n // Returns the cache mode associated with request,\n // which is a string indicating how the request will\n // interact with the browser’s cache when fetching.\n get cache () {\n webidl.brandCheck(this, Request)\n\n // The cache getter steps are to return this’s request’s cache mode.\n return this[kState].cache\n }\n\n // Returns the redirect mode associated with request,\n // which is a string indicating how redirects for the\n // request will be handled during fetching. A request\n // will follow redirects by default.\n get redirect () {\n webidl.brandCheck(this, Request)\n\n // The redirect getter steps are to return this’s request’s redirect mode.\n return this[kState].redirect\n }\n\n // Returns request’s subresource integrity metadata, which is a\n // cryptographic hash of the resource being fetched. Its value\n // consists of multiple hashes separated by whitespace. [SRI]\n get integrity () {\n webidl.brandCheck(this, Request)\n\n // The integrity getter steps are to return this’s request’s integrity\n // metadata.\n return this[kState].integrity\n }\n\n // Returns a boolean indicating whether or not request can outlive the\n // global in which it was created.\n get keepalive () {\n webidl.brandCheck(this, Request)\n\n // The keepalive getter steps are to return this’s request’s keepalive.\n return this[kState].keepalive\n }\n\n // Returns a boolean indicating whether or not request is for a reload\n // navigation.\n get isReloadNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isReloadNavigation getter steps are to return true if this’s\n // request’s reload-navigation flag is set; otherwise false.\n return this[kState].reloadNavigation\n }\n\n // Returns a boolean indicating whether or not request is for a history\n // navigation (a.k.a. back-foward navigation).\n get isHistoryNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isHistoryNavigation getter steps are to return true if this’s request’s\n // history-navigation flag is set; otherwise false.\n return this[kState].historyNavigation\n }\n\n // Returns the signal associated with request, which is an AbortSignal\n // object indicating whether or not request has been aborted, and its\n // abort event handler.\n get signal () {\n webidl.brandCheck(this, Request)\n\n // The signal getter steps are to return this’s signal.\n return this[kSignal]\n }\n\n get body () {\n webidl.brandCheck(this, Request)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Request)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n get duplex () {\n webidl.brandCheck(this, Request)\n\n return 'half'\n }\n\n // Returns a clone of request.\n clone () {\n webidl.brandCheck(this, Request)\n\n // 1. If this is unusable, then throw a TypeError.\n if (this.bodyUsed || this.body?.locked) {\n throw new TypeError('unusable')\n }\n\n // 2. Let clonedRequest be the result of cloning this’s request.\n const clonedRequest = cloneRequest(this[kState])\n\n // 3. Let clonedRequestObject be the result of creating a Request object,\n // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.\n const clonedRequestObject = new Request(kConstruct)\n clonedRequestObject[kState] = clonedRequest\n clonedRequestObject[kRealm] = this[kRealm]\n clonedRequestObject[kHeaders] = new Headers(kConstruct)\n clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList\n clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]\n clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]\n\n // 4. Make clonedRequestObject’s signal follow this’s signal.\n const ac = new AbortController()\n if (this.signal.aborted) {\n ac.abort(this.signal.reason)\n } else {\n util.addAbortListener(\n this.signal,\n () => {\n ac.abort(this.signal.reason)\n }\n )\n }\n clonedRequestObject[kSignal] = ac.signal\n\n // 4. Return clonedRequestObject.\n return clonedRequestObject\n }\n}\n\nmixinBody(Request)\n\nfunction makeRequest (init) {\n // https://fetch.spec.whatwg.org/#requests\n const request = {\n method: 'GET',\n localURLsOnly: false,\n unsafeRequest: false,\n body: null,\n client: null,\n reservedClient: null,\n replacesClientId: '',\n window: 'client',\n keepalive: false,\n serviceWorkers: 'all',\n initiator: '',\n destination: '',\n priority: null,\n origin: 'client',\n policyContainer: 'client',\n referrer: 'client',\n referrerPolicy: '',\n mode: 'no-cors',\n useCORSPreflightFlag: false,\n credentials: 'same-origin',\n useCredentials: false,\n cache: 'default',\n redirect: 'follow',\n integrity: '',\n cryptoGraphicsNonceMetadata: '',\n parserMetadata: '',\n reloadNavigation: false,\n historyNavigation: false,\n userActivation: false,\n taintedOrigin: false,\n redirectCount: 0,\n responseTainting: 'basic',\n preventNoCacheCacheControlHeaderModification: false,\n done: false,\n timingAllowFailed: false,\n ...init,\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList()\n }\n request.url = request.urlList[0]\n return request\n}\n\n// https://fetch.spec.whatwg.org/#concept-request-clone\nfunction cloneRequest (request) {\n // To clone a request request, run these steps:\n\n // 1. Let newRequest be a copy of request, except for its body.\n const newRequest = makeRequest({ ...request, body: null })\n\n // 2. If request’s body is non-null, set newRequest’s body to the\n // result of cloning request’s body.\n if (request.body != null) {\n newRequest.body = cloneBody(request.body)\n }\n\n // 3. Return newRequest.\n return newRequest\n}\n\nObject.defineProperties(Request.prototype, {\n method: kEnumerableProperty,\n url: kEnumerableProperty,\n headers: kEnumerableProperty,\n redirect: kEnumerableProperty,\n clone: kEnumerableProperty,\n signal: kEnumerableProperty,\n duplex: kEnumerableProperty,\n destination: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n isHistoryNavigation: kEnumerableProperty,\n isReloadNavigation: kEnumerableProperty,\n keepalive: kEnumerableProperty,\n integrity: kEnumerableProperty,\n cache: kEnumerableProperty,\n credentials: kEnumerableProperty,\n attribute: kEnumerableProperty,\n referrerPolicy: kEnumerableProperty,\n referrer: kEnumerableProperty,\n mode: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Request',\n configurable: true\n }\n})\n\nwebidl.converters.Request = webidl.interfaceConverter(\n Request\n)\n\n// https://fetch.spec.whatwg.org/#requestinfo\nwebidl.converters.RequestInfo = function (V) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V)\n }\n\n if (V instanceof Request) {\n return webidl.converters.Request(V)\n }\n\n return webidl.converters.USVString(V)\n}\n\nwebidl.converters.AbortSignal = webidl.interfaceConverter(\n AbortSignal\n)\n\n// https://fetch.spec.whatwg.org/#requestinit\nwebidl.converters.RequestInit = webidl.dictionaryConverter([\n {\n key: 'method',\n converter: webidl.converters.ByteString\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n },\n {\n key: 'body',\n converter: webidl.nullableConverter(\n webidl.converters.BodyInit\n )\n },\n {\n key: 'referrer',\n converter: webidl.converters.USVString\n },\n {\n key: 'referrerPolicy',\n converter: webidl.converters.DOMString,\n // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy\n allowedValues: referrerPolicy\n },\n {\n key: 'mode',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#concept-request-mode\n allowedValues: requestMode\n },\n {\n key: 'credentials',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcredentials\n allowedValues: requestCredentials\n },\n {\n key: 'cache',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcache\n allowedValues: requestCache\n },\n {\n key: 'redirect',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestredirect\n allowedValues: requestRedirect\n },\n {\n key: 'integrity',\n converter: webidl.converters.DOMString\n },\n {\n key: 'keepalive',\n converter: webidl.converters.boolean\n },\n {\n key: 'signal',\n converter: webidl.nullableConverter(\n (signal) => webidl.converters.AbortSignal(\n signal,\n { strict: false }\n )\n )\n },\n {\n key: 'window',\n converter: webidl.converters.any\n },\n {\n key: 'duplex',\n converter: webidl.converters.DOMString,\n allowedValues: requestDuplex\n }\n])\n\nmodule.exports = { Request, makeRequest }\n","'use strict'\n\nconst { Headers, HeadersList, fill } = require('./headers')\nconst { extractBody, cloneBody, mixinBody } = require('./body')\nconst util = require('../core/util')\nconst { kEnumerableProperty } = util\nconst {\n isValidReasonPhrase,\n isCancelled,\n isAborted,\n isBlobLike,\n serializeJavascriptValueToJSONString,\n isErrorLike,\n isomorphicEncode\n} = require('./util')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n DOMException\n} = require('./constants')\nconst { kState, kHeaders, kGuard, kRealm } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { FormData } = require('./formdata')\nconst { getGlobalOrigin } = require('./global')\nconst { URLSerializer } = require('./dataURL')\nconst { kHeadersList, kConstruct } = require('../core/symbols')\nconst assert = require('assert')\nconst { types } = require('util')\n\nconst ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream\nconst textEncoder = new TextEncoder('utf-8')\n\n// https://fetch.spec.whatwg.org/#response-class\nclass Response {\n // Creates network error Response.\n static error () {\n // TODO\n const relevantRealm = { settingsObject: {} }\n\n // The static error() method steps are to return the result of creating a\n // Response object, given a new network error, \"immutable\", and this’s\n // relevant Realm.\n const responseObject = new Response()\n responseObject[kState] = makeNetworkError()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response-json\n static json (data, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })\n\n if (init !== null) {\n init = webidl.converters.ResponseInit(init)\n }\n\n // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.\n const bytes = textEncoder.encode(\n serializeJavascriptValueToJSONString(data)\n )\n\n // 2. Let body be the result of extracting bytes.\n const body = extractBody(bytes)\n\n // 3. Let responseObject be the result of creating a Response object, given a new response,\n // \"response\", and this’s relevant Realm.\n const relevantRealm = { settingsObject: {} }\n const responseObject = new Response()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kGuard] = 'response'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 4. Perform initialize a response given responseObject, init, and (body, \"application/json\").\n initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })\n\n // 5. Return responseObject.\n return responseObject\n }\n\n // Creates a redirect Response that redirects to url with status status.\n static redirect (url, status = 302) {\n const relevantRealm = { settingsObject: {} }\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })\n\n url = webidl.converters.USVString(url)\n status = webidl.converters['unsigned short'](status)\n\n // 1. Let parsedURL be the result of parsing url with current settings\n // object’s API base URL.\n // 2. If parsedURL is failure, then throw a TypeError.\n // TODO: base-URL?\n let parsedURL\n try {\n parsedURL = new URL(url, getGlobalOrigin())\n } catch (err) {\n throw Object.assign(new TypeError('Failed to parse URL from ' + url), {\n cause: err\n })\n }\n\n // 3. If status is not a redirect status, then throw a RangeError.\n if (!redirectStatusSet.has(status)) {\n throw new RangeError('Invalid status code ' + status)\n }\n\n // 4. Let responseObject be the result of creating a Response object,\n // given a new response, \"immutable\", and this’s relevant Realm.\n const responseObject = new Response()\n responseObject[kRealm] = relevantRealm\n responseObject[kHeaders][kGuard] = 'immutable'\n responseObject[kHeaders][kRealm] = relevantRealm\n\n // 5. Set responseObject’s response’s status to status.\n responseObject[kState].status = status\n\n // 6. Let value be parsedURL, serialized and isomorphic encoded.\n const value = isomorphicEncode(URLSerializer(parsedURL))\n\n // 7. Append `Location`/value to responseObject’s response’s header list.\n responseObject[kState].headersList.append('location', value)\n\n // 8. Return responseObject.\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response\n constructor (body = null, init = {}) {\n if (body !== null) {\n body = webidl.converters.BodyInit(body)\n }\n\n init = webidl.converters.ResponseInit(init)\n\n // TODO\n this[kRealm] = { settingsObject: {} }\n\n // 1. Set this’s response to a new response.\n this[kState] = makeResponse({})\n\n // 2. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is this’s response’s header list and guard\n // is \"response\".\n this[kHeaders] = new Headers(kConstruct)\n this[kHeaders][kGuard] = 'response'\n this[kHeaders][kHeadersList] = this[kState].headersList\n this[kHeaders][kRealm] = this[kRealm]\n\n // 3. Let bodyWithType be null.\n let bodyWithType = null\n\n // 4. If body is non-null, then set bodyWithType to the result of extracting body.\n if (body != null) {\n const [extractedBody, type] = extractBody(body)\n bodyWithType = { body: extractedBody, type }\n }\n\n // 5. Perform initialize a response given this, init, and bodyWithType.\n initializeResponse(this, init, bodyWithType)\n }\n\n // Returns response’s type, e.g., \"cors\".\n get type () {\n webidl.brandCheck(this, Response)\n\n // The type getter steps are to return this’s response’s type.\n return this[kState].type\n }\n\n // Returns response’s URL, if it has one; otherwise the empty string.\n get url () {\n webidl.brandCheck(this, Response)\n\n const urlList = this[kState].urlList\n\n // The url getter steps are to return the empty string if this’s\n // response’s URL is null; otherwise this’s response’s URL,\n // serialized with exclude fragment set to true.\n const url = urlList[urlList.length - 1] ?? null\n\n if (url === null) {\n return ''\n }\n\n return URLSerializer(url, true)\n }\n\n // Returns whether response was obtained through a redirect.\n get redirected () {\n webidl.brandCheck(this, Response)\n\n // The redirected getter steps are to return true if this’s response’s URL\n // list has more than one item; otherwise false.\n return this[kState].urlList.length > 1\n }\n\n // Returns response’s status.\n get status () {\n webidl.brandCheck(this, Response)\n\n // The status getter steps are to return this’s response’s status.\n return this[kState].status\n }\n\n // Returns whether response’s status is an ok status.\n get ok () {\n webidl.brandCheck(this, Response)\n\n // The ok getter steps are to return true if this’s response’s status is an\n // ok status; otherwise false.\n return this[kState].status >= 200 && this[kState].status <= 299\n }\n\n // Returns response’s status message.\n get statusText () {\n webidl.brandCheck(this, Response)\n\n // The statusText getter steps are to return this’s response’s status\n // message.\n return this[kState].statusText\n }\n\n // Returns response’s headers as Headers.\n get headers () {\n webidl.brandCheck(this, Response)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n get body () {\n webidl.brandCheck(this, Response)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Response)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n // Returns a clone of response.\n clone () {\n webidl.brandCheck(this, Response)\n\n // 1. If this is unusable, then throw a TypeError.\n if (this.bodyUsed || (this.body && this.body.locked)) {\n throw webidl.errors.exception({\n header: 'Response.clone',\n message: 'Body has already been consumed.'\n })\n }\n\n // 2. Let clonedResponse be the result of cloning this’s response.\n const clonedResponse = cloneResponse(this[kState])\n\n // 3. Return the result of creating a Response object, given\n // clonedResponse, this’s headers’s guard, and this’s relevant Realm.\n const clonedResponseObject = new Response()\n clonedResponseObject[kState] = clonedResponse\n clonedResponseObject[kRealm] = this[kRealm]\n clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList\n clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]\n clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]\n\n return clonedResponseObject\n }\n}\n\nmixinBody(Response)\n\nObject.defineProperties(Response.prototype, {\n type: kEnumerableProperty,\n url: kEnumerableProperty,\n status: kEnumerableProperty,\n ok: kEnumerableProperty,\n redirected: kEnumerableProperty,\n statusText: kEnumerableProperty,\n headers: kEnumerableProperty,\n clone: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Response',\n configurable: true\n }\n})\n\nObject.defineProperties(Response, {\n json: kEnumerableProperty,\n redirect: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\n// https://fetch.spec.whatwg.org/#concept-response-clone\nfunction cloneResponse (response) {\n // To clone a response response, run these steps:\n\n // 1. If response is a filtered response, then return a new identical\n // filtered response whose internal response is a clone of response’s\n // internal response.\n if (response.internalResponse) {\n return filterResponse(\n cloneResponse(response.internalResponse),\n response.type\n )\n }\n\n // 2. Let newResponse be a copy of response, except for its body.\n const newResponse = makeResponse({ ...response, body: null })\n\n // 3. If response’s body is non-null, then set newResponse’s body to the\n // result of cloning response’s body.\n if (response.body != null) {\n newResponse.body = cloneBody(response.body)\n }\n\n // 4. Return newResponse.\n return newResponse\n}\n\nfunction makeResponse (init) {\n return {\n aborted: false,\n rangeRequested: false,\n timingAllowPassed: false,\n requestIncludesCredentials: false,\n type: 'default',\n status: 200,\n timingInfo: null,\n cacheState: '',\n statusText: '',\n ...init,\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList(),\n urlList: init.urlList ? [...init.urlList] : []\n }\n}\n\nfunction makeNetworkError (reason) {\n const isError = isErrorLike(reason)\n return makeResponse({\n type: 'error',\n status: 0,\n error: isError\n ? reason\n : new Error(reason ? String(reason) : reason),\n aborted: reason && reason.name === 'AbortError'\n })\n}\n\nfunction makeFilteredResponse (response, state) {\n state = {\n internalResponse: response,\n ...state\n }\n\n return new Proxy(response, {\n get (target, p) {\n return p in state ? state[p] : target[p]\n },\n set (target, p, value) {\n assert(!(p in state))\n target[p] = value\n return true\n }\n })\n}\n\n// https://fetch.spec.whatwg.org/#concept-filtered-response\nfunction filterResponse (response, type) {\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (type === 'basic') {\n // A basic filtered response is a filtered response whose type is \"basic\"\n // and header list excludes any headers in internal response’s header list\n // whose name is a forbidden response-header name.\n\n // Note: undici does not implement forbidden response-header names\n return makeFilteredResponse(response, {\n type: 'basic',\n headersList: response.headersList\n })\n } else if (type === 'cors') {\n // A CORS filtered response is a filtered response whose type is \"cors\"\n // and header list excludes any headers in internal response’s header\n // list whose name is not a CORS-safelisted response-header name, given\n // internal response’s CORS-exposed header-name list.\n\n // Note: undici does not implement CORS-safelisted response-header names\n return makeFilteredResponse(response, {\n type: 'cors',\n headersList: response.headersList\n })\n } else if (type === 'opaque') {\n // An opaque filtered response is a filtered response whose type is\n // \"opaque\", URL list is the empty list, status is 0, status message\n // is the empty byte sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaque',\n urlList: Object.freeze([]),\n status: 0,\n statusText: '',\n body: null\n })\n } else if (type === 'opaqueredirect') {\n // An opaque-redirect filtered response is a filtered response whose type\n // is \"opaqueredirect\", status is 0, status message is the empty byte\n // sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaqueredirect',\n status: 0,\n statusText: '',\n headersList: [],\n body: null\n })\n } else {\n assert(false)\n }\n}\n\n// https://fetch.spec.whatwg.org/#appropriate-network-error\nfunction makeAppropriateNetworkError (fetchParams, err = null) {\n // 1. Assert: fetchParams is canceled.\n assert(isCancelled(fetchParams))\n\n // 2. Return an aborted network error if fetchParams is aborted;\n // otherwise return a network error.\n return isAborted(fetchParams)\n ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))\n : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))\n}\n\n// https://whatpr.org/fetch/1392.html#initialize-a-response\nfunction initializeResponse (response, init, body) {\n // 1. If init[\"status\"] is not in the range 200 to 599, inclusive, then\n // throw a RangeError.\n if (init.status !== null && (init.status < 200 || init.status > 599)) {\n throw new RangeError('init[\"status\"] must be in the range of 200 to 599, inclusive.')\n }\n\n // 2. If init[\"statusText\"] does not match the reason-phrase token production,\n // then throw a TypeError.\n if ('statusText' in init && init.statusText != null) {\n // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:\n // reason-phrase = *( HTAB / SP / VCHAR / obs-text )\n if (!isValidReasonPhrase(String(init.statusText))) {\n throw new TypeError('Invalid statusText')\n }\n }\n\n // 3. Set response’s response’s status to init[\"status\"].\n if ('status' in init && init.status != null) {\n response[kState].status = init.status\n }\n\n // 4. Set response’s response’s status message to init[\"statusText\"].\n if ('statusText' in init && init.statusText != null) {\n response[kState].statusText = init.statusText\n }\n\n // 5. If init[\"headers\"] exists, then fill response’s headers with init[\"headers\"].\n if ('headers' in init && init.headers != null) {\n fill(response[kHeaders], init.headers)\n }\n\n // 6. If body was given, then:\n if (body) {\n // 1. If response's status is a null body status, then throw a TypeError.\n if (nullBodyStatus.includes(response.status)) {\n throw webidl.errors.exception({\n header: 'Response constructor',\n message: 'Invalid response status code ' + response.status\n })\n }\n\n // 2. Set response's body to body's body.\n response[kState].body = body.body\n\n // 3. If body's type is non-null and response's header list does not contain\n // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.\n if (body.type != null && !response[kState].headersList.contains('Content-Type')) {\n response[kState].headersList.append('content-type', body.type)\n }\n }\n}\n\nwebidl.converters.ReadableStream = webidl.interfaceConverter(\n ReadableStream\n)\n\nwebidl.converters.FormData = webidl.interfaceConverter(\n FormData\n)\n\nwebidl.converters.URLSearchParams = webidl.interfaceConverter(\n URLSearchParams\n)\n\n// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit\nwebidl.converters.XMLHttpRequestBodyInit = function (V) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V)\n }\n\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {\n return webidl.converters.BufferSource(V)\n }\n\n if (util.isFormDataLike(V)) {\n return webidl.converters.FormData(V, { strict: false })\n }\n\n if (V instanceof URLSearchParams) {\n return webidl.converters.URLSearchParams(V)\n }\n\n return webidl.converters.DOMString(V)\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit\nwebidl.converters.BodyInit = function (V) {\n if (V instanceof ReadableStream) {\n return webidl.converters.ReadableStream(V)\n }\n\n // Note: the spec doesn't include async iterables,\n // this is an undici extension.\n if (V?.[Symbol.asyncIterator]) {\n return V\n }\n\n return webidl.converters.XMLHttpRequestBodyInit(V)\n}\n\nwebidl.converters.ResponseInit = webidl.dictionaryConverter([\n {\n key: 'status',\n converter: webidl.converters['unsigned short'],\n defaultValue: 200\n },\n {\n key: 'statusText',\n converter: webidl.converters.ByteString,\n defaultValue: ''\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n }\n])\n\nmodule.exports = {\n makeNetworkError,\n makeResponse,\n makeAppropriateNetworkError,\n filterResponse,\n Response,\n cloneResponse\n}\n","'use strict'\n\nmodule.exports = {\n kUrl: Symbol('url'),\n kHeaders: Symbol('headers'),\n kSignal: Symbol('signal'),\n kState: Symbol('state'),\n kGuard: Symbol('guard'),\n kRealm: Symbol('realm')\n}\n","'use strict'\n\nconst { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants')\nconst { getGlobalOrigin } = require('./global')\nconst { performance } = require('perf_hooks')\nconst { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util')\nconst assert = require('assert')\nconst { isUint8Array } = require('util/types')\n\nlet supportedHashes = []\n\n// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable\n/** @type {import('crypto')|undefined} */\nlet crypto\n\ntry {\n crypto = require('crypto')\n const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']\n supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))\n/* c8 ignore next 3 */\n} catch {\n}\n\nfunction responseURL (response) {\n // https://fetch.spec.whatwg.org/#responses\n // A response has an associated URL. It is a pointer to the last URL\n // in response’s URL list and null if response’s URL list is empty.\n const urlList = response.urlList\n const length = urlList.length\n return length === 0 ? null : urlList[length - 1].toString()\n}\n\n// https://fetch.spec.whatwg.org/#concept-response-location-url\nfunction responseLocationURL (response, requestFragment) {\n // 1. If response’s status is not a redirect status, then return null.\n if (!redirectStatusSet.has(response.status)) {\n return null\n }\n\n // 2. Let location be the result of extracting header list values given\n // `Location` and response’s header list.\n let location = response.headersList.get('location')\n\n // 3. If location is a header value, then set location to the result of\n // parsing location with response’s URL.\n if (location !== null && isValidHeaderValue(location)) {\n location = new URL(location, responseURL(response))\n }\n\n // 4. If location is a URL whose fragment is null, then set location’s\n // fragment to requestFragment.\n if (location && !location.hash) {\n location.hash = requestFragment\n }\n\n // 5. Return location.\n return location\n}\n\n/** @returns {URL} */\nfunction requestCurrentURL (request) {\n return request.urlList[request.urlList.length - 1]\n}\n\nfunction requestBadPort (request) {\n // 1. Let url be request’s current URL.\n const url = requestCurrentURL(request)\n\n // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,\n // then return blocked.\n if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {\n return 'blocked'\n }\n\n // 3. Return allowed.\n return 'allowed'\n}\n\nfunction isErrorLike (object) {\n return object instanceof Error || (\n object?.constructor?.name === 'Error' ||\n object?.constructor?.name === 'DOMException'\n )\n}\n\n// Check whether |statusText| is a ByteString and\n// matches the Reason-Phrase token production.\n// RFC 2616: https://tools.ietf.org/html/rfc2616\n// RFC 7230: https://tools.ietf.org/html/rfc7230\n// \"reason-phrase = *( HTAB / SP / VCHAR / obs-text )\"\n// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116\nfunction isValidReasonPhrase (statusText) {\n for (let i = 0; i < statusText.length; ++i) {\n const c = statusText.charCodeAt(i)\n if (\n !(\n (\n c === 0x09 || // HTAB\n (c >= 0x20 && c <= 0x7e) || // SP / VCHAR\n (c >= 0x80 && c <= 0xff)\n ) // obs-text\n )\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://tools.ietf.org/html/rfc7230#section-3.2.6\n * @param {number} c\n */\nfunction isTokenCharCode (c) {\n switch (c) {\n case 0x22:\n case 0x28:\n case 0x29:\n case 0x2c:\n case 0x2f:\n case 0x3a:\n case 0x3b:\n case 0x3c:\n case 0x3d:\n case 0x3e:\n case 0x3f:\n case 0x40:\n case 0x5b:\n case 0x5c:\n case 0x5d:\n case 0x7b:\n case 0x7d:\n // DQUOTE and \"(),/:;<=>?@[\\]{}\"\n return false\n default:\n // VCHAR %x21-7E\n return c >= 0x21 && c <= 0x7e\n }\n}\n\n/**\n * @param {string} characters\n */\nfunction isValidHTTPToken (characters) {\n if (characters.length === 0) {\n return false\n }\n for (let i = 0; i < characters.length; ++i) {\n if (!isTokenCharCode(characters.charCodeAt(i))) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-name\n * @param {string} potentialValue\n */\nfunction isValidHeaderName (potentialValue) {\n return isValidHTTPToken(potentialValue)\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-value\n * @param {string} potentialValue\n */\nfunction isValidHeaderValue (potentialValue) {\n // - Has no leading or trailing HTTP tab or space bytes.\n // - Contains no 0x00 (NUL) or HTTP newline bytes.\n if (\n potentialValue.startsWith('\\t') ||\n potentialValue.startsWith(' ') ||\n potentialValue.endsWith('\\t') ||\n potentialValue.endsWith(' ')\n ) {\n return false\n }\n\n if (\n potentialValue.includes('\\0') ||\n potentialValue.includes('\\r') ||\n potentialValue.includes('\\n')\n ) {\n return false\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect\nfunction setRequestReferrerPolicyOnRedirect (request, actualResponse) {\n // Given a request request and a response actualResponse, this algorithm\n // updates request’s referrer policy according to the Referrer-Policy\n // header (if any) in actualResponse.\n\n // 1. Let policy be the result of executing § 8.1 Parse a referrer policy\n // from a Referrer-Policy header on actualResponse.\n\n // 8.1 Parse a referrer policy from a Referrer-Policy header\n // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.\n const { headersList } = actualResponse\n // 2. Let policy be the empty string.\n // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.\n // 4. Return policy.\n const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')\n\n // Note: As the referrer-policy can contain multiple policies\n // separated by comma, we need to loop through all of them\n // and pick the first valid one.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy\n let policy = ''\n if (policyHeader.length > 0) {\n // The right-most policy takes precedence.\n // The left-most policy is the fallback.\n for (let i = policyHeader.length; i !== 0; i--) {\n const token = policyHeader[i - 1].trim()\n if (referrerPolicyTokens.has(token)) {\n policy = token\n break\n }\n }\n }\n\n // 2. If policy is not the empty string, then set request’s referrer policy to policy.\n if (policy !== '') {\n request.referrerPolicy = policy\n }\n}\n\n// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check\nfunction crossOriginResourcePolicyCheck () {\n // TODO\n return 'allowed'\n}\n\n// https://fetch.spec.whatwg.org/#concept-cors-check\nfunction corsCheck () {\n // TODO\n return 'success'\n}\n\n// https://fetch.spec.whatwg.org/#concept-tao-check\nfunction TAOCheck () {\n // TODO\n return 'success'\n}\n\nfunction appendFetchMetadata (httpRequest) {\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header\n\n // 1. Assert: r’s url is a potentially trustworthy URL.\n // TODO\n\n // 2. Let header be a Structured Header whose value is a token.\n let header = null\n\n // 3. Set header’s value to r’s mode.\n header = httpRequest.mode\n\n // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.\n httpRequest.headersList.set('sec-fetch-mode', header)\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header\n // TODO\n}\n\n// https://fetch.spec.whatwg.org/#append-a-request-origin-header\nfunction appendRequestOriginHeader (request) {\n // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.\n let serializedOrigin = request.origin\n\n // 2. If request’s response tainting is \"cors\" or request’s mode is \"websocket\", then append (`Origin`, serializedOrigin) to request’s header list.\n if (request.responseTainting === 'cors' || request.mode === 'websocket') {\n if (serializedOrigin) {\n request.headersList.append('origin', serializedOrigin)\n }\n\n // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:\n } else if (request.method !== 'GET' && request.method !== 'HEAD') {\n // 1. Switch on request’s referrer policy:\n switch (request.referrerPolicy) {\n case 'no-referrer':\n // Set serializedOrigin to `null`.\n serializedOrigin = null\n break\n case 'no-referrer-when-downgrade':\n case 'strict-origin':\n case 'strict-origin-when-cross-origin':\n // If request’s origin is a tuple origin, its scheme is \"https\", and request’s current URL’s scheme is not \"https\", then set serializedOrigin to `null`.\n if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n case 'same-origin':\n // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.\n if (!sameOrigin(request, requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n default:\n // Do nothing.\n }\n\n if (serializedOrigin) {\n // 2. Append (`Origin`, serializedOrigin) to request’s header list.\n request.headersList.append('origin', serializedOrigin)\n }\n }\n}\n\nfunction coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {\n // TODO\n return performance.now()\n}\n\n// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info\nfunction createOpaqueTimingInfo (timingInfo) {\n return {\n startTime: timingInfo.startTime ?? 0,\n redirectStartTime: 0,\n redirectEndTime: 0,\n postRedirectStartTime: timingInfo.startTime ?? 0,\n finalServiceWorkerStartTime: 0,\n finalNetworkResponseStartTime: 0,\n finalNetworkRequestStartTime: 0,\n endTime: 0,\n encodedBodySize: 0,\n decodedBodySize: 0,\n finalConnectionTimingInfo: null\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#policy-container\nfunction makePolicyContainer () {\n // Note: the fetch spec doesn't make use of embedder policy or CSP list\n return {\n referrerPolicy: 'strict-origin-when-cross-origin'\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container\nfunction clonePolicyContainer (policyContainer) {\n return {\n referrerPolicy: policyContainer.referrerPolicy\n }\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer\nfunction determineRequestsReferrer (request) {\n // 1. Let policy be request's referrer policy.\n const policy = request.referrerPolicy\n\n // Note: policy cannot (shouldn't) be null or an empty string.\n assert(policy)\n\n // 2. Let environment be request’s client.\n\n let referrerSource = null\n\n // 3. Switch on request’s referrer:\n if (request.referrer === 'client') {\n // Note: node isn't a browser and doesn't implement document/iframes,\n // so we bypass this step and replace it with our own.\n\n const globalOrigin = getGlobalOrigin()\n\n if (!globalOrigin || globalOrigin.origin === 'null') {\n return 'no-referrer'\n }\n\n // note: we need to clone it as it's mutated\n referrerSource = new URL(globalOrigin)\n } else if (request.referrer instanceof URL) {\n // Let referrerSource be request’s referrer.\n referrerSource = request.referrer\n }\n\n // 4. Let request’s referrerURL be the result of stripping referrerSource for\n // use as a referrer.\n let referrerURL = stripURLForReferrer(referrerSource)\n\n // 5. Let referrerOrigin be the result of stripping referrerSource for use as\n // a referrer, with the origin-only flag set to true.\n const referrerOrigin = stripURLForReferrer(referrerSource, true)\n\n // 6. If the result of serializing referrerURL is a string whose length is\n // greater than 4096, set referrerURL to referrerOrigin.\n if (referrerURL.toString().length > 4096) {\n referrerURL = referrerOrigin\n }\n\n const areSameOrigin = sameOrigin(request, referrerURL)\n const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&\n !isURLPotentiallyTrustworthy(request.url)\n\n // 8. Execute the switch statements corresponding to the value of policy:\n switch (policy) {\n case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)\n case 'unsafe-url': return referrerURL\n case 'same-origin':\n return areSameOrigin ? referrerOrigin : 'no-referrer'\n case 'origin-when-cross-origin':\n return areSameOrigin ? referrerURL : referrerOrigin\n case 'strict-origin-when-cross-origin': {\n const currentURL = requestCurrentURL(request)\n\n // 1. If the origin of referrerURL and the origin of request’s current\n // URL are the same, then return referrerURL.\n if (sameOrigin(referrerURL, currentURL)) {\n return referrerURL\n }\n\n // 2. If referrerURL is a potentially trustworthy URL and request’s\n // current URL is not a potentially trustworthy URL, then return no\n // referrer.\n if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {\n return 'no-referrer'\n }\n\n // 3. Return referrerOrigin.\n return referrerOrigin\n }\n case 'strict-origin': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n case 'no-referrer-when-downgrade': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n\n default: // eslint-disable-line\n return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url\n * @param {URL} url\n * @param {boolean|undefined} originOnly\n */\nfunction stripURLForReferrer (url, originOnly) {\n // 1. Assert: url is a URL.\n assert(url instanceof URL)\n\n // 2. If url’s scheme is a local scheme, then return no referrer.\n if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {\n return 'no-referrer'\n }\n\n // 3. Set url’s username to the empty string.\n url.username = ''\n\n // 4. Set url’s password to the empty string.\n url.password = ''\n\n // 5. Set url’s fragment to null.\n url.hash = ''\n\n // 6. If the origin-only flag is true, then:\n if (originOnly) {\n // 1. Set url’s path to « the empty string ».\n url.pathname = ''\n\n // 2. Set url’s query to null.\n url.search = ''\n }\n\n // 7. Return url.\n return url\n}\n\nfunction isURLPotentiallyTrustworthy (url) {\n if (!(url instanceof URL)) {\n return false\n }\n\n // If child of about, return true\n if (url.href === 'about:blank' || url.href === 'about:srcdoc') {\n return true\n }\n\n // If scheme is data, return true\n if (url.protocol === 'data:') return true\n\n // If file, return true\n if (url.protocol === 'file:') return true\n\n return isOriginPotentiallyTrustworthy(url.origin)\n\n function isOriginPotentiallyTrustworthy (origin) {\n // If origin is explicitly null, return false\n if (origin == null || origin === 'null') return false\n\n const originAsURL = new URL(origin)\n\n // If secure, return true\n if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {\n return true\n }\n\n // If localhost or variants, return true\n if (/^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^\\[(?:0*:)*?:?0*1\\]$/.test(originAsURL.hostname) ||\n (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||\n (originAsURL.hostname.endsWith('.localhost'))) {\n return true\n }\n\n // If any other, return false\n return false\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist\n * @param {Uint8Array} bytes\n * @param {string} metadataList\n */\nfunction bytesMatch (bytes, metadataList) {\n // If node is not built with OpenSSL support, we cannot check\n // a request's integrity, so allow it by default (the spec will\n // allow requests if an invalid hash is given, as precedence).\n /* istanbul ignore if: only if node is built with --without-ssl */\n if (crypto === undefined) {\n return true\n }\n\n // 1. Let parsedMetadata be the result of parsing metadataList.\n const parsedMetadata = parseMetadata(metadataList)\n\n // 2. If parsedMetadata is no metadata, return true.\n if (parsedMetadata === 'no metadata') {\n return true\n }\n\n // 3. If response is not eligible for integrity validation, return false.\n // TODO\n\n // 4. If parsedMetadata is the empty set, return true.\n if (parsedMetadata.length === 0) {\n return true\n }\n\n // 5. Let metadata be the result of getting the strongest\n // metadata from parsedMetadata.\n const strongest = getStrongestMetadata(parsedMetadata)\n const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)\n\n // 6. For each item in metadata:\n for (const item of metadata) {\n // 1. Let algorithm be the alg component of item.\n const algorithm = item.algo\n\n // 2. Let expectedValue be the val component of item.\n const expectedValue = item.hash\n\n // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e\n // \"be liberal with padding\". This is annoying, and it's not even in the spec.\n\n // 3. Let actualValue be the result of applying algorithm to bytes.\n let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')\n\n if (actualValue[actualValue.length - 1] === '=') {\n if (actualValue[actualValue.length - 2] === '=') {\n actualValue = actualValue.slice(0, -2)\n } else {\n actualValue = actualValue.slice(0, -1)\n }\n }\n\n // 4. If actualValue is a case-sensitive match for expectedValue,\n // return true.\n if (compareBase64Mixed(actualValue, expectedValue)) {\n return true\n }\n }\n\n // 7. Return false.\n return false\n}\n\n// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options\n// https://www.w3.org/TR/CSP2/#source-list-syntax\n// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1\nconst parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\\s|$)( +[!-~]*)?)?/i\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata\n * @param {string} metadata\n */\nfunction parseMetadata (metadata) {\n // 1. Let result be the empty set.\n /** @type {{ algo: string, hash: string }[]} */\n const result = []\n\n // 2. Let empty be equal to true.\n let empty = true\n\n // 3. For each token returned by splitting metadata on spaces:\n for (const token of metadata.split(' ')) {\n // 1. Set empty to false.\n empty = false\n\n // 2. Parse token as a hash-with-options.\n const parsedToken = parseHashWithOptions.exec(token)\n\n // 3. If token does not parse, continue to the next token.\n if (\n parsedToken === null ||\n parsedToken.groups === undefined ||\n parsedToken.groups.algo === undefined\n ) {\n // Note: Chromium blocks the request at this point, but Firefox\n // gives a warning that an invalid integrity was given. The\n // correct behavior is to ignore these, and subsequently not\n // check the integrity of the resource.\n continue\n }\n\n // 4. Let algorithm be the hash-algo component of token.\n const algorithm = parsedToken.groups.algo.toLowerCase()\n\n // 5. If algorithm is a hash function recognized by the user\n // agent, add the parsed token to result.\n if (supportedHashes.includes(algorithm)) {\n result.push(parsedToken.groups)\n }\n }\n\n // 4. Return no metadata if empty is true, otherwise return result.\n if (empty === true) {\n return 'no metadata'\n }\n\n return result\n}\n\n/**\n * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList\n */\nfunction getStrongestMetadata (metadataList) {\n // Let algorithm be the algo component of the first item in metadataList.\n // Can be sha256\n let algorithm = metadataList[0].algo\n // If the algorithm is sha512, then it is the strongest\n // and we can return immediately\n if (algorithm[3] === '5') {\n return algorithm\n }\n\n for (let i = 1; i < metadataList.length; ++i) {\n const metadata = metadataList[i]\n // If the algorithm is sha512, then it is the strongest\n // and we can break the loop immediately\n if (metadata.algo[3] === '5') {\n algorithm = 'sha512'\n break\n // If the algorithm is sha384, then a potential sha256 or sha384 is ignored\n } else if (algorithm[3] === '3') {\n continue\n // algorithm is sha256, check if algorithm is sha384 and if so, set it as\n // the strongest\n } else if (metadata.algo[3] === '3') {\n algorithm = 'sha384'\n }\n }\n return algorithm\n}\n\nfunction filterMetadataListByAlgorithm (metadataList, algorithm) {\n if (metadataList.length === 1) {\n return metadataList\n }\n\n let pos = 0\n for (let i = 0; i < metadataList.length; ++i) {\n if (metadataList[i].algo === algorithm) {\n metadataList[pos++] = metadataList[i]\n }\n }\n\n metadataList.length = pos\n\n return metadataList\n}\n\n/**\n * Compares two base64 strings, allowing for base64url\n * in the second string.\n *\n* @param {string} actualValue always base64\n * @param {string} expectedValue base64 or base64url\n * @returns {boolean}\n */\nfunction compareBase64Mixed (actualValue, expectedValue) {\n if (actualValue.length !== expectedValue.length) {\n return false\n }\n for (let i = 0; i < actualValue.length; ++i) {\n if (actualValue[i] !== expectedValue[i]) {\n if (\n (actualValue[i] === '+' && expectedValue[i] === '-') ||\n (actualValue[i] === '/' && expectedValue[i] === '_')\n ) {\n continue\n }\n return false\n }\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request\nfunction tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {\n // TODO\n}\n\n/**\n * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}\n * @param {URL} A\n * @param {URL} B\n */\nfunction sameOrigin (A, B) {\n // 1. If A and B are the same opaque origin, then return true.\n if (A.origin === B.origin && A.origin === 'null') {\n return true\n }\n\n // 2. If A and B are both tuple origins and their schemes,\n // hosts, and port are identical, then return true.\n if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {\n return true\n }\n\n // 3. Return false.\n return false\n}\n\nfunction createDeferredPromise () {\n let res\n let rej\n const promise = new Promise((resolve, reject) => {\n res = resolve\n rej = reject\n })\n\n return { promise, resolve: res, reject: rej }\n}\n\nfunction isAborted (fetchParams) {\n return fetchParams.controller.state === 'aborted'\n}\n\nfunction isCancelled (fetchParams) {\n return fetchParams.controller.state === 'aborted' ||\n fetchParams.controller.state === 'terminated'\n}\n\nconst normalizeMethodRecord = {\n delete: 'DELETE',\n DELETE: 'DELETE',\n get: 'GET',\n GET: 'GET',\n head: 'HEAD',\n HEAD: 'HEAD',\n options: 'OPTIONS',\n OPTIONS: 'OPTIONS',\n post: 'POST',\n POST: 'POST',\n put: 'PUT',\n PUT: 'PUT'\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(normalizeMethodRecord, null)\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-method-normalize\n * @param {string} method\n */\nfunction normalizeMethod (method) {\n return normalizeMethodRecord[method.toLowerCase()] ?? method\n}\n\n// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string\nfunction serializeJavascriptValueToJSONString (value) {\n // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).\n const result = JSON.stringify(value)\n\n // 2. If result is undefined, then throw a TypeError.\n if (result === undefined) {\n throw new TypeError('Value is not JSON serializable')\n }\n\n // 3. Assert: result is a string.\n assert(typeof result === 'string')\n\n // 4. Return result.\n return result\n}\n\n// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object\nconst esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))\n\n/**\n * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object\n * @param {() => unknown[]} iterator\n * @param {string} name name of the instance\n * @param {'key'|'value'|'key+value'} kind\n */\nfunction makeIterator (iterator, name, kind) {\n const object = {\n index: 0,\n kind,\n target: iterator\n }\n\n const i = {\n next () {\n // 1. Let interface be the interface for which the iterator prototype object exists.\n\n // 2. Let thisValue be the this value.\n\n // 3. Let object be ? ToObject(thisValue).\n\n // 4. If object is a platform object, then perform a security\n // check, passing:\n\n // 5. If object is not a default iterator object for interface,\n // then throw a TypeError.\n if (Object.getPrototypeOf(this) !== i) {\n throw new TypeError(\n `'next' called on an object that does not implement interface ${name} Iterator.`\n )\n }\n\n // 6. Let index be object’s index.\n // 7. Let kind be object’s kind.\n // 8. Let values be object’s target's value pairs to iterate over.\n const { index, kind, target } = object\n const values = target()\n\n // 9. Let len be the length of values.\n const len = values.length\n\n // 10. If index is greater than or equal to len, then return\n // CreateIterResultObject(undefined, true).\n if (index >= len) {\n return { value: undefined, done: true }\n }\n\n // 11. Let pair be the entry in values at index index.\n const pair = values[index]\n\n // 12. Set object’s index to index + 1.\n object.index = index + 1\n\n // 13. Return the iterator result for pair and kind.\n return iteratorResult(pair, kind)\n },\n // The class string of an iterator prototype object for a given interface is the\n // result of concatenating the identifier of the interface and the string \" Iterator\".\n [Symbol.toStringTag]: `${name} Iterator`\n }\n\n // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.\n Object.setPrototypeOf(i, esIteratorPrototype)\n // esIteratorPrototype needs to be the prototype of i\n // which is the prototype of an empty object. Yes, it's confusing.\n return Object.setPrototypeOf({}, i)\n}\n\n// https://webidl.spec.whatwg.org/#iterator-result\nfunction iteratorResult (pair, kind) {\n let result\n\n // 1. Let result be a value determined by the value of kind:\n switch (kind) {\n case 'key': {\n // 1. Let idlKey be pair’s key.\n // 2. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 3. result is key.\n result = pair[0]\n break\n }\n case 'value': {\n // 1. Let idlValue be pair’s value.\n // 2. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 3. result is value.\n result = pair[1]\n break\n }\n case 'key+value': {\n // 1. Let idlKey be pair’s key.\n // 2. Let idlValue be pair’s value.\n // 3. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 4. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 5. Let array be ! ArrayCreate(2).\n // 6. Call ! CreateDataProperty(array, \"0\", key).\n // 7. Call ! CreateDataProperty(array, \"1\", value).\n // 8. result is array.\n result = pair\n break\n }\n }\n\n // 2. Return CreateIterResultObject(result, false).\n return { value: result, done: false }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#body-fully-read\n */\nasync function fullyReadBody (body, processBody, processBodyError) {\n // 1. If taskDestination is null, then set taskDestination to\n // the result of starting a new parallel queue.\n\n // 2. Let successSteps given a byte sequence bytes be to queue a\n // fetch task to run processBody given bytes, with taskDestination.\n const successSteps = processBody\n\n // 3. Let errorSteps be to queue a fetch task to run processBodyError,\n // with taskDestination.\n const errorSteps = processBodyError\n\n // 4. Let reader be the result of getting a reader for body’s stream.\n // If that threw an exception, then run errorSteps with that\n // exception and return.\n let reader\n\n try {\n reader = body.stream.getReader()\n } catch (e) {\n errorSteps(e)\n return\n }\n\n // 5. Read all bytes from reader, given successSteps and errorSteps.\n try {\n const result = await readAllBytes(reader)\n successSteps(result)\n } catch (e) {\n errorSteps(e)\n }\n}\n\n/** @type {ReadableStream} */\nlet ReadableStream = globalThis.ReadableStream\n\nfunction isReadableStreamLike (stream) {\n if (!ReadableStream) {\n ReadableStream = require('stream/web').ReadableStream\n }\n\n return stream instanceof ReadableStream || (\n stream[Symbol.toStringTag] === 'ReadableStream' &&\n typeof stream.tee === 'function'\n )\n}\n\nconst MAXIMUM_ARGUMENT_LENGTH = 65535\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-decode\n * @param {number[]|Uint8Array} input\n */\nfunction isomorphicDecode (input) {\n // 1. To isomorphic decode a byte sequence input, return a string whose code point\n // length is equal to input’s length and whose code points have the same values\n // as the values of input’s bytes, in the same order.\n\n if (input.length < MAXIMUM_ARGUMENT_LENGTH) {\n return String.fromCharCode(...input)\n }\n\n return input.reduce((previous, current) => previous + String.fromCharCode(current), '')\n}\n\n/**\n * @param {ReadableStreamController} controller\n */\nfunction readableStreamClose (controller) {\n try {\n controller.close()\n } catch (err) {\n // TODO: add comment explaining why this error occurs.\n if (!err.message.includes('Controller is already closed')) {\n throw err\n }\n }\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-encode\n * @param {string} input\n */\nfunction isomorphicEncode (input) {\n // 1. Assert: input contains no code points greater than U+00FF.\n for (let i = 0; i < input.length; i++) {\n assert(input.charCodeAt(i) <= 0xFF)\n }\n\n // 2. Return a byte sequence whose length is equal to input’s code\n // point length and whose bytes have the same values as the\n // values of input’s code points, in the same order\n return input\n}\n\n/**\n * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes\n * @see https://streams.spec.whatwg.org/#read-loop\n * @param {ReadableStreamDefaultReader} reader\n */\nasync function readAllBytes (reader) {\n const bytes = []\n let byteLength = 0\n\n while (true) {\n const { done, value: chunk } = await reader.read()\n\n if (done) {\n // 1. Call successSteps with bytes.\n return Buffer.concat(bytes, byteLength)\n }\n\n // 1. If chunk is not a Uint8Array object, call failureSteps\n // with a TypeError and abort these steps.\n if (!isUint8Array(chunk)) {\n throw new TypeError('Received non-Uint8Array chunk')\n }\n\n // 2. Append the bytes represented by chunk to bytes.\n bytes.push(chunk)\n byteLength += chunk.length\n\n // 3. Read-loop given reader, bytes, successSteps, and failureSteps.\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#is-local\n * @param {URL} url\n */\nfunction urlIsLocal (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'\n}\n\n/**\n * @param {string|URL} url\n */\nfunction urlHasHttpsScheme (url) {\n if (typeof url === 'string') {\n return url.startsWith('https:')\n }\n\n return url.protocol === 'https:'\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-scheme\n * @param {URL} url\n */\nfunction urlIsHttpHttpsScheme (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'http:' || protocol === 'https:'\n}\n\n/**\n * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.\n */\nconst hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))\n\nmodule.exports = {\n isAborted,\n isCancelled,\n createDeferredPromise,\n ReadableStreamFrom,\n toUSVString,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n coarsenedSharedCurrentTime,\n determineRequestsReferrer,\n makePolicyContainer,\n clonePolicyContainer,\n appendFetchMetadata,\n appendRequestOriginHeader,\n TAOCheck,\n corsCheck,\n crossOriginResourcePolicyCheck,\n createOpaqueTimingInfo,\n setRequestReferrerPolicyOnRedirect,\n isValidHTTPToken,\n requestBadPort,\n requestCurrentURL,\n responseURL,\n responseLocationURL,\n isBlobLike,\n isURLPotentiallyTrustworthy,\n isValidReasonPhrase,\n sameOrigin,\n normalizeMethod,\n serializeJavascriptValueToJSONString,\n makeIterator,\n isValidHeaderName,\n isValidHeaderValue,\n hasOwn,\n isErrorLike,\n fullyReadBody,\n bytesMatch,\n isReadableStreamLike,\n readableStreamClose,\n isomorphicEncode,\n isomorphicDecode,\n urlIsLocal,\n urlHasHttpsScheme,\n urlIsHttpHttpsScheme,\n readAllBytes,\n normalizeMethodRecord,\n parseMetadata\n}\n","'use strict'\n\nconst { types } = require('util')\nconst { hasOwn, toUSVString } = require('./util')\n\n/** @type {import('../../types/webidl').Webidl} */\nconst webidl = {}\nwebidl.converters = {}\nwebidl.util = {}\nwebidl.errors = {}\n\nwebidl.errors.exception = function (message) {\n return new TypeError(`${message.header}: ${message.message}`)\n}\n\nwebidl.errors.conversionFailed = function (context) {\n const plural = context.types.length === 1 ? '' : ' one of'\n const message =\n `${context.argument} could not be converted to` +\n `${plural}: ${context.types.join(', ')}.`\n\n return webidl.errors.exception({\n header: context.prefix,\n message\n })\n}\n\nwebidl.errors.invalidArgument = function (context) {\n return webidl.errors.exception({\n header: context.prefix,\n message: `\"${context.value}\" is an invalid ${context.type}.`\n })\n}\n\n// https://webidl.spec.whatwg.org/#implements\nwebidl.brandCheck = function (V, I, opts = undefined) {\n if (opts?.strict !== false && !(V instanceof I)) {\n throw new TypeError('Illegal invocation')\n } else {\n return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]\n }\n}\n\nwebidl.argumentLengthCheck = function ({ length }, min, ctx) {\n if (length < min) {\n throw webidl.errors.exception({\n message: `${min} argument${min !== 1 ? 's' : ''} required, ` +\n `but${length ? ' only' : ''} ${length} found.`,\n ...ctx\n })\n }\n}\n\nwebidl.illegalConstructor = function () {\n throw webidl.errors.exception({\n header: 'TypeError',\n message: 'Illegal constructor'\n })\n}\n\n// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values\nwebidl.util.Type = function (V) {\n switch (typeof V) {\n case 'undefined': return 'Undefined'\n case 'boolean': return 'Boolean'\n case 'string': return 'String'\n case 'symbol': return 'Symbol'\n case 'number': return 'Number'\n case 'bigint': return 'BigInt'\n case 'function':\n case 'object': {\n if (V === null) {\n return 'Null'\n }\n\n return 'Object'\n }\n }\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint\nwebidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {\n let upperBound\n let lowerBound\n\n // 1. If bitLength is 64, then:\n if (bitLength === 64) {\n // 1. Let upperBound be 2^53 − 1.\n upperBound = Math.pow(2, 53) - 1\n\n // 2. If signedness is \"unsigned\", then let lowerBound be 0.\n if (signedness === 'unsigned') {\n lowerBound = 0\n } else {\n // 3. Otherwise let lowerBound be −2^53 + 1.\n lowerBound = Math.pow(-2, 53) + 1\n }\n } else if (signedness === 'unsigned') {\n // 2. Otherwise, if signedness is \"unsigned\", then:\n\n // 1. Let lowerBound be 0.\n lowerBound = 0\n\n // 2. Let upperBound be 2^bitLength − 1.\n upperBound = Math.pow(2, bitLength) - 1\n } else {\n // 3. Otherwise:\n\n // 1. Let lowerBound be -2^bitLength − 1.\n lowerBound = Math.pow(-2, bitLength) - 1\n\n // 2. Let upperBound be 2^bitLength − 1 − 1.\n upperBound = Math.pow(2, bitLength - 1) - 1\n }\n\n // 4. Let x be ? ToNumber(V).\n let x = Number(V)\n\n // 5. If x is −0, then set x to +0.\n if (x === 0) {\n x = 0\n }\n\n // 6. If the conversion is to an IDL type associated\n // with the [EnforceRange] extended attribute, then:\n if (opts.enforceRange === true) {\n // 1. If x is NaN, +∞, or −∞, then throw a TypeError.\n if (\n Number.isNaN(x) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Could not convert ${V} to an integer.`\n })\n }\n\n // 2. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 3. If x < lowerBound or x > upperBound, then\n // throw a TypeError.\n if (x < lowerBound || x > upperBound) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`\n })\n }\n\n // 4. Return x.\n return x\n }\n\n // 7. If x is not NaN and the conversion is to an IDL\n // type associated with the [Clamp] extended\n // attribute, then:\n if (!Number.isNaN(x) && opts.clamp === true) {\n // 1. Set x to min(max(x, lowerBound), upperBound).\n x = Math.min(Math.max(x, lowerBound), upperBound)\n\n // 2. Round x to the nearest integer, choosing the\n // even integer if it lies halfway between two,\n // and choosing +0 rather than −0.\n if (Math.floor(x) % 2 === 0) {\n x = Math.floor(x)\n } else {\n x = Math.ceil(x)\n }\n\n // 3. Return x.\n return x\n }\n\n // 8. If x is NaN, +0, +∞, or −∞, then return +0.\n if (\n Number.isNaN(x) ||\n (x === 0 && Object.is(0, x)) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n return 0\n }\n\n // 9. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 10. Set x to x modulo 2^bitLength.\n x = x % Math.pow(2, bitLength)\n\n // 11. If signedness is \"signed\" and x ≥ 2^bitLength − 1,\n // then return x − 2^bitLength.\n if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {\n return x - Math.pow(2, bitLength)\n }\n\n // 12. Otherwise, return x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart\nwebidl.util.IntegerPart = function (n) {\n // 1. Let r be floor(abs(n)).\n const r = Math.floor(Math.abs(n))\n\n // 2. If n < 0, then return -1 × r.\n if (n < 0) {\n return -1 * r\n }\n\n // 3. Otherwise, return r.\n return r\n}\n\n// https://webidl.spec.whatwg.org/#es-sequence\nwebidl.sequenceConverter = function (converter) {\n return (V) => {\n // 1. If Type(V) is not Object, throw a TypeError.\n if (webidl.util.Type(V) !== 'Object') {\n throw webidl.errors.exception({\n header: 'Sequence',\n message: `Value of type ${webidl.util.Type(V)} is not an Object.`\n })\n }\n\n // 2. Let method be ? GetMethod(V, @@iterator).\n /** @type {Generator} */\n const method = V?.[Symbol.iterator]?.()\n const seq = []\n\n // 3. If method is undefined, throw a TypeError.\n if (\n method === undefined ||\n typeof method.next !== 'function'\n ) {\n throw webidl.errors.exception({\n header: 'Sequence',\n message: 'Object is not an iterator.'\n })\n }\n\n // https://webidl.spec.whatwg.org/#create-sequence-from-iterable\n while (true) {\n const { done, value } = method.next()\n\n if (done) {\n break\n }\n\n seq.push(converter(value))\n }\n\n return seq\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-to-record\nwebidl.recordConverter = function (keyConverter, valueConverter) {\n return (O) => {\n // 1. If Type(O) is not Object, throw a TypeError.\n if (webidl.util.Type(O) !== 'Object') {\n throw webidl.errors.exception({\n header: 'Record',\n message: `Value of type ${webidl.util.Type(O)} is not an Object.`\n })\n }\n\n // 2. Let result be a new empty instance of record.\n const result = {}\n\n if (!types.isProxy(O)) {\n // Object.keys only returns enumerable properties\n const keys = Object.keys(O)\n\n for (const key of keys) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key])\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n\n // 5. Return result.\n return result\n }\n\n // 3. Let keys be ? O.[[OwnPropertyKeys]]().\n const keys = Reflect.ownKeys(O)\n\n // 4. For each key of keys.\n for (const key of keys) {\n // 1. Let desc be ? O.[[GetOwnProperty]](key).\n const desc = Reflect.getOwnPropertyDescriptor(O, key)\n\n // 2. If desc is not undefined and desc.[[Enumerable]] is true:\n if (desc?.enumerable) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key])\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n }\n\n // 5. Return result.\n return result\n }\n}\n\nwebidl.interfaceConverter = function (i) {\n return (V, opts = {}) => {\n if (opts.strict !== false && !(V instanceof i)) {\n throw webidl.errors.exception({\n header: i.name,\n message: `Expected ${V} to be an instance of ${i.name}.`\n })\n }\n\n return V\n }\n}\n\nwebidl.dictionaryConverter = function (converters) {\n return (dictionary) => {\n const type = webidl.util.Type(dictionary)\n const dict = {}\n\n if (type === 'Null' || type === 'Undefined') {\n return dict\n } else if (type !== 'Object') {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`\n })\n }\n\n for (const options of converters) {\n const { key, defaultValue, required, converter } = options\n\n if (required === true) {\n if (!hasOwn(dictionary, key)) {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `Missing required key \"${key}\".`\n })\n }\n }\n\n let value = dictionary[key]\n const hasDefault = hasOwn(options, 'defaultValue')\n\n // Only use defaultValue if value is undefined and\n // a defaultValue options was provided.\n if (hasDefault && value !== null) {\n value = value ?? defaultValue\n }\n\n // A key can be optional and have no default value.\n // When this happens, do not perform a conversion,\n // and do not assign the key a value.\n if (required || hasDefault || value !== undefined) {\n value = converter(value)\n\n if (\n options.allowedValues &&\n !options.allowedValues.includes(value)\n ) {\n throw webidl.errors.exception({\n header: 'Dictionary',\n message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`\n })\n }\n\n dict[key] = value\n }\n }\n\n return dict\n }\n}\n\nwebidl.nullableConverter = function (converter) {\n return (V) => {\n if (V === null) {\n return V\n }\n\n return converter(V)\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-DOMString\nwebidl.converters.DOMString = function (V, opts = {}) {\n // 1. If V is null and the conversion is to an IDL type\n // associated with the [LegacyNullToEmptyString]\n // extended attribute, then return the DOMString value\n // that represents the empty string.\n if (V === null && opts.legacyNullToEmptyString) {\n return ''\n }\n\n // 2. Let x be ? ToString(V).\n if (typeof V === 'symbol') {\n throw new TypeError('Could not convert argument of type symbol to string.')\n }\n\n // 3. Return the IDL DOMString value that represents the\n // same sequence of code units as the one the\n // ECMAScript String value x represents.\n return String(V)\n}\n\n// https://webidl.spec.whatwg.org/#es-ByteString\nwebidl.converters.ByteString = function (V) {\n // 1. Let x be ? ToString(V).\n // Note: DOMString converter perform ? ToString(V)\n const x = webidl.converters.DOMString(V)\n\n // 2. If the value of any element of x is greater than\n // 255, then throw a TypeError.\n for (let index = 0; index < x.length; index++) {\n if (x.charCodeAt(index) > 255) {\n throw new TypeError(\n 'Cannot convert argument to a ByteString because the character at ' +\n `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`\n )\n }\n }\n\n // 3. Return an IDL ByteString value whose length is the\n // length of x, and where the value of each element is\n // the value of the corresponding element of x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-USVString\nwebidl.converters.USVString = toUSVString\n\n// https://webidl.spec.whatwg.org/#es-boolean\nwebidl.converters.boolean = function (V) {\n // 1. Let x be the result of computing ToBoolean(V).\n const x = Boolean(V)\n\n // 2. Return the IDL boolean value that is the one that represents\n // the same truth value as the ECMAScript Boolean value x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-any\nwebidl.converters.any = function (V) {\n return V\n}\n\n// https://webidl.spec.whatwg.org/#es-long-long\nwebidl.converters['long long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 64, \"signed\").\n const x = webidl.util.ConvertToInt(V, 64, 'signed')\n\n // 2. Return the IDL long long value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long-long\nwebidl.converters['unsigned long long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 64, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 64, 'unsigned')\n\n // 2. Return the IDL unsigned long long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long\nwebidl.converters['unsigned long'] = function (V) {\n // 1. Let x be ? ConvertToInt(V, 32, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 32, 'unsigned')\n\n // 2. Return the IDL unsigned long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-short\nwebidl.converters['unsigned short'] = function (V, opts) {\n // 1. Let x be ? ConvertToInt(V, 16, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)\n\n // 2. Return the IDL unsigned short value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#idl-ArrayBuffer\nwebidl.converters.ArrayBuffer = function (V, opts = {}) {\n // 1. If Type(V) is not Object, or V does not have an\n // [[ArrayBufferData]] internal slot, then throw a\n // TypeError.\n // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances\n // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isAnyArrayBuffer(V)\n ) {\n throw webidl.errors.conversionFailed({\n prefix: `${V}`,\n argument: `${V}`,\n types: ['ArrayBuffer']\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V) is true, then throw a\n // TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V) is true, then throw a\n // TypeError.\n // Note: resizable ArrayBuffers are currently a proposal.\n\n // 4. Return the IDL ArrayBuffer value that is a\n // reference to the same object as V.\n return V\n}\n\nwebidl.converters.TypedArray = function (V, T, opts = {}) {\n // 1. Let T be the IDL type V is being converted to.\n\n // 2. If Type(V) is not Object, or V does not have a\n // [[TypedArrayName]] internal slot with a value\n // equal to T’s name, then throw a TypeError.\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isTypedArray(V) ||\n V.constructor.name !== T.name\n ) {\n throw webidl.errors.conversionFailed({\n prefix: `${T.name}`,\n argument: `${V}`,\n types: [T.name]\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 4. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n // Note: resizable array buffers are currently a proposal\n\n // 5. Return the IDL value of type T that is a reference\n // to the same object as V.\n return V\n}\n\nwebidl.converters.DataView = function (V, opts = {}) {\n // 1. If Type(V) is not Object, or V does not have a\n // [[DataView]] internal slot, then throw a TypeError.\n if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {\n throw webidl.errors.exception({\n header: 'DataView',\n message: 'Object is not a DataView.'\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,\n // then throw a TypeError.\n if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n // Note: resizable ArrayBuffers are currently a proposal\n\n // 4. Return the IDL DataView value that is a reference\n // to the same object as V.\n return V\n}\n\n// https://webidl.spec.whatwg.org/#BufferSource\nwebidl.converters.BufferSource = function (V, opts = {}) {\n if (types.isAnyArrayBuffer(V)) {\n return webidl.converters.ArrayBuffer(V, opts)\n }\n\n if (types.isTypedArray(V)) {\n return webidl.converters.TypedArray(V, V.constructor)\n }\n\n if (types.isDataView(V)) {\n return webidl.converters.DataView(V, opts)\n }\n\n throw new TypeError(`Could not convert ${V} to a BufferSource.`)\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.ByteString\n)\n\nwebidl.converters['sequence>'] = webidl.sequenceConverter(\n webidl.converters['sequence']\n)\n\nwebidl.converters['record'] = webidl.recordConverter(\n webidl.converters.ByteString,\n webidl.converters.ByteString\n)\n\nmodule.exports = {\n webidl\n}\n","'use strict'\n\n/**\n * @see https://encoding.spec.whatwg.org/#concept-encoding-get\n * @param {string|undefined} label\n */\nfunction getEncoding (label) {\n if (!label) {\n return 'failure'\n }\n\n // 1. Remove any leading and trailing ASCII whitespace from label.\n // 2. If label is an ASCII case-insensitive match for any of the\n // labels listed in the table below, then return the\n // corresponding encoding; otherwise return failure.\n switch (label.trim().toLowerCase()) {\n case 'unicode-1-1-utf-8':\n case 'unicode11utf8':\n case 'unicode20utf8':\n case 'utf-8':\n case 'utf8':\n case 'x-unicode20utf8':\n return 'UTF-8'\n case '866':\n case 'cp866':\n case 'csibm866':\n case 'ibm866':\n return 'IBM866'\n case 'csisolatin2':\n case 'iso-8859-2':\n case 'iso-ir-101':\n case 'iso8859-2':\n case 'iso88592':\n case 'iso_8859-2':\n case 'iso_8859-2:1987':\n case 'l2':\n case 'latin2':\n return 'ISO-8859-2'\n case 'csisolatin3':\n case 'iso-8859-3':\n case 'iso-ir-109':\n case 'iso8859-3':\n case 'iso88593':\n case 'iso_8859-3':\n case 'iso_8859-3:1988':\n case 'l3':\n case 'latin3':\n return 'ISO-8859-3'\n case 'csisolatin4':\n case 'iso-8859-4':\n case 'iso-ir-110':\n case 'iso8859-4':\n case 'iso88594':\n case 'iso_8859-4':\n case 'iso_8859-4:1988':\n case 'l4':\n case 'latin4':\n return 'ISO-8859-4'\n case 'csisolatincyrillic':\n case 'cyrillic':\n case 'iso-8859-5':\n case 'iso-ir-144':\n case 'iso8859-5':\n case 'iso88595':\n case 'iso_8859-5':\n case 'iso_8859-5:1988':\n return 'ISO-8859-5'\n case 'arabic':\n case 'asmo-708':\n case 'csiso88596e':\n case 'csiso88596i':\n case 'csisolatinarabic':\n case 'ecma-114':\n case 'iso-8859-6':\n case 'iso-8859-6-e':\n case 'iso-8859-6-i':\n case 'iso-ir-127':\n case 'iso8859-6':\n case 'iso88596':\n case 'iso_8859-6':\n case 'iso_8859-6:1987':\n return 'ISO-8859-6'\n case 'csisolatingreek':\n case 'ecma-118':\n case 'elot_928':\n case 'greek':\n case 'greek8':\n case 'iso-8859-7':\n case 'iso-ir-126':\n case 'iso8859-7':\n case 'iso88597':\n case 'iso_8859-7':\n case 'iso_8859-7:1987':\n case 'sun_eu_greek':\n return 'ISO-8859-7'\n case 'csiso88598e':\n case 'csisolatinhebrew':\n case 'hebrew':\n case 'iso-8859-8':\n case 'iso-8859-8-e':\n case 'iso-ir-138':\n case 'iso8859-8':\n case 'iso88598':\n case 'iso_8859-8':\n case 'iso_8859-8:1988':\n case 'visual':\n return 'ISO-8859-8'\n case 'csiso88598i':\n case 'iso-8859-8-i':\n case 'logical':\n return 'ISO-8859-8-I'\n case 'csisolatin6':\n case 'iso-8859-10':\n case 'iso-ir-157':\n case 'iso8859-10':\n case 'iso885910':\n case 'l6':\n case 'latin6':\n return 'ISO-8859-10'\n case 'iso-8859-13':\n case 'iso8859-13':\n case 'iso885913':\n return 'ISO-8859-13'\n case 'iso-8859-14':\n case 'iso8859-14':\n case 'iso885914':\n return 'ISO-8859-14'\n case 'csisolatin9':\n case 'iso-8859-15':\n case 'iso8859-15':\n case 'iso885915':\n case 'iso_8859-15':\n case 'l9':\n return 'ISO-8859-15'\n case 'iso-8859-16':\n return 'ISO-8859-16'\n case 'cskoi8r':\n case 'koi':\n case 'koi8':\n case 'koi8-r':\n case 'koi8_r':\n return 'KOI8-R'\n case 'koi8-ru':\n case 'koi8-u':\n return 'KOI8-U'\n case 'csmacintosh':\n case 'mac':\n case 'macintosh':\n case 'x-mac-roman':\n return 'macintosh'\n case 'iso-8859-11':\n case 'iso8859-11':\n case 'iso885911':\n case 'tis-620':\n case 'windows-874':\n return 'windows-874'\n case 'cp1250':\n case 'windows-1250':\n case 'x-cp1250':\n return 'windows-1250'\n case 'cp1251':\n case 'windows-1251':\n case 'x-cp1251':\n return 'windows-1251'\n case 'ansi_x3.4-1968':\n case 'ascii':\n case 'cp1252':\n case 'cp819':\n case 'csisolatin1':\n case 'ibm819':\n case 'iso-8859-1':\n case 'iso-ir-100':\n case 'iso8859-1':\n case 'iso88591':\n case 'iso_8859-1':\n case 'iso_8859-1:1987':\n case 'l1':\n case 'latin1':\n case 'us-ascii':\n case 'windows-1252':\n case 'x-cp1252':\n return 'windows-1252'\n case 'cp1253':\n case 'windows-1253':\n case 'x-cp1253':\n return 'windows-1253'\n case 'cp1254':\n case 'csisolatin5':\n case 'iso-8859-9':\n case 'iso-ir-148':\n case 'iso8859-9':\n case 'iso88599':\n case 'iso_8859-9':\n case 'iso_8859-9:1989':\n case 'l5':\n case 'latin5':\n case 'windows-1254':\n case 'x-cp1254':\n return 'windows-1254'\n case 'cp1255':\n case 'windows-1255':\n case 'x-cp1255':\n return 'windows-1255'\n case 'cp1256':\n case 'windows-1256':\n case 'x-cp1256':\n return 'windows-1256'\n case 'cp1257':\n case 'windows-1257':\n case 'x-cp1257':\n return 'windows-1257'\n case 'cp1258':\n case 'windows-1258':\n case 'x-cp1258':\n return 'windows-1258'\n case 'x-mac-cyrillic':\n case 'x-mac-ukrainian':\n return 'x-mac-cyrillic'\n case 'chinese':\n case 'csgb2312':\n case 'csiso58gb231280':\n case 'gb2312':\n case 'gb_2312':\n case 'gb_2312-80':\n case 'gbk':\n case 'iso-ir-58':\n case 'x-gbk':\n return 'GBK'\n case 'gb18030':\n return 'gb18030'\n case 'big5':\n case 'big5-hkscs':\n case 'cn-big5':\n case 'csbig5':\n case 'x-x-big5':\n return 'Big5'\n case 'cseucpkdfmtjapanese':\n case 'euc-jp':\n case 'x-euc-jp':\n return 'EUC-JP'\n case 'csiso2022jp':\n case 'iso-2022-jp':\n return 'ISO-2022-JP'\n case 'csshiftjis':\n case 'ms932':\n case 'ms_kanji':\n case 'shift-jis':\n case 'shift_jis':\n case 'sjis':\n case 'windows-31j':\n case 'x-sjis':\n return 'Shift_JIS'\n case 'cseuckr':\n case 'csksc56011987':\n case 'euc-kr':\n case 'iso-ir-149':\n case 'korean':\n case 'ks_c_5601-1987':\n case 'ks_c_5601-1989':\n case 'ksc5601':\n case 'ksc_5601':\n case 'windows-949':\n return 'EUC-KR'\n case 'csiso2022kr':\n case 'hz-gb-2312':\n case 'iso-2022-cn':\n case 'iso-2022-cn-ext':\n case 'iso-2022-kr':\n case 'replacement':\n return 'replacement'\n case 'unicodefffe':\n case 'utf-16be':\n return 'UTF-16BE'\n case 'csunicode':\n case 'iso-10646-ucs-2':\n case 'ucs-2':\n case 'unicode':\n case 'unicodefeff':\n case 'utf-16':\n case 'utf-16le':\n return 'UTF-16LE'\n case 'x-user-defined':\n return 'x-user-defined'\n default: return 'failure'\n }\n}\n\nmodule.exports = {\n getEncoding\n}\n","'use strict'\n\nconst {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n} = require('./util')\nconst {\n kState,\n kError,\n kResult,\n kEvents,\n kAborted\n} = require('./symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\n\nclass FileReader extends EventTarget {\n constructor () {\n super()\n\n this[kState] = 'empty'\n this[kResult] = null\n this[kError] = null\n this[kEvents] = {\n loadend: null,\n error: null,\n abort: null,\n load: null,\n progress: null,\n loadstart: null\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer\n * @param {import('buffer').Blob} blob\n */\n readAsArrayBuffer (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsArrayBuffer(blob) method, when invoked,\n // must initiate a read operation for blob with ArrayBuffer.\n readOperation(this, blob, 'ArrayBuffer')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsBinaryString\n * @param {import('buffer').Blob} blob\n */\n readAsBinaryString (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsBinaryString(blob) method, when invoked,\n // must initiate a read operation for blob with BinaryString.\n readOperation(this, blob, 'BinaryString')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsDataText\n * @param {import('buffer').Blob} blob\n * @param {string?} encoding\n */\n readAsText (blob, encoding = undefined) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n if (encoding !== undefined) {\n encoding = webidl.converters.DOMString(encoding)\n }\n\n // The readAsText(blob, encoding) method, when invoked,\n // must initiate a read operation for blob with Text and encoding.\n readOperation(this, blob, 'Text', encoding)\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL\n * @param {import('buffer').Blob} blob\n */\n readAsDataURL (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsDataURL(blob) method, when invoked, must\n // initiate a read operation for blob with DataURL.\n readOperation(this, blob, 'DataURL')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-abort\n */\n abort () {\n // 1. If this's state is \"empty\" or if this's state is\n // \"done\" set this's result to null and terminate\n // this algorithm.\n if (this[kState] === 'empty' || this[kState] === 'done') {\n this[kResult] = null\n return\n }\n\n // 2. If this's state is \"loading\" set this's state to\n // \"done\" and set this's result to null.\n if (this[kState] === 'loading') {\n this[kState] = 'done'\n this[kResult] = null\n }\n\n // 3. If there are any tasks from this on the file reading\n // task source in an affiliated task queue, then remove\n // those tasks from that task queue.\n this[kAborted] = true\n\n // 4. Terminate the algorithm for the read method being processed.\n // TODO\n\n // 5. Fire a progress event called abort at this.\n fireAProgressEvent('abort', this)\n\n // 6. If this's state is not \"loading\", fire a progress\n // event called loadend at this.\n if (this[kState] !== 'loading') {\n fireAProgressEvent('loadend', this)\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate\n */\n get readyState () {\n webidl.brandCheck(this, FileReader)\n\n switch (this[kState]) {\n case 'empty': return this.EMPTY\n case 'loading': return this.LOADING\n case 'done': return this.DONE\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-result\n */\n get result () {\n webidl.brandCheck(this, FileReader)\n\n // The result attribute’s getter, when invoked, must return\n // this's result.\n return this[kResult]\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-error\n */\n get error () {\n webidl.brandCheck(this, FileReader)\n\n // The error attribute’s getter, when invoked, must return\n // this's error.\n return this[kError]\n }\n\n get onloadend () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadend\n }\n\n set onloadend (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadend) {\n this.removeEventListener('loadend', this[kEvents].loadend)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadend = fn\n this.addEventListener('loadend', fn)\n } else {\n this[kEvents].loadend = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].error) {\n this.removeEventListener('error', this[kEvents].error)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].error = fn\n this.addEventListener('error', fn)\n } else {\n this[kEvents].error = null\n }\n }\n\n get onloadstart () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadstart\n }\n\n set onloadstart (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadstart) {\n this.removeEventListener('loadstart', this[kEvents].loadstart)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadstart = fn\n this.addEventListener('loadstart', fn)\n } else {\n this[kEvents].loadstart = null\n }\n }\n\n get onprogress () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].progress\n }\n\n set onprogress (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].progress) {\n this.removeEventListener('progress', this[kEvents].progress)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].progress = fn\n this.addEventListener('progress', fn)\n } else {\n this[kEvents].progress = null\n }\n }\n\n get onload () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].load\n }\n\n set onload (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].load) {\n this.removeEventListener('load', this[kEvents].load)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].load = fn\n this.addEventListener('load', fn)\n } else {\n this[kEvents].load = null\n }\n }\n\n get onabort () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].abort\n }\n\n set onabort (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].abort) {\n this.removeEventListener('abort', this[kEvents].abort)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].abort = fn\n this.addEventListener('abort', fn)\n } else {\n this[kEvents].abort = null\n }\n }\n}\n\n// https://w3c.github.io/FileAPI/#dom-filereader-empty\nFileReader.EMPTY = FileReader.prototype.EMPTY = 0\n// https://w3c.github.io/FileAPI/#dom-filereader-loading\nFileReader.LOADING = FileReader.prototype.LOADING = 1\n// https://w3c.github.io/FileAPI/#dom-filereader-done\nFileReader.DONE = FileReader.prototype.DONE = 2\n\nObject.defineProperties(FileReader.prototype, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors,\n readAsArrayBuffer: kEnumerableProperty,\n readAsBinaryString: kEnumerableProperty,\n readAsText: kEnumerableProperty,\n readAsDataURL: kEnumerableProperty,\n abort: kEnumerableProperty,\n readyState: kEnumerableProperty,\n result: kEnumerableProperty,\n error: kEnumerableProperty,\n onloadstart: kEnumerableProperty,\n onprogress: kEnumerableProperty,\n onload: kEnumerableProperty,\n onabort: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onloadend: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'FileReader',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(FileReader, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors\n})\n\nmodule.exports = {\n FileReader\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\n\nconst kState = Symbol('ProgressEvent state')\n\n/**\n * @see https://xhr.spec.whatwg.org/#progressevent\n */\nclass ProgressEvent extends Event {\n constructor (type, eventInitDict = {}) {\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})\n\n super(type, eventInitDict)\n\n this[kState] = {\n lengthComputable: eventInitDict.lengthComputable,\n loaded: eventInitDict.loaded,\n total: eventInitDict.total\n }\n }\n\n get lengthComputable () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].lengthComputable\n }\n\n get loaded () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].loaded\n }\n\n get total () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].total\n }\n}\n\nwebidl.converters.ProgressEventInit = webidl.dictionaryConverter([\n {\n key: 'lengthComputable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'loaded',\n converter: webidl.converters['unsigned long long'],\n defaultValue: 0\n },\n {\n key: 'total',\n converter: webidl.converters['unsigned long long'],\n defaultValue: 0\n },\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n])\n\nmodule.exports = {\n ProgressEvent\n}\n","'use strict'\n\nmodule.exports = {\n kState: Symbol('FileReader state'),\n kResult: Symbol('FileReader result'),\n kError: Symbol('FileReader error'),\n kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),\n kEvents: Symbol('FileReader events'),\n kAborted: Symbol('FileReader aborted')\n}\n","'use strict'\n\nconst {\n kState,\n kError,\n kResult,\n kAborted,\n kLastProgressEventFired\n} = require('./symbols')\nconst { ProgressEvent } = require('./progressevent')\nconst { getEncoding } = require('./encoding')\nconst { DOMException } = require('../fetch/constants')\nconst { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL')\nconst { types } = require('util')\nconst { StringDecoder } = require('string_decoder')\nconst { btoa } = require('buffer')\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#readOperation\n * @param {import('./filereader').FileReader} fr\n * @param {import('buffer').Blob} blob\n * @param {string} type\n * @param {string?} encodingName\n */\nfunction readOperation (fr, blob, type, encodingName) {\n // 1. If fr’s state is \"loading\", throw an InvalidStateError\n // DOMException.\n if (fr[kState] === 'loading') {\n throw new DOMException('Invalid state', 'InvalidStateError')\n }\n\n // 2. Set fr’s state to \"loading\".\n fr[kState] = 'loading'\n\n // 3. Set fr’s result to null.\n fr[kResult] = null\n\n // 4. Set fr’s error to null.\n fr[kError] = null\n\n // 5. Let stream be the result of calling get stream on blob.\n /** @type {import('stream/web').ReadableStream} */\n const stream = blob.stream()\n\n // 6. Let reader be the result of getting a reader from stream.\n const reader = stream.getReader()\n\n // 7. Let bytes be an empty byte sequence.\n /** @type {Uint8Array[]} */\n const bytes = []\n\n // 8. Let chunkPromise be the result of reading a chunk from\n // stream with reader.\n let chunkPromise = reader.read()\n\n // 9. Let isFirstChunk be true.\n let isFirstChunk = true\n\n // 10. In parallel, while true:\n // Note: \"In parallel\" just means non-blocking\n // Note 2: readOperation itself cannot be async as double\n // reading the body would then reject the promise, instead\n // of throwing an error.\n ;(async () => {\n while (!fr[kAborted]) {\n // 1. Wait for chunkPromise to be fulfilled or rejected.\n try {\n const { done, value } = await chunkPromise\n\n // 2. If chunkPromise is fulfilled, and isFirstChunk is\n // true, queue a task to fire a progress event called\n // loadstart at fr.\n if (isFirstChunk && !fr[kAborted]) {\n queueMicrotask(() => {\n fireAProgressEvent('loadstart', fr)\n })\n }\n\n // 3. Set isFirstChunk to false.\n isFirstChunk = false\n\n // 4. If chunkPromise is fulfilled with an object whose\n // done property is false and whose value property is\n // a Uint8Array object, run these steps:\n if (!done && types.isUint8Array(value)) {\n // 1. Let bs be the byte sequence represented by the\n // Uint8Array object.\n\n // 2. Append bs to bytes.\n bytes.push(value)\n\n // 3. If roughly 50ms have passed since these steps\n // were last invoked, queue a task to fire a\n // progress event called progress at fr.\n if (\n (\n fr[kLastProgressEventFired] === undefined ||\n Date.now() - fr[kLastProgressEventFired] >= 50\n ) &&\n !fr[kAborted]\n ) {\n fr[kLastProgressEventFired] = Date.now()\n queueMicrotask(() => {\n fireAProgressEvent('progress', fr)\n })\n }\n\n // 4. Set chunkPromise to the result of reading a\n // chunk from stream with reader.\n chunkPromise = reader.read()\n } else if (done) {\n // 5. Otherwise, if chunkPromise is fulfilled with an\n // object whose done property is true, queue a task\n // to run the following steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Let result be the result of package data given\n // bytes, type, blob’s type, and encodingName.\n try {\n const result = packageData(bytes, type, blob.type, encodingName)\n\n // 4. Else:\n\n if (fr[kAborted]) {\n return\n }\n\n // 1. Set fr’s result to result.\n fr[kResult] = result\n\n // 2. Fire a progress event called load at the fr.\n fireAProgressEvent('load', fr)\n } catch (error) {\n // 3. If package data threw an exception error:\n\n // 1. Set fr’s error to error.\n fr[kError] = error\n\n // 2. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n }\n\n // 5. If fr’s state is not \"loading\", fire a progress\n // event called loadend at the fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n } catch (error) {\n if (fr[kAborted]) {\n return\n }\n\n // 6. Otherwise, if chunkPromise is rejected with an\n // error error, queue a task to run the following\n // steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Set fr’s error to error.\n fr[kError] = error\n\n // 3. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n\n // 4. If fr’s state is not \"loading\", fire a progress\n // event called loadend at fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n }\n })()\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#fire-a-progress-event\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e The name of the event\n * @param {import('./filereader').FileReader} reader\n */\nfunction fireAProgressEvent (e, reader) {\n // The progress event e does not bubble. e.bubbles must be false\n // The progress event e is NOT cancelable. e.cancelable must be false\n const event = new ProgressEvent(e, {\n bubbles: false,\n cancelable: false\n })\n\n reader.dispatchEvent(event)\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#blob-package-data\n * @param {Uint8Array[]} bytes\n * @param {string} type\n * @param {string?} mimeType\n * @param {string?} encodingName\n */\nfunction packageData (bytes, type, mimeType, encodingName) {\n // 1. A Blob has an associated package data algorithm, given\n // bytes, a type, a optional mimeType, and a optional\n // encodingName, which switches on type and runs the\n // associated steps:\n\n switch (type) {\n case 'DataURL': {\n // 1. Return bytes as a DataURL [RFC2397] subject to\n // the considerations below:\n // * Use mimeType as part of the Data URL if it is\n // available in keeping with the Data URL\n // specification [RFC2397].\n // * If mimeType is not available return a Data URL\n // without a media-type. [RFC2397].\n\n // https://datatracker.ietf.org/doc/html/rfc2397#section-3\n // dataurl := \"data:\" [ mediatype ] [ \";base64\" ] \",\" data\n // mediatype := [ type \"/\" subtype ] *( \";\" parameter )\n // data := *urlchar\n // parameter := attribute \"=\" value\n let dataURL = 'data:'\n\n const parsed = parseMIMEType(mimeType || 'application/octet-stream')\n\n if (parsed !== 'failure') {\n dataURL += serializeAMimeType(parsed)\n }\n\n dataURL += ';base64,'\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n dataURL += btoa(decoder.write(chunk))\n }\n\n dataURL += btoa(decoder.end())\n\n return dataURL\n }\n case 'Text': {\n // 1. Let encoding be failure\n let encoding = 'failure'\n\n // 2. If the encodingName is present, set encoding to the\n // result of getting an encoding from encodingName.\n if (encodingName) {\n encoding = getEncoding(encodingName)\n }\n\n // 3. If encoding is failure, and mimeType is present:\n if (encoding === 'failure' && mimeType) {\n // 1. Let type be the result of parse a MIME type\n // given mimeType.\n const type = parseMIMEType(mimeType)\n\n // 2. If type is not failure, set encoding to the result\n // of getting an encoding from type’s parameters[\"charset\"].\n if (type !== 'failure') {\n encoding = getEncoding(type.parameters.get('charset'))\n }\n }\n\n // 4. If encoding is failure, then set encoding to UTF-8.\n if (encoding === 'failure') {\n encoding = 'UTF-8'\n }\n\n // 5. Decode bytes using fallback encoding encoding, and\n // return the result.\n return decode(bytes, encoding)\n }\n case 'ArrayBuffer': {\n // Return a new ArrayBuffer whose contents are bytes.\n const sequence = combineByteSequences(bytes)\n\n return sequence.buffer\n }\n case 'BinaryString': {\n // Return bytes as a binary string, in which every byte\n // is represented by a code unit of equal value [0..255].\n let binaryString = ''\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n binaryString += decoder.write(chunk)\n }\n\n binaryString += decoder.end()\n\n return binaryString\n }\n }\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#decode\n * @param {Uint8Array[]} ioQueue\n * @param {string} encoding\n */\nfunction decode (ioQueue, encoding) {\n const bytes = combineByteSequences(ioQueue)\n\n // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.\n const BOMEncoding = BOMSniffing(bytes)\n\n let slice = 0\n\n // 2. If BOMEncoding is non-null:\n if (BOMEncoding !== null) {\n // 1. Set encoding to BOMEncoding.\n encoding = BOMEncoding\n\n // 2. Read three bytes from ioQueue, if BOMEncoding is\n // UTF-8; otherwise read two bytes.\n // (Do nothing with those bytes.)\n slice = BOMEncoding === 'UTF-8' ? 3 : 2\n }\n\n // 3. Process a queue with an instance of encoding’s\n // decoder, ioQueue, output, and \"replacement\".\n\n // 4. Return output.\n\n const sliced = bytes.slice(slice)\n return new TextDecoder(encoding).decode(sliced)\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#bom-sniff\n * @param {Uint8Array} ioQueue\n */\nfunction BOMSniffing (ioQueue) {\n // 1. Let BOM be the result of peeking 3 bytes from ioQueue,\n // converted to a byte sequence.\n const [a, b, c] = ioQueue\n\n // 2. For each of the rows in the table below, starting with\n // the first one and going down, if BOM starts with the\n // bytes given in the first column, then return the\n // encoding given in the cell in the second column of that\n // row. Otherwise, return null.\n if (a === 0xEF && b === 0xBB && c === 0xBF) {\n return 'UTF-8'\n } else if (a === 0xFE && b === 0xFF) {\n return 'UTF-16BE'\n } else if (a === 0xFF && b === 0xFE) {\n return 'UTF-16LE'\n }\n\n return null\n}\n\n/**\n * @param {Uint8Array[]} sequences\n */\nfunction combineByteSequences (sequences) {\n const size = sequences.reduce((a, b) => {\n return a + b.byteLength\n }, 0)\n\n let offset = 0\n\n return sequences.reduce((a, b) => {\n a.set(b, offset)\n offset += b.byteLength\n return a\n }, new Uint8Array(size))\n}\n\nmodule.exports = {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n}\n","'use strict'\n\n// We include a version number for the Dispatcher API. In case of breaking changes,\n// this version number must be increased to avoid conflicts.\nconst globalDispatcher = Symbol.for('undici.globalDispatcher.1')\nconst { InvalidArgumentError } = require('./core/errors')\nconst Agent = require('./agent')\n\nif (getGlobalDispatcher() === undefined) {\n setGlobalDispatcher(new Agent())\n}\n\nfunction setGlobalDispatcher (agent) {\n if (!agent || typeof agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument agent must implement Agent')\n }\n Object.defineProperty(globalThis, globalDispatcher, {\n value: agent,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nfunction getGlobalDispatcher () {\n return globalThis[globalDispatcher]\n}\n\nmodule.exports = {\n setGlobalDispatcher,\n getGlobalDispatcher\n}\n","'use strict'\n\nmodule.exports = class DecoratorHandler {\n constructor (handler) {\n this.handler = handler\n }\n\n onConnect (...args) {\n return this.handler.onConnect(...args)\n }\n\n onError (...args) {\n return this.handler.onError(...args)\n }\n\n onUpgrade (...args) {\n return this.handler.onUpgrade(...args)\n }\n\n onHeaders (...args) {\n return this.handler.onHeaders(...args)\n }\n\n onData (...args) {\n return this.handler.onData(...args)\n }\n\n onComplete (...args) {\n return this.handler.onComplete(...args)\n }\n\n onBodySent (...args) {\n return this.handler.onBodySent(...args)\n }\n}\n","'use strict'\n\nconst util = require('../core/util')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('assert')\nconst { InvalidArgumentError } = require('../core/errors')\nconst EE = require('events')\n\nconst redirectableStatusCodes = [300, 301, 302, 303, 307, 308]\n\nconst kBody = Symbol('body')\n\nclass BodyAsyncIterable {\n constructor (body) {\n this[kBody] = body\n this[kBodyUsed] = false\n }\n\n async * [Symbol.asyncIterator] () {\n assert(!this[kBodyUsed], 'disturbed')\n this[kBodyUsed] = true\n yield * this[kBody]\n }\n}\n\nclass RedirectHandler {\n constructor (dispatch, maxRedirections, opts, handler) {\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n util.validateHandler(handler, opts.method, opts.upgrade)\n\n this.dispatch = dispatch\n this.location = null\n this.abort = null\n this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy\n this.maxRedirections = maxRedirections\n this.handler = handler\n this.history = []\n\n if (util.isStream(this.opts.body)) {\n // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp\n // so that it can be dispatched again?\n // TODO (fix): Do we need 100-expect support to provide a way to do this properly?\n if (util.bodyLength(this.opts.body) === 0) {\n this.opts.body\n .on('data', function () {\n assert(false)\n })\n }\n\n if (typeof this.opts.body.readableDidRead !== 'boolean') {\n this.opts.body[kBodyUsed] = false\n EE.prototype.on.call(this.opts.body, 'data', function () {\n this[kBodyUsed] = true\n })\n }\n } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {\n // TODO (fix): We can't access ReadableStream internal state\n // to determine whether or not it has been disturbed. This is just\n // a workaround.\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n } else if (\n this.opts.body &&\n typeof this.opts.body !== 'string' &&\n !ArrayBuffer.isView(this.opts.body) &&\n util.isIterable(this.opts.body)\n ) {\n // TODO: Should we allow re-using iterable if !this.opts.idempotent\n // or through some other flag?\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n }\n }\n\n onConnect (abort) {\n this.abort = abort\n this.handler.onConnect(abort, { history: this.history })\n }\n\n onUpgrade (statusCode, headers, socket) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n\n onError (error) {\n this.handler.onError(error)\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)\n ? null\n : parseLocation(statusCode, headers)\n\n if (this.opts.origin) {\n this.history.push(new URL(this.opts.path, this.opts.origin))\n }\n\n if (!this.location) {\n return this.handler.onHeaders(statusCode, headers, resume, statusText)\n }\n\n const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))\n const path = search ? `${pathname}${search}` : pathname\n\n // Remove headers referring to the original URL.\n // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.\n // https://tools.ietf.org/html/rfc7231#section-6.4\n this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)\n this.opts.path = path\n this.opts.origin = origin\n this.opts.maxRedirections = 0\n this.opts.query = null\n\n // https://tools.ietf.org/html/rfc7231#section-6.4.4\n // In case of HTTP 303, always replace method to be either HEAD or GET\n if (statusCode === 303 && this.opts.method !== 'HEAD') {\n this.opts.method = 'GET'\n this.opts.body = null\n }\n }\n\n onData (chunk) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response bodies.\n\n Redirection is used to serve the requested resource from another URL, so it is assumes that\n no body is generated (and thus can be ignored). Even though generating a body is not prohibited.\n\n For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually\n (which means it's optional and not mandated) contain just an hyperlink to the value of\n the Location response header, so the body can be ignored safely.\n\n For status 300, which is \"Multiple Choices\", the spec mentions both generating a Location\n response header AND a response body with the other possible location to follow.\n Since the spec explicitily chooses not to specify a format for such body and leave it to\n servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.\n */\n } else {\n return this.handler.onData(chunk)\n }\n }\n\n onComplete (trailers) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections\n and neither are useful if present.\n\n See comment on onData method above for more detailed informations.\n */\n\n this.location = null\n this.abort = null\n\n this.dispatch(this.opts, this)\n } else {\n this.handler.onComplete(trailers)\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) {\n this.handler.onBodySent(chunk)\n }\n }\n}\n\nfunction parseLocation (statusCode, headers) {\n if (redirectableStatusCodes.indexOf(statusCode) === -1) {\n return null\n }\n\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toString().toLowerCase() === 'location') {\n return headers[i + 1]\n }\n }\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4.4\nfunction shouldRemoveHeader (header, removeContent, unknownOrigin) {\n if (header.length === 4) {\n return util.headerNameToString(header) === 'host'\n }\n if (removeContent && util.headerNameToString(header).startsWith('content-')) {\n return true\n }\n if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {\n const name = util.headerNameToString(header)\n return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'\n }\n return false\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4\nfunction cleanRequestHeaders (headers, removeContent, unknownOrigin) {\n const ret = []\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {\n ret.push(headers[i], headers[i + 1])\n }\n }\n } else if (headers && typeof headers === 'object') {\n for (const key of Object.keys(headers)) {\n if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {\n ret.push(key, headers[key])\n }\n }\n } else {\n assert(headers == null, 'headers must be an object or an array')\n }\n return ret\n}\n\nmodule.exports = RedirectHandler\n","const assert = require('assert')\n\nconst { kRetryHandlerDefaultRetry } = require('../core/symbols')\nconst { RequestRetryError } = require('../core/errors')\nconst { isDisturbed, parseHeaders, parseRangeHeader } = require('../core/util')\n\nfunction calculateRetryAfterHeader (retryAfter) {\n const current = Date.now()\n const diff = new Date(retryAfter).getTime() - current\n\n return diff\n}\n\nclass RetryHandler {\n constructor (opts, handlers) {\n const { retryOptions, ...dispatchOpts } = opts\n const {\n // Retry scoped\n retry: retryFn,\n maxRetries,\n maxTimeout,\n minTimeout,\n timeoutFactor,\n // Response scoped\n methods,\n errorCodes,\n retryAfter,\n statusCodes\n } = retryOptions ?? {}\n\n this.dispatch = handlers.dispatch\n this.handler = handlers.handler\n this.opts = dispatchOpts\n this.abort = null\n this.aborted = false\n this.retryOpts = {\n retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],\n retryAfter: retryAfter ?? true,\n maxTimeout: maxTimeout ?? 30 * 1000, // 30s,\n timeout: minTimeout ?? 500, // .5s\n timeoutFactor: timeoutFactor ?? 2,\n maxRetries: maxRetries ?? 5,\n // What errors we should retry\n methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],\n // Indicates which errors to retry\n statusCodes: statusCodes ?? [500, 502, 503, 504, 429],\n // List of errors to retry\n errorCodes: errorCodes ?? [\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ENETDOWN',\n 'ENETUNREACH',\n 'EHOSTDOWN',\n 'EHOSTUNREACH',\n 'EPIPE'\n ]\n }\n\n this.retryCount = 0\n this.start = 0\n this.end = null\n this.etag = null\n this.resume = null\n\n // Handle possible onConnect duplication\n this.handler.onConnect(reason => {\n this.aborted = true\n if (this.abort) {\n this.abort(reason)\n } else {\n this.reason = reason\n }\n })\n }\n\n onRequestSent () {\n if (this.handler.onRequestSent) {\n this.handler.onRequestSent()\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n if (this.handler.onUpgrade) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n }\n\n onConnect (abort) {\n if (this.aborted) {\n abort(this.reason)\n } else {\n this.abort = abort\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) return this.handler.onBodySent(chunk)\n }\n\n static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {\n const { statusCode, code, headers } = err\n const { method, retryOptions } = opts\n const {\n maxRetries,\n timeout,\n maxTimeout,\n timeoutFactor,\n statusCodes,\n errorCodes,\n methods\n } = retryOptions\n let { counter, currentTimeout } = state\n\n currentTimeout =\n currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout\n\n // Any code that is not a Undici's originated and allowed to retry\n if (\n code &&\n code !== 'UND_ERR_REQ_RETRY' &&\n code !== 'UND_ERR_SOCKET' &&\n !errorCodes.includes(code)\n ) {\n cb(err)\n return\n }\n\n // If a set of method are provided and the current method is not in the list\n if (Array.isArray(methods) && !methods.includes(method)) {\n cb(err)\n return\n }\n\n // If a set of status code are provided and the current status code is not in the list\n if (\n statusCode != null &&\n Array.isArray(statusCodes) &&\n !statusCodes.includes(statusCode)\n ) {\n cb(err)\n return\n }\n\n // If we reached the max number of retries\n if (counter > maxRetries) {\n cb(err)\n return\n }\n\n let retryAfterHeader = headers != null && headers['retry-after']\n if (retryAfterHeader) {\n retryAfterHeader = Number(retryAfterHeader)\n retryAfterHeader = isNaN(retryAfterHeader)\n ? calculateRetryAfterHeader(retryAfterHeader)\n : retryAfterHeader * 1e3 // Retry-After is in seconds\n }\n\n const retryTimeout =\n retryAfterHeader > 0\n ? Math.min(retryAfterHeader, maxTimeout)\n : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)\n\n state.currentTimeout = retryTimeout\n\n setTimeout(() => cb(null), retryTimeout)\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const headers = parseHeaders(rawHeaders)\n\n this.retryCount += 1\n\n if (statusCode >= 300) {\n this.abort(\n new RequestRetryError('Request failed', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n // Checkpoint for resume from where we left it\n if (this.resume != null) {\n this.resume = null\n\n if (statusCode !== 206) {\n return true\n }\n\n const contentRange = parseRangeHeader(headers['content-range'])\n // If no content range\n if (!contentRange) {\n this.abort(\n new RequestRetryError('Content-Range mismatch', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n // Let's start with a weak etag check\n if (this.etag != null && this.etag !== headers.etag) {\n this.abort(\n new RequestRetryError('ETag mismatch', statusCode, {\n headers,\n count: this.retryCount\n })\n )\n return false\n }\n\n const { start, size, end = size } = contentRange\n\n assert(this.start === start, 'content-range mismatch')\n assert(this.end == null || this.end === end, 'content-range mismatch')\n\n this.resume = resume\n return true\n }\n\n if (this.end == null) {\n if (statusCode === 206) {\n // First time we receive 206\n const range = parseRangeHeader(headers['content-range'])\n\n if (range == null) {\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const { start, size, end = size } = range\n\n assert(\n start != null && Number.isFinite(start) && this.start !== start,\n 'content-range mismatch'\n )\n assert(Number.isFinite(start))\n assert(\n end != null && Number.isFinite(end) && this.end !== end,\n 'invalid content-length'\n )\n\n this.start = start\n this.end = end\n }\n\n // We make our best to checkpoint the body for further range headers\n if (this.end == null) {\n const contentLength = headers['content-length']\n this.end = contentLength != null ? Number(contentLength) : null\n }\n\n assert(Number.isFinite(this.start))\n assert(\n this.end == null || Number.isFinite(this.end),\n 'invalid content-length'\n )\n\n this.resume = resume\n this.etag = headers.etag != null ? headers.etag : null\n\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const err = new RequestRetryError('Request failed', statusCode, {\n headers,\n count: this.retryCount\n })\n\n this.abort(err)\n\n return false\n }\n\n onData (chunk) {\n this.start += chunk.length\n\n return this.handler.onData(chunk)\n }\n\n onComplete (rawTrailers) {\n this.retryCount = 0\n return this.handler.onComplete(rawTrailers)\n }\n\n onError (err) {\n if (this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n this.retryOpts.retry(\n err,\n {\n state: { counter: this.retryCount++, currentTimeout: this.retryAfter },\n opts: { retryOptions: this.retryOpts, ...this.opts }\n },\n onRetry.bind(this)\n )\n\n function onRetry (err) {\n if (err != null || this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n if (this.start !== 0) {\n this.opts = {\n ...this.opts,\n headers: {\n ...this.opts.headers,\n range: `bytes=${this.start}-${this.end ?? ''}`\n }\n }\n }\n\n try {\n this.dispatch(this.opts, this)\n } catch (err) {\n this.handler.onError(err)\n }\n }\n }\n}\n\nmodule.exports = RetryHandler\n","'use strict'\n\nconst RedirectHandler = require('../handler/RedirectHandler')\n\nfunction createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {\n return (dispatch) => {\n return function Intercept (opts, handler) {\n const { maxRedirections = defaultMaxRedirections } = opts\n\n if (!maxRedirections) {\n return dispatch(opts, handler)\n }\n\n const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)\n opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.\n return dispatch(opts, redirectHandler)\n }\n }\n}\n\nmodule.exports = createRedirectInterceptor\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;\nconst utils_1 = require(\"./utils\");\n// C headers\nvar ERROR;\n(function (ERROR) {\n ERROR[ERROR[\"OK\"] = 0] = \"OK\";\n ERROR[ERROR[\"INTERNAL\"] = 1] = \"INTERNAL\";\n ERROR[ERROR[\"STRICT\"] = 2] = \"STRICT\";\n ERROR[ERROR[\"LF_EXPECTED\"] = 3] = \"LF_EXPECTED\";\n ERROR[ERROR[\"UNEXPECTED_CONTENT_LENGTH\"] = 4] = \"UNEXPECTED_CONTENT_LENGTH\";\n ERROR[ERROR[\"CLOSED_CONNECTION\"] = 5] = \"CLOSED_CONNECTION\";\n ERROR[ERROR[\"INVALID_METHOD\"] = 6] = \"INVALID_METHOD\";\n ERROR[ERROR[\"INVALID_URL\"] = 7] = \"INVALID_URL\";\n ERROR[ERROR[\"INVALID_CONSTANT\"] = 8] = \"INVALID_CONSTANT\";\n ERROR[ERROR[\"INVALID_VERSION\"] = 9] = \"INVALID_VERSION\";\n ERROR[ERROR[\"INVALID_HEADER_TOKEN\"] = 10] = \"INVALID_HEADER_TOKEN\";\n ERROR[ERROR[\"INVALID_CONTENT_LENGTH\"] = 11] = \"INVALID_CONTENT_LENGTH\";\n ERROR[ERROR[\"INVALID_CHUNK_SIZE\"] = 12] = \"INVALID_CHUNK_SIZE\";\n ERROR[ERROR[\"INVALID_STATUS\"] = 13] = \"INVALID_STATUS\";\n ERROR[ERROR[\"INVALID_EOF_STATE\"] = 14] = \"INVALID_EOF_STATE\";\n ERROR[ERROR[\"INVALID_TRANSFER_ENCODING\"] = 15] = \"INVALID_TRANSFER_ENCODING\";\n ERROR[ERROR[\"CB_MESSAGE_BEGIN\"] = 16] = \"CB_MESSAGE_BEGIN\";\n ERROR[ERROR[\"CB_HEADERS_COMPLETE\"] = 17] = \"CB_HEADERS_COMPLETE\";\n ERROR[ERROR[\"CB_MESSAGE_COMPLETE\"] = 18] = \"CB_MESSAGE_COMPLETE\";\n ERROR[ERROR[\"CB_CHUNK_HEADER\"] = 19] = \"CB_CHUNK_HEADER\";\n ERROR[ERROR[\"CB_CHUNK_COMPLETE\"] = 20] = \"CB_CHUNK_COMPLETE\";\n ERROR[ERROR[\"PAUSED\"] = 21] = \"PAUSED\";\n ERROR[ERROR[\"PAUSED_UPGRADE\"] = 22] = \"PAUSED_UPGRADE\";\n ERROR[ERROR[\"PAUSED_H2_UPGRADE\"] = 23] = \"PAUSED_H2_UPGRADE\";\n ERROR[ERROR[\"USER\"] = 24] = \"USER\";\n})(ERROR = exports.ERROR || (exports.ERROR = {}));\nvar TYPE;\n(function (TYPE) {\n TYPE[TYPE[\"BOTH\"] = 0] = \"BOTH\";\n TYPE[TYPE[\"REQUEST\"] = 1] = \"REQUEST\";\n TYPE[TYPE[\"RESPONSE\"] = 2] = \"RESPONSE\";\n})(TYPE = exports.TYPE || (exports.TYPE = {}));\nvar FLAGS;\n(function (FLAGS) {\n FLAGS[FLAGS[\"CONNECTION_KEEP_ALIVE\"] = 1] = \"CONNECTION_KEEP_ALIVE\";\n FLAGS[FLAGS[\"CONNECTION_CLOSE\"] = 2] = \"CONNECTION_CLOSE\";\n FLAGS[FLAGS[\"CONNECTION_UPGRADE\"] = 4] = \"CONNECTION_UPGRADE\";\n FLAGS[FLAGS[\"CHUNKED\"] = 8] = \"CHUNKED\";\n FLAGS[FLAGS[\"UPGRADE\"] = 16] = \"UPGRADE\";\n FLAGS[FLAGS[\"CONTENT_LENGTH\"] = 32] = \"CONTENT_LENGTH\";\n FLAGS[FLAGS[\"SKIPBODY\"] = 64] = \"SKIPBODY\";\n FLAGS[FLAGS[\"TRAILING\"] = 128] = \"TRAILING\";\n // 1 << 8 is unused\n FLAGS[FLAGS[\"TRANSFER_ENCODING\"] = 512] = \"TRANSFER_ENCODING\";\n})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));\nvar LENIENT_FLAGS;\n(function (LENIENT_FLAGS) {\n LENIENT_FLAGS[LENIENT_FLAGS[\"HEADERS\"] = 1] = \"HEADERS\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"CHUNKED_LENGTH\"] = 2] = \"CHUNKED_LENGTH\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"KEEP_ALIVE\"] = 4] = \"KEEP_ALIVE\";\n})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));\nvar METHODS;\n(function (METHODS) {\n METHODS[METHODS[\"DELETE\"] = 0] = \"DELETE\";\n METHODS[METHODS[\"GET\"] = 1] = \"GET\";\n METHODS[METHODS[\"HEAD\"] = 2] = \"HEAD\";\n METHODS[METHODS[\"POST\"] = 3] = \"POST\";\n METHODS[METHODS[\"PUT\"] = 4] = \"PUT\";\n /* pathological */\n METHODS[METHODS[\"CONNECT\"] = 5] = \"CONNECT\";\n METHODS[METHODS[\"OPTIONS\"] = 6] = \"OPTIONS\";\n METHODS[METHODS[\"TRACE\"] = 7] = \"TRACE\";\n /* WebDAV */\n METHODS[METHODS[\"COPY\"] = 8] = \"COPY\";\n METHODS[METHODS[\"LOCK\"] = 9] = \"LOCK\";\n METHODS[METHODS[\"MKCOL\"] = 10] = \"MKCOL\";\n METHODS[METHODS[\"MOVE\"] = 11] = \"MOVE\";\n METHODS[METHODS[\"PROPFIND\"] = 12] = \"PROPFIND\";\n METHODS[METHODS[\"PROPPATCH\"] = 13] = \"PROPPATCH\";\n METHODS[METHODS[\"SEARCH\"] = 14] = \"SEARCH\";\n METHODS[METHODS[\"UNLOCK\"] = 15] = \"UNLOCK\";\n METHODS[METHODS[\"BIND\"] = 16] = \"BIND\";\n METHODS[METHODS[\"REBIND\"] = 17] = \"REBIND\";\n METHODS[METHODS[\"UNBIND\"] = 18] = \"UNBIND\";\n METHODS[METHODS[\"ACL\"] = 19] = \"ACL\";\n /* subversion */\n METHODS[METHODS[\"REPORT\"] = 20] = \"REPORT\";\n METHODS[METHODS[\"MKACTIVITY\"] = 21] = \"MKACTIVITY\";\n METHODS[METHODS[\"CHECKOUT\"] = 22] = \"CHECKOUT\";\n METHODS[METHODS[\"MERGE\"] = 23] = \"MERGE\";\n /* upnp */\n METHODS[METHODS[\"M-SEARCH\"] = 24] = \"M-SEARCH\";\n METHODS[METHODS[\"NOTIFY\"] = 25] = \"NOTIFY\";\n METHODS[METHODS[\"SUBSCRIBE\"] = 26] = \"SUBSCRIBE\";\n METHODS[METHODS[\"UNSUBSCRIBE\"] = 27] = \"UNSUBSCRIBE\";\n /* RFC-5789 */\n METHODS[METHODS[\"PATCH\"] = 28] = \"PATCH\";\n METHODS[METHODS[\"PURGE\"] = 29] = \"PURGE\";\n /* CalDAV */\n METHODS[METHODS[\"MKCALENDAR\"] = 30] = \"MKCALENDAR\";\n /* RFC-2068, section 19.6.1.2 */\n METHODS[METHODS[\"LINK\"] = 31] = \"LINK\";\n METHODS[METHODS[\"UNLINK\"] = 32] = \"UNLINK\";\n /* icecast */\n METHODS[METHODS[\"SOURCE\"] = 33] = \"SOURCE\";\n /* RFC-7540, section 11.6 */\n METHODS[METHODS[\"PRI\"] = 34] = \"PRI\";\n /* RFC-2326 RTSP */\n METHODS[METHODS[\"DESCRIBE\"] = 35] = \"DESCRIBE\";\n METHODS[METHODS[\"ANNOUNCE\"] = 36] = \"ANNOUNCE\";\n METHODS[METHODS[\"SETUP\"] = 37] = \"SETUP\";\n METHODS[METHODS[\"PLAY\"] = 38] = \"PLAY\";\n METHODS[METHODS[\"PAUSE\"] = 39] = \"PAUSE\";\n METHODS[METHODS[\"TEARDOWN\"] = 40] = \"TEARDOWN\";\n METHODS[METHODS[\"GET_PARAMETER\"] = 41] = \"GET_PARAMETER\";\n METHODS[METHODS[\"SET_PARAMETER\"] = 42] = \"SET_PARAMETER\";\n METHODS[METHODS[\"REDIRECT\"] = 43] = \"REDIRECT\";\n METHODS[METHODS[\"RECORD\"] = 44] = \"RECORD\";\n /* RAOP */\n METHODS[METHODS[\"FLUSH\"] = 45] = \"FLUSH\";\n})(METHODS = exports.METHODS || (exports.METHODS = {}));\nexports.METHODS_HTTP = [\n METHODS.DELETE,\n METHODS.GET,\n METHODS.HEAD,\n METHODS.POST,\n METHODS.PUT,\n METHODS.CONNECT,\n METHODS.OPTIONS,\n METHODS.TRACE,\n METHODS.COPY,\n METHODS.LOCK,\n METHODS.MKCOL,\n METHODS.MOVE,\n METHODS.PROPFIND,\n METHODS.PROPPATCH,\n METHODS.SEARCH,\n METHODS.UNLOCK,\n METHODS.BIND,\n METHODS.REBIND,\n METHODS.UNBIND,\n METHODS.ACL,\n METHODS.REPORT,\n METHODS.MKACTIVITY,\n METHODS.CHECKOUT,\n METHODS.MERGE,\n METHODS['M-SEARCH'],\n METHODS.NOTIFY,\n METHODS.SUBSCRIBE,\n METHODS.UNSUBSCRIBE,\n METHODS.PATCH,\n METHODS.PURGE,\n METHODS.MKCALENDAR,\n METHODS.LINK,\n METHODS.UNLINK,\n METHODS.PRI,\n // TODO(indutny): should we allow it with HTTP?\n METHODS.SOURCE,\n];\nexports.METHODS_ICE = [\n METHODS.SOURCE,\n];\nexports.METHODS_RTSP = [\n METHODS.OPTIONS,\n METHODS.DESCRIBE,\n METHODS.ANNOUNCE,\n METHODS.SETUP,\n METHODS.PLAY,\n METHODS.PAUSE,\n METHODS.TEARDOWN,\n METHODS.GET_PARAMETER,\n METHODS.SET_PARAMETER,\n METHODS.REDIRECT,\n METHODS.RECORD,\n METHODS.FLUSH,\n // For AirPlay\n METHODS.GET,\n METHODS.POST,\n];\nexports.METHOD_MAP = utils_1.enumToMap(METHODS);\nexports.H_METHOD_MAP = {};\nObject.keys(exports.METHOD_MAP).forEach((key) => {\n if (/^H/.test(key)) {\n exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];\n }\n});\nvar FINISH;\n(function (FINISH) {\n FINISH[FINISH[\"SAFE\"] = 0] = \"SAFE\";\n FINISH[FINISH[\"SAFE_WITH_CB\"] = 1] = \"SAFE_WITH_CB\";\n FINISH[FINISH[\"UNSAFE\"] = 2] = \"UNSAFE\";\n})(FINISH = exports.FINISH || (exports.FINISH = {}));\nexports.ALPHA = [];\nfor (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {\n // Upper case\n exports.ALPHA.push(String.fromCharCode(i));\n // Lower case\n exports.ALPHA.push(String.fromCharCode(i + 0x20));\n}\nexports.NUM_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n};\nexports.HEX_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,\n a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,\n};\nexports.NUM = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n];\nexports.ALPHANUM = exports.ALPHA.concat(exports.NUM);\nexports.MARK = ['-', '_', '.', '!', '~', '*', '\\'', '(', ')'];\nexports.USERINFO_CHARS = exports.ALPHANUM\n .concat(exports.MARK)\n .concat(['%', ';', ':', '&', '=', '+', '$', ',']);\n// TODO(indutny): use RFC\nexports.STRICT_URL_CHAR = [\n '!', '\"', '$', '%', '&', '\\'',\n '(', ')', '*', '+', ',', '-', '.', '/',\n ':', ';', '<', '=', '>',\n '@', '[', '\\\\', ']', '^', '_',\n '`',\n '{', '|', '}', '~',\n].concat(exports.ALPHANUM);\nexports.URL_CHAR = exports.STRICT_URL_CHAR\n .concat(['\\t', '\\f']);\n// All characters with 0x80 bit set to 1\nfor (let i = 0x80; i <= 0xff; i++) {\n exports.URL_CHAR.push(i);\n}\nexports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);\n/* Tokens as defined by rfc 2616. Also lowercases them.\n * token = 1*\n * separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n * | \",\" | \";\" | \":\" | \"\\\" | <\">\n * | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n * | \"{\" | \"}\" | SP | HT\n */\nexports.STRICT_TOKEN = [\n '!', '#', '$', '%', '&', '\\'',\n '*', '+', '-', '.',\n '^', '_', '`',\n '|', '~',\n].concat(exports.ALPHANUM);\nexports.TOKEN = exports.STRICT_TOKEN.concat([' ']);\n/*\n * Verify that a char is a valid visible (printable) US-ASCII\n * character or %x80-FF\n */\nexports.HEADER_CHARS = ['\\t'];\nfor (let i = 32; i <= 255; i++) {\n if (i !== 127) {\n exports.HEADER_CHARS.push(i);\n }\n}\n// ',' = \\x44\nexports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);\nexports.MAJOR = exports.NUM_MAP;\nexports.MINOR = exports.MAJOR;\nvar HEADER_STATE;\n(function (HEADER_STATE) {\n HEADER_STATE[HEADER_STATE[\"GENERAL\"] = 0] = \"GENERAL\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION\"] = 1] = \"CONNECTION\";\n HEADER_STATE[HEADER_STATE[\"CONTENT_LENGTH\"] = 2] = \"CONTENT_LENGTH\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING\"] = 3] = \"TRANSFER_ENCODING\";\n HEADER_STATE[HEADER_STATE[\"UPGRADE\"] = 4] = \"UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_KEEP_ALIVE\"] = 5] = \"CONNECTION_KEEP_ALIVE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_CLOSE\"] = 6] = \"CONNECTION_CLOSE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_UPGRADE\"] = 7] = \"CONNECTION_UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING_CHUNKED\"] = 8] = \"TRANSFER_ENCODING_CHUNKED\";\n})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));\nexports.SPECIAL_HEADERS = {\n 'connection': HEADER_STATE.CONNECTION,\n 'content-length': HEADER_STATE.CONTENT_LENGTH,\n 'proxy-connection': HEADER_STATE.CONNECTION,\n 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,\n 'upgrade': HEADER_STATE.UPGRADE,\n};\n//# sourceMappingURL=constants.js.map","module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkB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QAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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FCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAU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YWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='\n","module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJs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IAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEB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QAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQID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YWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.enumToMap = void 0;\nfunction enumToMap(obj) {\n const res = {};\n Object.keys(obj).forEach((key) => {\n const value = obj[key];\n if (typeof value === 'number') {\n res[key] = value;\n }\n });\n return res;\n}\nexports.enumToMap = enumToMap;\n//# sourceMappingURL=utils.js.map","'use strict'\n\nconst { kClients } = require('../core/symbols')\nconst Agent = require('../agent')\nconst {\n kAgent,\n kMockAgentSet,\n kMockAgentGet,\n kDispatches,\n kIsMockActive,\n kNetConnect,\n kGetNetConnect,\n kOptions,\n kFactory\n} = require('./mock-symbols')\nconst MockClient = require('./mock-client')\nconst MockPool = require('./mock-pool')\nconst { matchValue, buildMockOptions } = require('./mock-utils')\nconst { InvalidArgumentError, UndiciError } = require('../core/errors')\nconst Dispatcher = require('../dispatcher')\nconst Pluralizer = require('./pluralizer')\nconst PendingInterceptorsFormatter = require('./pending-interceptors-formatter')\n\nclass FakeWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value\n }\n}\n\nclass MockAgent extends Dispatcher {\n constructor (opts) {\n super(opts)\n\n this[kNetConnect] = true\n this[kIsMockActive] = true\n\n // Instantiate Agent and encapsulate\n if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n const agent = opts && opts.agent ? opts.agent : new Agent(opts)\n this[kAgent] = agent\n\n this[kClients] = agent[kClients]\n this[kOptions] = buildMockOptions(opts)\n }\n\n get (origin) {\n let dispatcher = this[kMockAgentGet](origin)\n\n if (!dispatcher) {\n dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n }\n return dispatcher\n }\n\n dispatch (opts, handler) {\n // Call MockAgent.get to perform additional setup before dispatching as normal\n this.get(opts.origin)\n return this[kAgent].dispatch(opts, handler)\n }\n\n async close () {\n await this[kAgent].close()\n this[kClients].clear()\n }\n\n deactivate () {\n this[kIsMockActive] = false\n }\n\n activate () {\n this[kIsMockActive] = true\n }\n\n enableNetConnect (matcher) {\n if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {\n if (Array.isArray(this[kNetConnect])) {\n this[kNetConnect].push(matcher)\n } else {\n this[kNetConnect] = [matcher]\n }\n } else if (typeof matcher === 'undefined') {\n this[kNetConnect] = true\n } else {\n throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')\n }\n }\n\n disableNetConnect () {\n this[kNetConnect] = false\n }\n\n // This is required to bypass issues caused by using global symbols - see:\n // https://github.com/nodejs/undici/issues/1447\n get isMockActive () {\n return this[kIsMockActive]\n }\n\n [kMockAgentSet] (origin, dispatcher) {\n this[kClients].set(origin, new FakeWeakRef(dispatcher))\n }\n\n [kFactory] (origin) {\n const mockOptions = Object.assign({ agent: this }, this[kOptions])\n return this[kOptions] && this[kOptions].connections === 1\n ? new MockClient(origin, mockOptions)\n : new MockPool(origin, mockOptions)\n }\n\n [kMockAgentGet] (origin) {\n // First check if we can immediately find it\n const ref = this[kClients].get(origin)\n if (ref) {\n return ref.deref()\n }\n\n // If the origin is not a string create a dummy parent pool and return to user\n if (typeof origin !== 'string') {\n const dispatcher = this[kFactory]('http://localhost:9999')\n this[kMockAgentSet](origin, dispatcher)\n return dispatcher\n }\n\n // If we match, create a pool and assign the same dispatches\n for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {\n const nonExplicitDispatcher = nonExplicitRef.deref()\n if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {\n const dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]\n return dispatcher\n }\n }\n }\n\n [kGetNetConnect] () {\n return this[kNetConnect]\n }\n\n pendingInterceptors () {\n const mockAgentClients = this[kClients]\n\n return Array.from(mockAgentClients.entries())\n .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))\n .filter(({ pending }) => pending)\n }\n\n assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {\n const pending = this.pendingInterceptors()\n\n if (pending.length === 0) {\n return\n }\n\n const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)\n\n throw new UndiciError(`\n${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:\n\n${pendingInterceptorsFormatter.format(pending)}\n`.trim())\n }\n}\n\nmodule.exports = MockAgent\n","'use strict'\n\nconst { promisify } = require('util')\nconst Client = require('../client')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockClient provides an API that extends the Client to influence the mockDispatches.\n */\nclass MockClient extends Client {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockClient\n","'use strict'\n\nconst { UndiciError } = require('../core/errors')\n\nclass MockNotMatchedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, MockNotMatchedError)\n this.name = 'MockNotMatchedError'\n this.message = message || 'The request does not match any registered mock dispatches'\n this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'\n }\n}\n\nmodule.exports = {\n MockNotMatchedError\n}\n","'use strict'\n\nconst { getResponseData, buildKey, addMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kDispatchKey,\n kDefaultHeaders,\n kDefaultTrailers,\n kContentLength,\n kMockDispatch\n} = require('./mock-symbols')\nconst { InvalidArgumentError } = require('../core/errors')\nconst { buildURL } = require('../core/util')\n\n/**\n * Defines the scope API for an interceptor reply\n */\nclass MockScope {\n constructor (mockDispatch) {\n this[kMockDispatch] = mockDispatch\n }\n\n /**\n * Delay a reply by a set amount in ms.\n */\n delay (waitInMs) {\n if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {\n throw new InvalidArgumentError('waitInMs must be a valid integer > 0')\n }\n\n this[kMockDispatch].delay = waitInMs\n return this\n }\n\n /**\n * For a defined reply, never mark as consumed.\n */\n persist () {\n this[kMockDispatch].persist = true\n return this\n }\n\n /**\n * Allow one to define a reply for a set amount of matching requests.\n */\n times (repeatTimes) {\n if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {\n throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')\n }\n\n this[kMockDispatch].times = repeatTimes\n return this\n }\n}\n\n/**\n * Defines an interceptor for a Mock\n */\nclass MockInterceptor {\n constructor (opts, mockDispatches) {\n if (typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object')\n }\n if (typeof opts.path === 'undefined') {\n throw new InvalidArgumentError('opts.path must be defined')\n }\n if (typeof opts.method === 'undefined') {\n opts.method = 'GET'\n }\n // See https://github.com/nodejs/undici/issues/1245\n // As per RFC 3986, clients are not supposed to send URI\n // fragments to servers when they retrieve a document,\n if (typeof opts.path === 'string') {\n if (opts.query) {\n opts.path = buildURL(opts.path, opts.query)\n } else {\n // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811\n const parsedURL = new URL(opts.path, 'data://')\n opts.path = parsedURL.pathname + parsedURL.search\n }\n }\n if (typeof opts.method === 'string') {\n opts.method = opts.method.toUpperCase()\n }\n\n this[kDispatchKey] = buildKey(opts)\n this[kDispatches] = mockDispatches\n this[kDefaultHeaders] = {}\n this[kDefaultTrailers] = {}\n this[kContentLength] = false\n }\n\n createMockScopeDispatchData (statusCode, data, responseOptions = {}) {\n const responseData = getResponseData(data)\n const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}\n const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }\n const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }\n\n return { statusCode, data, headers, trailers }\n }\n\n validateReplyParameters (statusCode, data, responseOptions) {\n if (typeof statusCode === 'undefined') {\n throw new InvalidArgumentError('statusCode must be defined')\n }\n if (typeof data === 'undefined') {\n throw new InvalidArgumentError('data must be defined')\n }\n if (typeof responseOptions !== 'object') {\n throw new InvalidArgumentError('responseOptions must be an object')\n }\n }\n\n /**\n * Mock an undici request with a defined reply.\n */\n reply (replyData) {\n // Values of reply aren't available right now as they\n // can only be available when the reply callback is invoked.\n if (typeof replyData === 'function') {\n // We'll first wrap the provided callback in another function,\n // this function will properly resolve the data from the callback\n // when invoked.\n const wrappedDefaultsCallback = (opts) => {\n // Our reply options callback contains the parameter for statusCode, data and options.\n const resolvedData = replyData(opts)\n\n // Check if it is in the right format\n if (typeof resolvedData !== 'object') {\n throw new InvalidArgumentError('reply options callback must return an object')\n }\n\n const { statusCode, data = '', responseOptions = {} } = resolvedData\n this.validateReplyParameters(statusCode, data, responseOptions)\n // Since the values can be obtained immediately we return them\n // from this higher order function that will be resolved later.\n return {\n ...this.createMockScopeDispatchData(statusCode, data, responseOptions)\n }\n }\n\n // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)\n return new MockScope(newMockDispatch)\n }\n\n // We can have either one or three parameters, if we get here,\n // we should have 1-3 parameters. So we spread the arguments of\n // this function to obtain the parameters, since replyData will always\n // just be the statusCode.\n const [statusCode, data = '', responseOptions = {}] = [...arguments]\n this.validateReplyParameters(statusCode, data, responseOptions)\n\n // Send in-already provided data like usual\n const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Mock an undici request with a defined error.\n */\n replyWithError (error) {\n if (typeof error === 'undefined') {\n throw new InvalidArgumentError('error must be defined')\n }\n\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Set default reply headers on the interceptor for subsequent replies\n */\n defaultReplyHeaders (headers) {\n if (typeof headers === 'undefined') {\n throw new InvalidArgumentError('headers must be defined')\n }\n\n this[kDefaultHeaders] = headers\n return this\n }\n\n /**\n * Set default reply trailers on the interceptor for subsequent replies\n */\n defaultReplyTrailers (trailers) {\n if (typeof trailers === 'undefined') {\n throw new InvalidArgumentError('trailers must be defined')\n }\n\n this[kDefaultTrailers] = trailers\n return this\n }\n\n /**\n * Set reply content length header for replies on the interceptor\n */\n replyContentLength () {\n this[kContentLength] = true\n return this\n }\n}\n\nmodule.exports.MockInterceptor = MockInterceptor\nmodule.exports.MockScope = MockScope\n","'use strict'\n\nconst { promisify } = require('util')\nconst Pool = require('../pool')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockPool provides an API that extends the Pool to influence the mockDispatches.\n */\nclass MockPool extends Pool {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockPool\n","'use strict'\n\nmodule.exports = {\n kAgent: Symbol('agent'),\n kOptions: Symbol('options'),\n kFactory: Symbol('factory'),\n kDispatches: Symbol('dispatches'),\n kDispatchKey: Symbol('dispatch key'),\n kDefaultHeaders: Symbol('default headers'),\n kDefaultTrailers: Symbol('default trailers'),\n kContentLength: Symbol('content length'),\n kMockAgent: Symbol('mock agent'),\n kMockAgentSet: Symbol('mock agent set'),\n kMockAgentGet: Symbol('mock agent get'),\n kMockDispatch: Symbol('mock dispatch'),\n kClose: Symbol('close'),\n kOriginalClose: Symbol('original agent close'),\n kOrigin: Symbol('origin'),\n kIsMockActive: Symbol('is mock active'),\n kNetConnect: Symbol('net connect'),\n kGetNetConnect: Symbol('get net connect'),\n kConnected: Symbol('connected')\n}\n","'use strict'\n\nconst { MockNotMatchedError } = require('./mock-errors')\nconst {\n kDispatches,\n kMockAgent,\n kOriginalDispatch,\n kOrigin,\n kGetNetConnect\n} = require('./mock-symbols')\nconst { buildURL, nop } = require('../core/util')\nconst { STATUS_CODES } = require('http')\nconst {\n types: {\n isPromise\n }\n} = require('util')\n\nfunction matchValue (match, value) {\n if (typeof match === 'string') {\n return match === value\n }\n if (match instanceof RegExp) {\n return match.test(value)\n }\n if (typeof match === 'function') {\n return match(value) === true\n }\n return false\n}\n\nfunction lowerCaseEntries (headers) {\n return Object.fromEntries(\n Object.entries(headers).map(([headerName, headerValue]) => {\n return [headerName.toLocaleLowerCase(), headerValue]\n })\n )\n}\n\n/**\n * @param {import('../../index').Headers|string[]|Record} headers\n * @param {string} key\n */\nfunction getHeaderByName (headers, key) {\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {\n return headers[i + 1]\n }\n }\n\n return undefined\n } else if (typeof headers.get === 'function') {\n return headers.get(key)\n } else {\n return lowerCaseEntries(headers)[key.toLocaleLowerCase()]\n }\n}\n\n/** @param {string[]} headers */\nfunction buildHeadersFromArray (headers) { // fetch HeadersList\n const clone = headers.slice()\n const entries = []\n for (let index = 0; index < clone.length; index += 2) {\n entries.push([clone[index], clone[index + 1]])\n }\n return Object.fromEntries(entries)\n}\n\nfunction matchHeaders (mockDispatch, headers) {\n if (typeof mockDispatch.headers === 'function') {\n if (Array.isArray(headers)) { // fetch HeadersList\n headers = buildHeadersFromArray(headers)\n }\n return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})\n }\n if (typeof mockDispatch.headers === 'undefined') {\n return true\n }\n if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {\n return false\n }\n\n for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {\n const headerValue = getHeaderByName(headers, matchHeaderName)\n\n if (!matchValue(matchHeaderValue, headerValue)) {\n return false\n }\n }\n return true\n}\n\nfunction safeUrl (path) {\n if (typeof path !== 'string') {\n return path\n }\n\n const pathSegments = path.split('?')\n\n if (pathSegments.length !== 2) {\n return path\n }\n\n const qp = new URLSearchParams(pathSegments.pop())\n qp.sort()\n return [...pathSegments, qp.toString()].join('?')\n}\n\nfunction matchKey (mockDispatch, { path, method, body, headers }) {\n const pathMatch = matchValue(mockDispatch.path, path)\n const methodMatch = matchValue(mockDispatch.method, method)\n const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true\n const headersMatch = matchHeaders(mockDispatch, headers)\n return pathMatch && methodMatch && bodyMatch && headersMatch\n}\n\nfunction getResponseData (data) {\n if (Buffer.isBuffer(data)) {\n return data\n } else if (typeof data === 'object') {\n return JSON.stringify(data)\n } else {\n return data.toString()\n }\n}\n\nfunction getMockDispatch (mockDispatches, key) {\n const basePath = key.query ? buildURL(key.path, key.query) : key.path\n const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath\n\n // Match path\n let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)\n }\n\n // Match method\n matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)\n }\n\n // Match body\n matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)\n }\n\n // Match headers\n matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)\n }\n\n return matchedMockDispatches[0]\n}\n\nfunction addMockDispatch (mockDispatches, key, data) {\n const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }\n const replyData = typeof data === 'function' ? { callback: data } : { ...data }\n const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }\n mockDispatches.push(newMockDispatch)\n return newMockDispatch\n}\n\nfunction deleteMockDispatch (mockDispatches, key) {\n const index = mockDispatches.findIndex(dispatch => {\n if (!dispatch.consumed) {\n return false\n }\n return matchKey(dispatch, key)\n })\n if (index !== -1) {\n mockDispatches.splice(index, 1)\n }\n}\n\nfunction buildKey (opts) {\n const { path, method, body, headers, query } = opts\n return {\n path,\n method,\n body,\n headers,\n query\n }\n}\n\nfunction generateKeyValues (data) {\n return Object.entries(data).reduce((keyValuePairs, [key, value]) => [\n ...keyValuePairs,\n Buffer.from(`${key}`),\n Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)\n ], [])\n}\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\n * @param {number} statusCode\n */\nfunction getStatusText (statusCode) {\n return STATUS_CODES[statusCode] || 'unknown'\n}\n\nasync function getResponse (body) {\n const buffers = []\n for await (const data of body) {\n buffers.push(data)\n }\n return Buffer.concat(buffers).toString('utf8')\n}\n\n/**\n * Mock dispatch function used to simulate undici dispatches\n */\nfunction mockDispatch (opts, handler) {\n // Get mock dispatch from built key\n const key = buildKey(opts)\n const mockDispatch = getMockDispatch(this[kDispatches], key)\n\n mockDispatch.timesInvoked++\n\n // Here's where we resolve a callback if a callback is present for the dispatch data.\n if (mockDispatch.data.callback) {\n mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }\n }\n\n // Parse mockDispatch data\n const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch\n const { timesInvoked, times } = mockDispatch\n\n // If it's used up and not persistent, mark as consumed\n mockDispatch.consumed = !persist && timesInvoked >= times\n mockDispatch.pending = timesInvoked < times\n\n // If specified, trigger dispatch error\n if (error !== null) {\n deleteMockDispatch(this[kDispatches], key)\n handler.onError(error)\n return true\n }\n\n // Handle the request with a delay if necessary\n if (typeof delay === 'number' && delay > 0) {\n setTimeout(() => {\n handleReply(this[kDispatches])\n }, delay)\n } else {\n handleReply(this[kDispatches])\n }\n\n function handleReply (mockDispatches, _data = data) {\n // fetch's HeadersList is a 1D string array\n const optsHeaders = Array.isArray(opts.headers)\n ? buildHeadersFromArray(opts.headers)\n : opts.headers\n const body = typeof _data === 'function'\n ? _data({ ...opts, headers: optsHeaders })\n : _data\n\n // util.types.isPromise is likely needed for jest.\n if (isPromise(body)) {\n // If handleReply is asynchronous, throwing an error\n // in the callback will reject the promise, rather than\n // synchronously throw the error, which breaks some tests.\n // Rather, we wait for the callback to resolve if it is a\n // promise, and then re-run handleReply with the new body.\n body.then((newData) => handleReply(mockDispatches, newData))\n return\n }\n\n const responseData = getResponseData(body)\n const responseHeaders = generateKeyValues(headers)\n const responseTrailers = generateKeyValues(trailers)\n\n handler.abort = nop\n handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))\n handler.onData(Buffer.from(responseData))\n handler.onComplete(responseTrailers)\n deleteMockDispatch(mockDispatches, key)\n }\n\n function resume () {}\n\n return true\n}\n\nfunction buildMockDispatch () {\n const agent = this[kMockAgent]\n const origin = this[kOrigin]\n const originalDispatch = this[kOriginalDispatch]\n\n return function dispatch (opts, handler) {\n if (agent.isMockActive) {\n try {\n mockDispatch.call(this, opts, handler)\n } catch (error) {\n if (error instanceof MockNotMatchedError) {\n const netConnect = agent[kGetNetConnect]()\n if (netConnect === false) {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)\n }\n if (checkNetConnect(netConnect, origin)) {\n originalDispatch.call(this, opts, handler)\n } else {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)\n }\n } else {\n throw error\n }\n }\n } else {\n originalDispatch.call(this, opts, handler)\n }\n }\n}\n\nfunction checkNetConnect (netConnect, origin) {\n const url = new URL(origin)\n if (netConnect === true) {\n return true\n } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {\n return true\n }\n return false\n}\n\nfunction buildMockOptions (opts) {\n if (opts) {\n const { agent, ...mockOptions } = opts\n return mockOptions\n }\n}\n\nmodule.exports = {\n getResponseData,\n getMockDispatch,\n addMockDispatch,\n deleteMockDispatch,\n buildKey,\n generateKeyValues,\n matchValue,\n getResponse,\n getStatusText,\n mockDispatch,\n buildMockDispatch,\n checkNetConnect,\n buildMockOptions,\n getHeaderByName\n}\n","'use strict'\n\nconst { Transform } = require('stream')\nconst { Console } = require('console')\n\n/**\n * Gets the output of `console.table(…)` as a string.\n */\nmodule.exports = class PendingInterceptorsFormatter {\n constructor ({ disableColors } = {}) {\n this.transform = new Transform({\n transform (chunk, _enc, cb) {\n cb(null, chunk)\n }\n })\n\n this.logger = new Console({\n stdout: this.transform,\n inspectOptions: {\n colors: !disableColors && !process.env.CI\n }\n })\n }\n\n format (pendingInterceptors) {\n const withPrettyHeaders = pendingInterceptors.map(\n ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({\n Method: method,\n Origin: origin,\n Path: path,\n 'Status code': statusCode,\n Persistent: persist ? '✅' : '❌',\n Invocations: timesInvoked,\n Remaining: persist ? Infinity : times - timesInvoked\n }))\n\n this.logger.table(withPrettyHeaders)\n return this.transform.read().toString()\n }\n}\n","'use strict'\n\nconst singulars = {\n pronoun: 'it',\n is: 'is',\n was: 'was',\n this: 'this'\n}\n\nconst plurals = {\n pronoun: 'they',\n is: 'are',\n was: 'were',\n this: 'these'\n}\n\nmodule.exports = class Pluralizer {\n constructor (singular, plural) {\n this.singular = singular\n this.plural = plural\n }\n\n pluralize (count) {\n const one = count === 1\n const keys = one ? singulars : plurals\n const noun = one ? this.singular : this.plural\n return { ...keys, count, noun }\n }\n}\n","/* eslint-disable */\n\n'use strict'\n\n// Extracted from node/lib/internal/fixed_queue.js\n\n// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.\nconst kSize = 2048;\nconst kMask = kSize - 1;\n\n// The FixedQueue is implemented as a singly-linked list of fixed-size\n// circular buffers. It looks something like this:\n//\n// head tail\n// | |\n// v v\n// +-----------+ <-----\\ +-----------+ <------\\ +-----------+\n// | [null] | \\----- | next | \\------- | next |\n// +-----------+ +-----------+ +-----------+\n// | item | <-- bottom | item | <-- bottom | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | bottom --> | item |\n// | item | | item | | item |\n// | ... | | ... | | ... |\n// | item | | item | | item |\n// | item | | item | | item |\n// | [empty] | <-- top | item | | item |\n// | [empty] | | item | | item |\n// | [empty] | | [empty] | <-- top top --> | [empty] |\n// +-----------+ +-----------+ +-----------+\n//\n// Or, if there is only one circular buffer, it looks something\n// like either of these:\n//\n// head tail head tail\n// | | | |\n// v v v v\n// +-----------+ +-----------+\n// | [null] | | [null] |\n// +-----------+ +-----------+\n// | [empty] | | item |\n// | [empty] | | item |\n// | item | <-- bottom top --> | [empty] |\n// | item | | [empty] |\n// | [empty] | <-- top bottom --> | item |\n// | [empty] | | item |\n// +-----------+ +-----------+\n//\n// Adding a value means moving `top` forward by one, removing means\n// moving `bottom` forward by one. After reaching the end, the queue\n// wraps around.\n//\n// When `top === bottom` the current queue is empty and when\n// `top + 1 === bottom` it's full. This wastes a single space of storage\n// but allows much quicker checks.\n\nclass FixedCircularBuffer {\n constructor() {\n this.bottom = 0;\n this.top = 0;\n this.list = new Array(kSize);\n this.next = null;\n }\n\n isEmpty() {\n return this.top === this.bottom;\n }\n\n isFull() {\n return ((this.top + 1) & kMask) === this.bottom;\n }\n\n push(data) {\n this.list[this.top] = data;\n this.top = (this.top + 1) & kMask;\n }\n\n shift() {\n const nextItem = this.list[this.bottom];\n if (nextItem === undefined)\n return null;\n this.list[this.bottom] = undefined;\n this.bottom = (this.bottom + 1) & kMask;\n return nextItem;\n }\n}\n\nmodule.exports = class FixedQueue {\n constructor() {\n this.head = this.tail = new FixedCircularBuffer();\n }\n\n isEmpty() {\n return this.head.isEmpty();\n }\n\n push(data) {\n if (this.head.isFull()) {\n // Head is full: Creates a new queue, sets the old queue's `.next` to it,\n // and sets it as the new main queue.\n this.head = this.head.next = new FixedCircularBuffer();\n }\n this.head.push(data);\n }\n\n shift() {\n const tail = this.tail;\n const next = tail.shift();\n if (tail.isEmpty() && tail.next !== null) {\n // If there is another queue, it forms the new tail.\n this.tail = tail.next;\n }\n return next;\n }\n};\n","'use strict'\n\nconst DispatcherBase = require('./dispatcher-base')\nconst FixedQueue = require('./node/fixed-queue')\nconst { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols')\nconst PoolStats = require('./pool-stats')\n\nconst kClients = Symbol('clients')\nconst kNeedDrain = Symbol('needDrain')\nconst kQueue = Symbol('queue')\nconst kClosedResolve = Symbol('closed resolve')\nconst kOnDrain = Symbol('onDrain')\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kGetDispatcher = Symbol('get dispatcher')\nconst kAddClient = Symbol('add client')\nconst kRemoveClient = Symbol('remove client')\nconst kStats = Symbol('stats')\n\nclass PoolBase extends DispatcherBase {\n constructor () {\n super()\n\n this[kQueue] = new FixedQueue()\n this[kClients] = []\n this[kQueued] = 0\n\n const pool = this\n\n this[kOnDrain] = function onDrain (origin, targets) {\n const queue = pool[kQueue]\n\n let needDrain = false\n\n while (!needDrain) {\n const item = queue.shift()\n if (!item) {\n break\n }\n pool[kQueued]--\n needDrain = !this.dispatch(item.opts, item.handler)\n }\n\n this[kNeedDrain] = needDrain\n\n if (!this[kNeedDrain] && pool[kNeedDrain]) {\n pool[kNeedDrain] = false\n pool.emit('drain', origin, [pool, ...targets])\n }\n\n if (pool[kClosedResolve] && queue.isEmpty()) {\n Promise\n .all(pool[kClients].map(c => c.close()))\n .then(pool[kClosedResolve])\n }\n }\n\n this[kOnConnect] = (origin, targets) => {\n pool.emit('connect', origin, [pool, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n pool.emit('disconnect', origin, [pool, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n pool.emit('connectionError', origin, [pool, ...targets], err)\n }\n\n this[kStats] = new PoolStats(this)\n }\n\n get [kBusy] () {\n return this[kNeedDrain]\n }\n\n get [kConnected] () {\n return this[kClients].filter(client => client[kConnected]).length\n }\n\n get [kFree] () {\n return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length\n }\n\n get [kPending] () {\n let ret = this[kQueued]\n for (const { [kPending]: pending } of this[kClients]) {\n ret += pending\n }\n return ret\n }\n\n get [kRunning] () {\n let ret = 0\n for (const { [kRunning]: running } of this[kClients]) {\n ret += running\n }\n return ret\n }\n\n get [kSize] () {\n let ret = this[kQueued]\n for (const { [kSize]: size } of this[kClients]) {\n ret += size\n }\n return ret\n }\n\n get stats () {\n return this[kStats]\n }\n\n async [kClose] () {\n if (this[kQueue].isEmpty()) {\n return Promise.all(this[kClients].map(c => c.close()))\n } else {\n return new Promise((resolve) => {\n this[kClosedResolve] = resolve\n })\n }\n }\n\n async [kDestroy] (err) {\n while (true) {\n const item = this[kQueue].shift()\n if (!item) {\n break\n }\n item.handler.onError(err)\n }\n\n return Promise.all(this[kClients].map(c => c.destroy(err)))\n }\n\n [kDispatch] (opts, handler) {\n const dispatcher = this[kGetDispatcher]()\n\n if (!dispatcher) {\n this[kNeedDrain] = true\n this[kQueue].push({ opts, handler })\n this[kQueued]++\n } else if (!dispatcher.dispatch(opts, handler)) {\n dispatcher[kNeedDrain] = true\n this[kNeedDrain] = !this[kGetDispatcher]()\n }\n\n return !this[kNeedDrain]\n }\n\n [kAddClient] (client) {\n client\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].push(client)\n\n if (this[kNeedDrain]) {\n process.nextTick(() => {\n if (this[kNeedDrain]) {\n this[kOnDrain](client[kUrl], [this, client])\n }\n })\n }\n\n return this\n }\n\n [kRemoveClient] (client) {\n client.close(() => {\n const idx = this[kClients].indexOf(client)\n if (idx !== -1) {\n this[kClients].splice(idx, 1)\n }\n })\n\n this[kNeedDrain] = this[kClients].some(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n }\n}\n\nmodule.exports = {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n}\n","const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('./core/symbols')\nconst kPool = Symbol('pool')\n\nclass PoolStats {\n constructor (pool) {\n this[kPool] = pool\n }\n\n get connected () {\n return this[kPool][kConnected]\n }\n\n get free () {\n return this[kPool][kFree]\n }\n\n get pending () {\n return this[kPool][kPending]\n }\n\n get queued () {\n return this[kPool][kQueued]\n }\n\n get running () {\n return this[kPool][kRunning]\n }\n\n get size () {\n return this[kPool][kSize]\n }\n}\n\nmodule.exports = PoolStats\n","'use strict'\n\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Client = require('./client')\nconst {\n InvalidArgumentError\n} = require('./core/errors')\nconst util = require('./core/util')\nconst { kUrl, kInterceptors } = require('./core/symbols')\nconst buildConnector = require('./core/connect')\n\nconst kOptions = Symbol('options')\nconst kConnections = Symbol('connections')\nconst kFactory = Symbol('factory')\n\nfunction defaultFactory (origin, opts) {\n return new Client(origin, opts)\n}\n\nclass Pool extends PoolBase {\n constructor (origin, {\n connections,\n factory = defaultFactory,\n connect,\n connectTimeout,\n tls,\n maxCachedSessions,\n socketPath,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n allowH2,\n ...options\n } = {}) {\n super()\n\n if (connections != null && (!Number.isFinite(connections) || connections < 0)) {\n throw new InvalidArgumentError('invalid connections')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)\n ? options.interceptors.Pool\n : []\n this[kConnections] = connections || null\n this[kUrl] = util.parseOrigin(origin)\n this[kOptions] = { ...util.deepClone(options), connect, allowH2 }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kFactory] = factory\n\n this.on('connectionError', (origin, targets, error) => {\n // If a connection error occurs, we remove the client from the pool,\n // and emit a connectionError event. They will not be re-used.\n // Fixes https://github.com/nodejs/undici/issues/3895\n for (const target of targets) {\n // Do not use kRemoveClient here, as it will close the client,\n // but the client cannot be closed in this state.\n const idx = this[kClients].indexOf(target)\n if (idx !== -1) {\n this[kClients].splice(idx, 1)\n }\n }\n })\n }\n\n [kGetDispatcher] () {\n let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])\n\n if (dispatcher) {\n return dispatcher\n }\n\n if (!this[kConnections] || this[kClients].length < this[kConnections]) {\n dispatcher = this[kFactory](this[kUrl], this[kOptions])\n this[kAddClient](dispatcher)\n }\n\n return dispatcher\n }\n}\n\nmodule.exports = Pool\n","'use strict'\n\nconst { kProxy, kClose, kDestroy, kInterceptors } = require('./core/symbols')\nconst { URL } = require('url')\nconst Agent = require('./agent')\nconst Pool = require('./pool')\nconst DispatcherBase = require('./dispatcher-base')\nconst { InvalidArgumentError, RequestAbortedError } = require('./core/errors')\nconst buildConnector = require('./core/connect')\n\nconst kAgent = Symbol('proxy agent')\nconst kClient = Symbol('proxy client')\nconst kProxyHeaders = Symbol('proxy headers')\nconst kRequestTls = Symbol('request tls settings')\nconst kProxyTls = Symbol('proxy tls settings')\nconst kConnectEndpoint = Symbol('connect endpoint function')\n\nfunction defaultProtocolPort (protocol) {\n return protocol === 'https:' ? 443 : 80\n}\n\nfunction buildProxyOptions (opts) {\n if (typeof opts === 'string') {\n opts = { uri: opts }\n }\n\n if (!opts || !opts.uri) {\n throw new InvalidArgumentError('Proxy opts.uri is mandatory')\n }\n\n return {\n uri: opts.uri,\n protocol: opts.protocol || 'https'\n }\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass ProxyAgent extends DispatcherBase {\n constructor (opts) {\n super(opts)\n this[kProxy] = buildProxyOptions(opts)\n this[kAgent] = new Agent(opts)\n this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)\n ? opts.interceptors.ProxyAgent\n : []\n\n if (typeof opts === 'string') {\n opts = { uri: opts }\n }\n\n if (!opts || !opts.uri) {\n throw new InvalidArgumentError('Proxy opts.uri is mandatory')\n }\n\n const { clientFactory = defaultFactory } = opts\n\n if (typeof clientFactory !== 'function') {\n throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')\n }\n\n this[kRequestTls] = opts.requestTls\n this[kProxyTls] = opts.proxyTls\n this[kProxyHeaders] = opts.headers || {}\n\n const resolvedUrl = new URL(opts.uri)\n const { origin, port, host, username, password } = resolvedUrl\n\n if (opts.auth && opts.token) {\n throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')\n } else if (opts.auth) {\n /* @deprecated in favour of opts.token */\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`\n } else if (opts.token) {\n this[kProxyHeaders]['proxy-authorization'] = opts.token\n } else if (username && password) {\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`\n }\n\n const connect = buildConnector({ ...opts.proxyTls })\n this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })\n this[kClient] = clientFactory(resolvedUrl, { connect })\n this[kAgent] = new Agent({\n ...opts,\n connect: async (opts, callback) => {\n let requestedHost = opts.host\n if (!opts.port) {\n requestedHost += `:${defaultProtocolPort(opts.protocol)}`\n }\n try {\n const { socket, statusCode } = await this[kClient].connect({\n origin,\n port,\n path: requestedHost,\n signal: opts.signal,\n headers: {\n ...this[kProxyHeaders],\n host\n }\n })\n if (statusCode !== 200) {\n socket.on('error', () => {}).destroy()\n callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))\n }\n if (opts.protocol !== 'https:') {\n callback(null, socket)\n return\n }\n let servername\n if (this[kRequestTls]) {\n servername = this[kRequestTls].servername\n } else {\n servername = opts.servername\n }\n this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)\n } catch (err) {\n callback(err)\n }\n }\n })\n }\n\n dispatch (opts, handler) {\n const { host } = new URL(opts.origin)\n const headers = buildHeaders(opts.headers)\n throwIfProxyAuthIsSent(headers)\n return this[kAgent].dispatch(\n {\n ...opts,\n headers: {\n ...headers,\n host\n }\n },\n handler\n )\n }\n\n async [kClose] () {\n await this[kAgent].close()\n await this[kClient].close()\n }\n\n async [kDestroy] () {\n await this[kAgent].destroy()\n await this[kClient].destroy()\n }\n}\n\n/**\n * @param {string[] | Record} headers\n * @returns {Record}\n */\nfunction buildHeaders (headers) {\n // When using undici.fetch, the headers list is stored\n // as an array.\n if (Array.isArray(headers)) {\n /** @type {Record} */\n const headersPair = {}\n\n for (let i = 0; i < headers.length; i += 2) {\n headersPair[headers[i]] = headers[i + 1]\n }\n\n return headersPair\n }\n\n return headers\n}\n\n/**\n * @param {Record} headers\n *\n * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers\n * Nevertheless, it was changed and to avoid a security vulnerability by end users\n * this check was created.\n * It should be removed in the next major version for performance reasons\n */\nfunction throwIfProxyAuthIsSent (headers) {\n const existProxyAuth = headers && Object.keys(headers)\n .find((key) => key.toLowerCase() === 'proxy-authorization')\n if (existProxyAuth) {\n throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')\n }\n}\n\nmodule.exports = ProxyAgent\n","'use strict'\n\nlet fastNow = Date.now()\nlet fastNowTimeout\n\nconst fastTimers = []\n\nfunction onTimeout () {\n fastNow = Date.now()\n\n let len = fastTimers.length\n let idx = 0\n while (idx < len) {\n const timer = fastTimers[idx]\n\n if (timer.state === 0) {\n timer.state = fastNow + timer.delay\n } else if (timer.state > 0 && fastNow >= timer.state) {\n timer.state = -1\n timer.callback(timer.opaque)\n }\n\n if (timer.state === -1) {\n timer.state = -2\n if (idx !== len - 1) {\n fastTimers[idx] = fastTimers.pop()\n } else {\n fastTimers.pop()\n }\n len -= 1\n } else {\n idx += 1\n }\n }\n\n if (fastTimers.length > 0) {\n refreshTimeout()\n }\n}\n\nfunction refreshTimeout () {\n if (fastNowTimeout && fastNowTimeout.refresh) {\n fastNowTimeout.refresh()\n } else {\n clearTimeout(fastNowTimeout)\n fastNowTimeout = setTimeout(onTimeout, 1e3)\n if (fastNowTimeout.unref) {\n fastNowTimeout.unref()\n }\n }\n}\n\nclass Timeout {\n constructor (callback, delay, opaque) {\n this.callback = callback\n this.delay = delay\n this.opaque = opaque\n\n // -2 not in timer list\n // -1 in timer list but inactive\n // 0 in timer list waiting for time\n // > 0 in timer list waiting for time to expire\n this.state = -2\n\n this.refresh()\n }\n\n refresh () {\n if (this.state === -2) {\n fastTimers.push(this)\n if (!fastNowTimeout || fastTimers.length === 1) {\n refreshTimeout()\n }\n }\n\n this.state = 0\n }\n\n clear () {\n this.state = -1\n }\n}\n\nmodule.exports = {\n setTimeout (callback, delay, opaque) {\n return delay < 1e3\n ? setTimeout(callback, delay, opaque)\n : new Timeout(callback, delay, opaque)\n },\n clearTimeout (timeout) {\n if (timeout instanceof Timeout) {\n timeout.clear()\n } else {\n clearTimeout(timeout)\n }\n }\n}\n","'use strict'\n\nconst diagnosticsChannel = require('diagnostics_channel')\nconst { uid, states } = require('./constants')\nconst {\n kReadyState,\n kSentClose,\n kByteParser,\n kReceivedClose\n} = require('./symbols')\nconst { fireEvent, failWebsocketConnection } = require('./util')\nconst { CloseEvent } = require('./events')\nconst { makeRequest } = require('../fetch/request')\nconst { fetching } = require('../fetch/index')\nconst { Headers } = require('../fetch/headers')\nconst { getGlobalDispatcher } = require('../global')\nconst { kHeadersList } = require('../core/symbols')\n\nconst channels = {}\nchannels.open = diagnosticsChannel.channel('undici:websocket:open')\nchannels.close = diagnosticsChannel.channel('undici:websocket:close')\nchannels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('crypto')\n} catch {\n\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#concept-websocket-establish\n * @param {URL} url\n * @param {string|string[]} protocols\n * @param {import('./websocket').WebSocket} ws\n * @param {(response: any) => void} onEstablish\n * @param {Partial} options\n */\nfunction establishWebSocketConnection (url, protocols, ws, onEstablish, options) {\n // 1. Let requestURL be a copy of url, with its scheme set to \"http\", if url’s\n // scheme is \"ws\", and to \"https\" otherwise.\n const requestURL = url\n\n requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'\n\n // 2. Let request be a new request, whose URL is requestURL, client is client,\n // service-workers mode is \"none\", referrer is \"no-referrer\", mode is\n // \"websocket\", credentials mode is \"include\", cache mode is \"no-store\" ,\n // and redirect mode is \"error\".\n const request = makeRequest({\n urlList: [requestURL],\n serviceWorkers: 'none',\n referrer: 'no-referrer',\n mode: 'websocket',\n credentials: 'include',\n cache: 'no-store',\n redirect: 'error'\n })\n\n // Note: undici extension, allow setting custom headers.\n if (options.headers) {\n const headersList = new Headers(options.headers)[kHeadersList]\n\n request.headersList = headersList\n }\n\n // 3. Append (`Upgrade`, `websocket`) to request’s header list.\n // 4. Append (`Connection`, `Upgrade`) to request’s header list.\n // Note: both of these are handled by undici currently.\n // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397\n\n // 5. Let keyValue be a nonce consisting of a randomly selected\n // 16-byte value that has been forgiving-base64-encoded and\n // isomorphic encoded.\n const keyValue = crypto.randomBytes(16).toString('base64')\n\n // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s\n // header list.\n request.headersList.append('sec-websocket-key', keyValue)\n\n // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s\n // header list.\n request.headersList.append('sec-websocket-version', '13')\n\n // 8. For each protocol in protocols, combine\n // (`Sec-WebSocket-Protocol`, protocol) in request’s header\n // list.\n for (const protocol of protocols) {\n request.headersList.append('sec-websocket-protocol', protocol)\n }\n\n // 9. Let permessageDeflate be a user-agent defined\n // \"permessage-deflate\" extension header value.\n // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673\n // TODO: enable once permessage-deflate is supported\n const permessageDeflate = '' // 'permessage-deflate; 15'\n\n // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to\n // request’s header list.\n // request.headersList.append('sec-websocket-extensions', permessageDeflate)\n\n // 11. Fetch request with useParallelQueue set to true, and\n // processResponse given response being these steps:\n const controller = fetching({\n request,\n useParallelQueue: true,\n dispatcher: options.dispatcher ?? getGlobalDispatcher(),\n processResponse (response) {\n // 1. If response is a network error or its status is not 101,\n // fail the WebSocket connection.\n if (response.type === 'error' || response.status !== 101) {\n failWebsocketConnection(ws, 'Received network error or non-101 status code.')\n return\n }\n\n // 2. If protocols is not the empty list and extracting header\n // list values given `Sec-WebSocket-Protocol` and response’s\n // header list results in null, failure, or the empty byte\n // sequence, then fail the WebSocket connection.\n if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Server did not respond with sent protocols.')\n return\n }\n\n // 3. Follow the requirements stated step 2 to step 6, inclusive,\n // of the last set of steps in section 4.1 of The WebSocket\n // Protocol to validate response. This either results in fail\n // the WebSocket connection or the WebSocket connection is\n // established.\n\n // 2. If the response lacks an |Upgrade| header field or the |Upgrade|\n // header field contains a value that is not an ASCII case-\n // insensitive match for the value \"websocket\", the client MUST\n // _Fail the WebSocket Connection_.\n if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {\n failWebsocketConnection(ws, 'Server did not set Upgrade header to \"websocket\".')\n return\n }\n\n // 3. If the response lacks a |Connection| header field or the\n // |Connection| header field doesn't contain a token that is an\n // ASCII case-insensitive match for the value \"Upgrade\", the client\n // MUST _Fail the WebSocket Connection_.\n if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {\n failWebsocketConnection(ws, 'Server did not set Connection header to \"upgrade\".')\n return\n }\n\n // 4. If the response lacks a |Sec-WebSocket-Accept| header field or\n // the |Sec-WebSocket-Accept| contains a value other than the\n // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-\n // Key| (as a string, not base64-decoded) with the string \"258EAFA5-\n // E914-47DA-95CA-C5AB0DC85B11\" but ignoring any leading and\n // trailing whitespace, the client MUST _Fail the WebSocket\n // Connection_.\n const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')\n const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')\n if (secWSAccept !== digest) {\n failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')\n return\n }\n\n // 5. If the response includes a |Sec-WebSocket-Extensions| header\n // field and this header field indicates the use of an extension\n // that was not present in the client's handshake (the server has\n // indicated an extension not requested by the client), the client\n // MUST _Fail the WebSocket Connection_. (The parsing of this\n // header field to determine which extensions are requested is\n // discussed in Section 9.1.)\n const secExtension = response.headersList.get('Sec-WebSocket-Extensions')\n\n if (secExtension !== null && secExtension !== permessageDeflate) {\n failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')\n return\n }\n\n // 6. If the response includes a |Sec-WebSocket-Protocol| header field\n // and this header field indicates the use of a subprotocol that was\n // not present in the client's handshake (the server has indicated a\n // subprotocol not requested by the client), the client MUST _Fail\n // the WebSocket Connection_.\n const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')\n\n if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')\n return\n }\n\n response.socket.on('data', onSocketData)\n response.socket.on('close', onSocketClose)\n response.socket.on('error', onSocketError)\n\n if (channels.open.hasSubscribers) {\n channels.open.publish({\n address: response.socket.address(),\n protocol: secProtocol,\n extensions: secExtension\n })\n }\n\n onEstablish(response)\n }\n })\n\n return controller\n}\n\n/**\n * @param {Buffer} chunk\n */\nfunction onSocketData (chunk) {\n if (!this.ws[kByteParser].write(chunk)) {\n this.pause()\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4\n */\nfunction onSocketClose () {\n const { ws } = this\n\n // If the TCP connection was closed after the\n // WebSocket closing handshake was completed, the WebSocket connection\n // is said to have been closed _cleanly_.\n const wasClean = ws[kSentClose] && ws[kReceivedClose]\n\n let code = 1005\n let reason = ''\n\n const result = ws[kByteParser].closingInfo\n\n if (result) {\n code = result.code ?? 1005\n reason = result.reason\n } else if (!ws[kSentClose]) {\n // If _The WebSocket\n // Connection is Closed_ and no Close control frame was received by the\n // endpoint (such as could occur if the underlying transport connection\n // is lost), _The WebSocket Connection Close Code_ is considered to be\n // 1006.\n code = 1006\n }\n\n // 1. Change the ready state to CLOSED (3).\n ws[kReadyState] = states.CLOSED\n\n // 2. If the user agent was required to fail the WebSocket\n // connection, or if the WebSocket connection was closed\n // after being flagged as full, fire an event named error\n // at the WebSocket object.\n // TODO\n\n // 3. Fire an event named close at the WebSocket object,\n // using CloseEvent, with the wasClean attribute\n // initialized to true if the connection closed cleanly\n // and false otherwise, the code attribute initialized to\n // the WebSocket connection close code, and the reason\n // attribute initialized to the result of applying UTF-8\n // decode without BOM to the WebSocket connection close\n // reason.\n fireEvent('close', ws, CloseEvent, {\n wasClean, code, reason\n })\n\n if (channels.close.hasSubscribers) {\n channels.close.publish({\n websocket: ws,\n code,\n reason\n })\n }\n}\n\nfunction onSocketError (error) {\n const { ws } = this\n\n ws[kReadyState] = states.CLOSING\n\n if (channels.socketError.hasSubscribers) {\n channels.socketError.publish(error)\n }\n\n this.destroy()\n}\n\nmodule.exports = {\n establishWebSocketConnection\n}\n","'use strict'\n\n// This is a Globally Unique Identifier unique used\n// to validate that the endpoint accepts websocket\n// connections.\n// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3\nconst uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\nconst states = {\n CONNECTING: 0,\n OPEN: 1,\n CLOSING: 2,\n CLOSED: 3\n}\n\nconst opcodes = {\n CONTINUATION: 0x0,\n TEXT: 0x1,\n BINARY: 0x2,\n CLOSE: 0x8,\n PING: 0x9,\n PONG: 0xA\n}\n\nconst maxUnsigned16Bit = 2 ** 16 - 1 // 65535\n\nconst parserStates = {\n INFO: 0,\n PAYLOADLENGTH_16: 2,\n PAYLOADLENGTH_64: 3,\n READ_DATA: 4\n}\n\nconst emptyBuffer = Buffer.allocUnsafe(0)\n\nmodule.exports = {\n uid,\n staticPropertyDescriptors,\n states,\n opcodes,\n maxUnsigned16Bit,\n parserStates,\n emptyBuffer\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../core/util')\nconst { MessagePort } = require('worker_threads')\n\n/**\n * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent\n */\nclass MessageEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.MessageEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n }\n\n get data () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.data\n }\n\n get origin () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.origin\n }\n\n get lastEventId () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.lastEventId\n }\n\n get source () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.source\n }\n\n get ports () {\n webidl.brandCheck(this, MessageEvent)\n\n if (!Object.isFrozen(this.#eventInit.ports)) {\n Object.freeze(this.#eventInit.ports)\n }\n\n return this.#eventInit.ports\n }\n\n initMessageEvent (\n type,\n bubbles = false,\n cancelable = false,\n data = null,\n origin = '',\n lastEventId = '',\n source = null,\n ports = []\n ) {\n webidl.brandCheck(this, MessageEvent)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })\n\n return new MessageEvent(type, {\n bubbles, cancelable, data, origin, lastEventId, source, ports\n })\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#the-closeevent-interface\n */\nclass CloseEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.CloseEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n }\n\n get wasClean () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.wasClean\n }\n\n get code () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.code\n }\n\n get reason () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.reason\n }\n}\n\n// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface\nclass ErrorEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict) {\n webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })\n\n super(type, eventInitDict)\n\n type = webidl.converters.DOMString(type)\n eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})\n\n this.#eventInit = eventInitDict\n }\n\n get message () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.message\n }\n\n get filename () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.filename\n }\n\n get lineno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.lineno\n }\n\n get colno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.colno\n }\n\n get error () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.error\n }\n}\n\nObject.defineProperties(MessageEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'MessageEvent',\n configurable: true\n },\n data: kEnumerableProperty,\n origin: kEnumerableProperty,\n lastEventId: kEnumerableProperty,\n source: kEnumerableProperty,\n ports: kEnumerableProperty,\n initMessageEvent: kEnumerableProperty\n})\n\nObject.defineProperties(CloseEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'CloseEvent',\n configurable: true\n },\n reason: kEnumerableProperty,\n code: kEnumerableProperty,\n wasClean: kEnumerableProperty\n})\n\nObject.defineProperties(ErrorEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'ErrorEvent',\n configurable: true\n },\n message: kEnumerableProperty,\n filename: kEnumerableProperty,\n lineno: kEnumerableProperty,\n colno: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\nwebidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.MessagePort\n)\n\nconst eventInit = [\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: false\n }\n]\n\nwebidl.converters.MessageEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'data',\n converter: webidl.converters.any,\n defaultValue: null\n },\n {\n key: 'origin',\n converter: webidl.converters.USVString,\n defaultValue: ''\n },\n {\n key: 'lastEventId',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'source',\n // Node doesn't implement WindowProxy or ServiceWorker, so the only\n // valid value for source is a MessagePort.\n converter: webidl.nullableConverter(webidl.converters.MessagePort),\n defaultValue: null\n },\n {\n key: 'ports',\n converter: webidl.converters['sequence'],\n get defaultValue () {\n return []\n }\n }\n])\n\nwebidl.converters.CloseEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'wasClean',\n converter: webidl.converters.boolean,\n defaultValue: false\n },\n {\n key: 'code',\n converter: webidl.converters['unsigned short'],\n defaultValue: 0\n },\n {\n key: 'reason',\n converter: webidl.converters.USVString,\n defaultValue: ''\n }\n])\n\nwebidl.converters.ErrorEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'message',\n converter: webidl.converters.DOMString,\n defaultValue: ''\n },\n {\n key: 'filename',\n converter: webidl.converters.USVString,\n defaultValue: ''\n },\n {\n key: 'lineno',\n converter: webidl.converters['unsigned long'],\n defaultValue: 0\n },\n {\n key: 'colno',\n converter: webidl.converters['unsigned long'],\n defaultValue: 0\n },\n {\n key: 'error',\n converter: webidl.converters.any\n }\n])\n\nmodule.exports = {\n MessageEvent,\n CloseEvent,\n ErrorEvent\n}\n","'use strict'\n\nconst { maxUnsigned16Bit } = require('./constants')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('crypto')\n} catch {\n\n}\n\nclass WebsocketFrameSend {\n /**\n * @param {Buffer|undefined} data\n */\n constructor (data) {\n this.frameData = data\n this.maskKey = crypto.randomBytes(4)\n }\n\n createFrame (opcode) {\n const bodyLength = this.frameData?.byteLength ?? 0\n\n /** @type {number} */\n let payloadLength = bodyLength // 0-125\n let offset = 6\n\n if (bodyLength > maxUnsigned16Bit) {\n offset += 8 // payload length is next 8 bytes\n payloadLength = 127\n } else if (bodyLength > 125) {\n offset += 2 // payload length is next 2 bytes\n payloadLength = 126\n }\n\n const buffer = Buffer.allocUnsafe(bodyLength + offset)\n\n // Clear first 2 bytes, everything else is overwritten\n buffer[0] = buffer[1] = 0\n buffer[0] |= 0x80 // FIN\n buffer[0] = (buffer[0] & 0xF0) + opcode // opcode\n\n /*! ws. MIT License. Einar Otto Stangvik */\n buffer[offset - 4] = this.maskKey[0]\n buffer[offset - 3] = this.maskKey[1]\n buffer[offset - 2] = this.maskKey[2]\n buffer[offset - 1] = this.maskKey[3]\n\n buffer[1] = payloadLength\n\n if (payloadLength === 126) {\n buffer.writeUInt16BE(bodyLength, 2)\n } else if (payloadLength === 127) {\n // Clear extended payload length\n buffer[2] = buffer[3] = 0\n buffer.writeUIntBE(bodyLength, 4, 6)\n }\n\n buffer[1] |= 0x80 // MASK\n\n // mask body\n for (let i = 0; i < bodyLength; i++) {\n buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]\n }\n\n return buffer\n }\n}\n\nmodule.exports = {\n WebsocketFrameSend\n}\n","'use strict'\n\nconst { Writable } = require('stream')\nconst diagnosticsChannel = require('diagnostics_channel')\nconst { parserStates, opcodes, states, emptyBuffer } = require('./constants')\nconst { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols')\nconst { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = require('./util')\nconst { WebsocketFrameSend } = require('./frame')\n\n// This code was influenced by ws released under the MIT license.\n// Copyright (c) 2011 Einar Otto Stangvik \n// Copyright (c) 2013 Arnout Kazemier and contributors\n// Copyright (c) 2016 Luigi Pinca and contributors\n\nconst channels = {}\nchannels.ping = diagnosticsChannel.channel('undici:websocket:ping')\nchannels.pong = diagnosticsChannel.channel('undici:websocket:pong')\n\nclass ByteParser extends Writable {\n #buffers = []\n #byteOffset = 0\n\n #state = parserStates.INFO\n\n #info = {}\n #fragments = []\n\n constructor (ws) {\n super()\n\n this.ws = ws\n }\n\n /**\n * @param {Buffer} chunk\n * @param {() => void} callback\n */\n _write (chunk, _, callback) {\n this.#buffers.push(chunk)\n this.#byteOffset += chunk.length\n\n this.run(callback)\n }\n\n /**\n * Runs whenever a new chunk is received.\n * Callback is called whenever there are no more chunks buffering,\n * or not enough bytes are buffered to parse.\n */\n run (callback) {\n while (true) {\n if (this.#state === parserStates.INFO) {\n // If there aren't enough bytes to parse the payload length, etc.\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.fin = (buffer[0] & 0x80) !== 0\n this.#info.opcode = buffer[0] & 0x0F\n\n // If we receive a fragmented message, we use the type of the first\n // frame to parse the full message as binary/text, when it's terminated\n this.#info.originalOpcode ??= this.#info.opcode\n\n this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION\n\n if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {\n // Only text and binary frames can be fragmented\n failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')\n return\n }\n\n const payloadLength = buffer[1] & 0x7F\n\n if (payloadLength <= 125) {\n this.#info.payloadLength = payloadLength\n this.#state = parserStates.READ_DATA\n } else if (payloadLength === 126) {\n this.#state = parserStates.PAYLOADLENGTH_16\n } else if (payloadLength === 127) {\n this.#state = parserStates.PAYLOADLENGTH_64\n }\n\n if (this.#info.fragmented && payloadLength > 125) {\n // A fragmented frame can't be fragmented itself\n failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')\n return\n } else if (\n (this.#info.opcode === opcodes.PING ||\n this.#info.opcode === opcodes.PONG ||\n this.#info.opcode === opcodes.CLOSE) &&\n payloadLength > 125\n ) {\n // Control frames can have a payload length of 125 bytes MAX\n failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')\n return\n } else if (this.#info.opcode === opcodes.CLOSE) {\n if (payloadLength === 1) {\n failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')\n return\n }\n\n const body = this.consume(payloadLength)\n\n this.#info.closeInfo = this.parseCloseBody(false, body)\n\n if (!this.ws[kSentClose]) {\n // If an endpoint receives a Close frame and did not previously send a\n // Close frame, the endpoint MUST send a Close frame in response. (When\n // sending a Close frame in response, the endpoint typically echos the\n // status code it received.)\n const body = Buffer.allocUnsafe(2)\n body.writeUInt16BE(this.#info.closeInfo.code, 0)\n const closeFrame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(\n closeFrame.createFrame(opcodes.CLOSE),\n (err) => {\n if (!err) {\n this.ws[kSentClose] = true\n }\n }\n )\n }\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this.ws[kReadyState] = states.CLOSING\n this.ws[kReceivedClose] = true\n\n this.end()\n\n return\n } else if (this.#info.opcode === opcodes.PING) {\n // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in\n // response, unless it already received a Close frame.\n // A Pong frame sent in response to a Ping frame must have identical\n // \"Application data\"\n\n const body = this.consume(payloadLength)\n\n if (!this.ws[kReceivedClose]) {\n const frame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))\n\n if (channels.ping.hasSubscribers) {\n channels.ping.publish({\n payload: body\n })\n }\n }\n\n this.#state = parserStates.INFO\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n return\n }\n } else if (this.#info.opcode === opcodes.PONG) {\n // A Pong frame MAY be sent unsolicited. This serves as a\n // unidirectional heartbeat. A response to an unsolicited Pong frame is\n // not expected.\n\n const body = this.consume(payloadLength)\n\n if (channels.pong.hasSubscribers) {\n channels.pong.publish({\n payload: body\n })\n }\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n return\n }\n }\n } else if (this.#state === parserStates.PAYLOADLENGTH_16) {\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.payloadLength = buffer.readUInt16BE(0)\n this.#state = parserStates.READ_DATA\n } else if (this.#state === parserStates.PAYLOADLENGTH_64) {\n if (this.#byteOffset < 8) {\n return callback()\n }\n\n const buffer = this.consume(8)\n const upper = buffer.readUInt32BE(0)\n\n // 2^31 is the maxinimum bytes an arraybuffer can contain\n // on 32-bit systems. Although, on 64-bit systems, this is\n // 2^53-1 bytes.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e\n if (upper > 2 ** 31 - 1) {\n failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')\n return\n }\n\n const lower = buffer.readUInt32BE(4)\n\n this.#info.payloadLength = (upper << 8) + lower\n this.#state = parserStates.READ_DATA\n } else if (this.#state === parserStates.READ_DATA) {\n if (this.#byteOffset < this.#info.payloadLength) {\n // If there is still more data in this chunk that needs to be read\n return callback()\n } else if (this.#byteOffset >= this.#info.payloadLength) {\n // If the server sent multiple frames in a single chunk\n\n const body = this.consume(this.#info.payloadLength)\n\n this.#fragments.push(body)\n\n // If the frame is unfragmented, or a fragmented frame was terminated,\n // a message was received\n if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {\n const fullMessage = Buffer.concat(this.#fragments)\n\n websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)\n\n this.#info = {}\n this.#fragments.length = 0\n }\n\n this.#state = parserStates.INFO\n }\n }\n\n if (this.#byteOffset > 0) {\n continue\n } else {\n callback()\n break\n }\n }\n }\n\n /**\n * Take n bytes from the buffered Buffers\n * @param {number} n\n * @returns {Buffer|null}\n */\n consume (n) {\n if (n > this.#byteOffset) {\n return null\n } else if (n === 0) {\n return emptyBuffer\n }\n\n if (this.#buffers[0].length === n) {\n this.#byteOffset -= this.#buffers[0].length\n return this.#buffers.shift()\n }\n\n const buffer = Buffer.allocUnsafe(n)\n let offset = 0\n\n while (offset !== n) {\n const next = this.#buffers[0]\n const { length } = next\n\n if (length + offset === n) {\n buffer.set(this.#buffers.shift(), offset)\n break\n } else if (length + offset > n) {\n buffer.set(next.subarray(0, n - offset), offset)\n this.#buffers[0] = next.subarray(n - offset)\n break\n } else {\n buffer.set(this.#buffers.shift(), offset)\n offset += next.length\n }\n }\n\n this.#byteOffset -= n\n\n return buffer\n }\n\n parseCloseBody (onlyCode, data) {\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5\n /** @type {number|undefined} */\n let code\n\n if (data.length >= 2) {\n // _The WebSocket Connection Close Code_ is\n // defined as the status code (Section 7.4) contained in the first Close\n // control frame received by the application\n code = data.readUInt16BE(0)\n }\n\n if (onlyCode) {\n if (!isValidStatusCode(code)) {\n return null\n }\n\n return { code }\n }\n\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6\n /** @type {Buffer} */\n let reason = data.subarray(2)\n\n // Remove BOM\n if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {\n reason = reason.subarray(3)\n }\n\n if (code !== undefined && !isValidStatusCode(code)) {\n return null\n }\n\n try {\n // TODO: optimize this\n reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)\n } catch {\n return null\n }\n\n return { code, reason }\n }\n\n get closingInfo () {\n return this.#info.closeInfo\n }\n}\n\nmodule.exports = {\n ByteParser\n}\n","'use strict'\n\nmodule.exports = {\n kWebSocketURL: Symbol('url'),\n kReadyState: Symbol('ready state'),\n kController: Symbol('controller'),\n kResponse: Symbol('response'),\n kBinaryType: Symbol('binary type'),\n kSentClose: Symbol('sent close'),\n kReceivedClose: Symbol('received close'),\n kByteParser: Symbol('byte parser')\n}\n","'use strict'\n\nconst { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols')\nconst { states, opcodes } = require('./constants')\nconst { MessageEvent, ErrorEvent } = require('./events')\n\n/* globals Blob */\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isEstablished (ws) {\n // If the server's response is validated as provided for above, it is\n // said that _The WebSocket Connection is Established_ and that the\n // WebSocket Connection is in the OPEN state.\n return ws[kReadyState] === states.OPEN\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isClosing (ws) {\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n return ws[kReadyState] === states.CLOSING\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n */\nfunction isClosed (ws) {\n return ws[kReadyState] === states.CLOSED\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e\n * @param {EventTarget} target\n * @param {EventInit | undefined} eventInitDict\n */\nfunction fireEvent (e, target, eventConstructor = Event, eventInitDict) {\n // 1. If eventConstructor is not given, then let eventConstructor be Event.\n\n // 2. Let event be the result of creating an event given eventConstructor,\n // in the relevant realm of target.\n // 3. Initialize event’s type attribute to e.\n const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap\n\n // 4. Initialize any other IDL attributes of event as described in the\n // invocation of this algorithm.\n\n // 5. Return the result of dispatching event at target, with legacy target\n // override flag set if set.\n target.dispatchEvent(event)\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @param {import('./websocket').WebSocket} ws\n * @param {number} type Opcode\n * @param {Buffer} data application data\n */\nfunction websocketMessageReceived (ws, type, data) {\n // 1. If ready state is not OPEN (1), then return.\n if (ws[kReadyState] !== states.OPEN) {\n return\n }\n\n // 2. Let dataForEvent be determined by switching on type and binary type:\n let dataForEvent\n\n if (type === opcodes.TEXT) {\n // -> type indicates that the data is Text\n // a new DOMString containing data\n try {\n dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)\n } catch {\n failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')\n return\n }\n } else if (type === opcodes.BINARY) {\n if (ws[kBinaryType] === 'blob') {\n // -> type indicates that the data is Binary and binary type is \"blob\"\n // a new Blob object, created in the relevant Realm of the WebSocket\n // object, that represents data as its raw data\n dataForEvent = new Blob([data])\n } else {\n // -> type indicates that the data is Binary and binary type is \"arraybuffer\"\n // a new ArrayBuffer object, created in the relevant Realm of the\n // WebSocket object, whose contents are data\n dataForEvent = new Uint8Array(data).buffer\n }\n }\n\n // 3. Fire an event named message at the WebSocket object, using MessageEvent,\n // with the origin attribute initialized to the serialization of the WebSocket\n // object’s url's origin, and the data attribute initialized to dataForEvent.\n fireEvent('message', ws, MessageEvent, {\n origin: ws[kWebSocketURL].origin,\n data: dataForEvent\n })\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455\n * @see https://datatracker.ietf.org/doc/html/rfc2616\n * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407\n * @param {string} protocol\n */\nfunction isValidSubprotocol (protocol) {\n // If present, this value indicates one\n // or more comma-separated subprotocol the client wishes to speak,\n // ordered by preference. The elements that comprise this value\n // MUST be non-empty strings with characters in the range U+0021 to\n // U+007E not including separator characters as defined in\n // [RFC2616] and MUST all be unique strings.\n if (protocol.length === 0) {\n return false\n }\n\n for (const char of protocol) {\n const code = char.charCodeAt(0)\n\n if (\n code < 0x21 ||\n code > 0x7E ||\n char === '(' ||\n char === ')' ||\n char === '<' ||\n char === '>' ||\n char === '@' ||\n char === ',' ||\n char === ';' ||\n char === ':' ||\n char === '\\\\' ||\n char === '\"' ||\n char === '/' ||\n char === '[' ||\n char === ']' ||\n char === '?' ||\n char === '=' ||\n char === '{' ||\n char === '}' ||\n code === 32 || // SP\n code === 9 // HT\n ) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4\n * @param {number} code\n */\nfunction isValidStatusCode (code) {\n if (code >= 1000 && code < 1015) {\n return (\n code !== 1004 && // reserved\n code !== 1005 && // \"MUST NOT be set as a status code\"\n code !== 1006 // \"MUST NOT be set as a status code\"\n )\n }\n\n return code >= 3000 && code <= 4999\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @param {string|undefined} reason\n */\nfunction failWebsocketConnection (ws, reason) {\n const { [kController]: controller, [kResponse]: response } = ws\n\n controller.abort()\n\n if (response?.socket && !response.socket.destroyed) {\n response.socket.destroy()\n }\n\n if (reason) {\n fireEvent('error', ws, ErrorEvent, {\n error: new Error(reason)\n })\n }\n}\n\nmodule.exports = {\n isEstablished,\n isClosing,\n isClosed,\n fireEvent,\n isValidSubprotocol,\n isValidStatusCode,\n failWebsocketConnection,\n websocketMessageReceived\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { DOMException } = require('../fetch/constants')\nconst { URLSerializer } = require('../fetch/dataURL')\nconst { getGlobalOrigin } = require('../fetch/global')\nconst { staticPropertyDescriptors, states, opcodes, emptyBuffer } = require('./constants')\nconst {\n kWebSocketURL,\n kReadyState,\n kController,\n kBinaryType,\n kResponse,\n kSentClose,\n kByteParser\n} = require('./symbols')\nconst { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = require('./util')\nconst { establishWebSocketConnection } = require('./connection')\nconst { WebsocketFrameSend } = require('./frame')\nconst { ByteParser } = require('./receiver')\nconst { kEnumerableProperty, isBlobLike } = require('../core/util')\nconst { getGlobalDispatcher } = require('../global')\nconst { types } = require('util')\n\nlet experimentalWarned = false\n\n// https://websockets.spec.whatwg.org/#interface-definition\nclass WebSocket extends EventTarget {\n #events = {\n open: null,\n error: null,\n close: null,\n message: null\n }\n\n #bufferedAmount = 0\n #protocol = ''\n #extensions = ''\n\n /**\n * @param {string} url\n * @param {string|string[]} protocols\n */\n constructor (url, protocols = []) {\n super()\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })\n\n if (!experimentalWarned) {\n experimentalWarned = true\n process.emitWarning('WebSockets are experimental, expect them to change at any time.', {\n code: 'UNDICI-WS'\n })\n }\n\n const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)\n\n url = webidl.converters.USVString(url)\n protocols = options.protocols\n\n // 1. Let baseURL be this's relevant settings object's API base URL.\n const baseURL = getGlobalOrigin()\n\n // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.\n let urlRecord\n\n try {\n urlRecord = new URL(url, baseURL)\n } catch (e) {\n // 3. If urlRecord is failure, then throw a \"SyntaxError\" DOMException.\n throw new DOMException(e, 'SyntaxError')\n }\n\n // 4. If urlRecord’s scheme is \"http\", then set urlRecord’s scheme to \"ws\".\n if (urlRecord.protocol === 'http:') {\n urlRecord.protocol = 'ws:'\n } else if (urlRecord.protocol === 'https:') {\n // 5. Otherwise, if urlRecord’s scheme is \"https\", set urlRecord’s scheme to \"wss\".\n urlRecord.protocol = 'wss:'\n }\n\n // 6. If urlRecord’s scheme is not \"ws\" or \"wss\", then throw a \"SyntaxError\" DOMException.\n if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {\n throw new DOMException(\n `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,\n 'SyntaxError'\n )\n }\n\n // 7. If urlRecord’s fragment is non-null, then throw a \"SyntaxError\"\n // DOMException.\n if (urlRecord.hash || urlRecord.href.endsWith('#')) {\n throw new DOMException('Got fragment', 'SyntaxError')\n }\n\n // 8. If protocols is a string, set protocols to a sequence consisting\n // of just that string.\n if (typeof protocols === 'string') {\n protocols = [protocols]\n }\n\n // 9. If any of the values in protocols occur more than once or otherwise\n // fail to match the requirements for elements that comprise the value\n // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket\n // protocol, then throw a \"SyntaxError\" DOMException.\n if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n // 10. Set this's url to urlRecord.\n this[kWebSocketURL] = new URL(urlRecord.href)\n\n // 11. Let client be this's relevant settings object.\n\n // 12. Run this step in parallel:\n\n // 1. Establish a WebSocket connection given urlRecord, protocols,\n // and client.\n this[kController] = establishWebSocketConnection(\n urlRecord,\n protocols,\n this,\n (response) => this.#onConnectionEstablished(response),\n options\n )\n\n // Each WebSocket object has an associated ready state, which is a\n // number representing the state of the connection. Initially it must\n // be CONNECTING (0).\n this[kReadyState] = WebSocket.CONNECTING\n\n // The extensions attribute must initially return the empty string.\n\n // The protocol attribute must initially return the empty string.\n\n // Each WebSocket object has an associated binary type, which is a\n // BinaryType. Initially it must be \"blob\".\n this[kBinaryType] = 'blob'\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-close\n * @param {number|undefined} code\n * @param {string|undefined} reason\n */\n close (code = undefined, reason = undefined) {\n webidl.brandCheck(this, WebSocket)\n\n if (code !== undefined) {\n code = webidl.converters['unsigned short'](code, { clamp: true })\n }\n\n if (reason !== undefined) {\n reason = webidl.converters.USVString(reason)\n }\n\n // 1. If code is present, but is neither an integer equal to 1000 nor an\n // integer in the range 3000 to 4999, inclusive, throw an\n // \"InvalidAccessError\" DOMException.\n if (code !== undefined) {\n if (code !== 1000 && (code < 3000 || code > 4999)) {\n throw new DOMException('invalid code', 'InvalidAccessError')\n }\n }\n\n let reasonByteLength = 0\n\n // 2. If reason is present, then run these substeps:\n if (reason !== undefined) {\n // 1. Let reasonBytes be the result of encoding reason.\n // 2. If reasonBytes is longer than 123 bytes, then throw a\n // \"SyntaxError\" DOMException.\n reasonByteLength = Buffer.byteLength(reason)\n\n if (reasonByteLength > 123) {\n throw new DOMException(\n `Reason must be less than 123 bytes; received ${reasonByteLength}`,\n 'SyntaxError'\n )\n }\n }\n\n // 3. Run the first matching steps from the following list:\n if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {\n // If this's ready state is CLOSING (2) or CLOSED (3)\n // Do nothing.\n } else if (!isEstablished(this)) {\n // If the WebSocket connection is not yet established\n // Fail the WebSocket connection and set this's ready state\n // to CLOSING (2).\n failWebsocketConnection(this, 'Connection was closed before it was established.')\n this[kReadyState] = WebSocket.CLOSING\n } else if (!isClosing(this)) {\n // If the WebSocket closing handshake has not yet been started\n // Start the WebSocket closing handshake and set this's ready\n // state to CLOSING (2).\n // - If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n // - If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n // - If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n\n const frame = new WebsocketFrameSend()\n\n // If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n\n // If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n if (code !== undefined && reason === undefined) {\n frame.frameData = Buffer.allocUnsafe(2)\n frame.frameData.writeUInt16BE(code, 0)\n } else if (code !== undefined && reason !== undefined) {\n // If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)\n frame.frameData.writeUInt16BE(code, 0)\n // the body MAY contain UTF-8-encoded data with value /reason/\n frame.frameData.write(reason, 2, 'utf-8')\n } else {\n frame.frameData = emptyBuffer\n }\n\n /** @type {import('stream').Duplex} */\n const socket = this[kResponse].socket\n\n socket.write(frame.createFrame(opcodes.CLOSE), (err) => {\n if (!err) {\n this[kSentClose] = true\n }\n })\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this[kReadyState] = states.CLOSING\n } else {\n // Otherwise\n // Set this's ready state to CLOSING (2).\n this[kReadyState] = WebSocket.CLOSING\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-send\n * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data\n */\n send (data) {\n webidl.brandCheck(this, WebSocket)\n\n webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })\n\n data = webidl.converters.WebSocketSendData(data)\n\n // 1. If this's ready state is CONNECTING, then throw an\n // \"InvalidStateError\" DOMException.\n if (this[kReadyState] === WebSocket.CONNECTING) {\n throw new DOMException('Sent before connected.', 'InvalidStateError')\n }\n\n // 2. Run the appropriate set of steps from the following list:\n // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1\n // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n\n if (!isEstablished(this) || isClosing(this)) {\n return\n }\n\n /** @type {import('stream').Duplex} */\n const socket = this[kResponse].socket\n\n // If data is a string\n if (typeof data === 'string') {\n // If the WebSocket connection is established and the WebSocket\n // closing handshake has not yet started, then the user agent\n // must send a WebSocket Message comprised of the data argument\n // using a text frame opcode; if the data cannot be sent, e.g.\n // because it would need to be buffered but the buffer is full,\n // the user agent must flag the WebSocket as full and then close\n // the WebSocket connection. Any invocation of this method with a\n // string argument that does not throw an exception must increase\n // the bufferedAmount attribute by the number of bytes needed to\n // express the argument as UTF-8.\n\n const value = Buffer.from(data)\n const frame = new WebsocketFrameSend(value)\n const buffer = frame.createFrame(opcodes.TEXT)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n } else if (types.isArrayBuffer(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need\n // to be buffered but the buffer is full, the user agent must flag\n // the WebSocket as full and then close the WebSocket connection.\n // The data to be sent is the data stored in the buffer described\n // by the ArrayBuffer object. Any invocation of this method with an\n // ArrayBuffer argument that does not throw an exception must\n // increase the bufferedAmount attribute by the length of the\n // ArrayBuffer in bytes.\n\n const value = Buffer.from(data)\n const frame = new WebsocketFrameSend(value)\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n } else if (ArrayBuffer.isView(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The\n // data to be sent is the data stored in the section of the buffer\n // described by the ArrayBuffer object that data references. Any\n // invocation of this method with this kind of argument that does\n // not throw an exception must increase the bufferedAmount attribute\n // by the length of data’s buffer in bytes.\n\n const ab = Buffer.from(data, data.byteOffset, data.byteLength)\n\n const frame = new WebsocketFrameSend(ab)\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += ab.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= ab.byteLength\n })\n } else if (isBlobLike(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The data\n // to be sent is the raw data represented by the Blob object. Any\n // invocation of this method with a Blob argument that does not throw\n // an exception must increase the bufferedAmount attribute by the size\n // of the Blob object’s raw data, in bytes.\n\n const frame = new WebsocketFrameSend()\n\n data.arrayBuffer().then((ab) => {\n const value = Buffer.from(ab)\n frame.frameData = value\n const buffer = frame.createFrame(opcodes.BINARY)\n\n this.#bufferedAmount += value.byteLength\n socket.write(buffer, () => {\n this.#bufferedAmount -= value.byteLength\n })\n })\n }\n }\n\n get readyState () {\n webidl.brandCheck(this, WebSocket)\n\n // The readyState getter steps are to return this's ready state.\n return this[kReadyState]\n }\n\n get bufferedAmount () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#bufferedAmount\n }\n\n get url () {\n webidl.brandCheck(this, WebSocket)\n\n // The url getter steps are to return this's url, serialized.\n return URLSerializer(this[kWebSocketURL])\n }\n\n get extensions () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#extensions\n }\n\n get protocol () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#protocol\n }\n\n get onopen () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.open\n }\n\n set onopen (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.open) {\n this.removeEventListener('open', this.#events.open)\n }\n\n if (typeof fn === 'function') {\n this.#events.open = fn\n this.addEventListener('open', fn)\n } else {\n this.#events.open = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.error) {\n this.removeEventListener('error', this.#events.error)\n }\n\n if (typeof fn === 'function') {\n this.#events.error = fn\n this.addEventListener('error', fn)\n } else {\n this.#events.error = null\n }\n }\n\n get onclose () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.close\n }\n\n set onclose (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.close) {\n this.removeEventListener('close', this.#events.close)\n }\n\n if (typeof fn === 'function') {\n this.#events.close = fn\n this.addEventListener('close', fn)\n } else {\n this.#events.close = null\n }\n }\n\n get onmessage () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.message\n }\n\n set onmessage (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.message) {\n this.removeEventListener('message', this.#events.message)\n }\n\n if (typeof fn === 'function') {\n this.#events.message = fn\n this.addEventListener('message', fn)\n } else {\n this.#events.message = null\n }\n }\n\n get binaryType () {\n webidl.brandCheck(this, WebSocket)\n\n return this[kBinaryType]\n }\n\n set binaryType (type) {\n webidl.brandCheck(this, WebSocket)\n\n if (type !== 'blob' && type !== 'arraybuffer') {\n this[kBinaryType] = 'blob'\n } else {\n this[kBinaryType] = type\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n */\n #onConnectionEstablished (response) {\n // processResponse is called when the \"response’s header list has been received and initialized.\"\n // once this happens, the connection is open\n this[kResponse] = response\n\n const parser = new ByteParser(this)\n parser.on('drain', function onParserDrain () {\n this.ws[kResponse].socket.resume()\n })\n\n response.socket.ws = this\n this[kByteParser] = parser\n\n // 1. Change the ready state to OPEN (1).\n this[kReadyState] = states.OPEN\n\n // 2. Change the extensions attribute’s value to the extensions in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1\n const extensions = response.headersList.get('sec-websocket-extensions')\n\n if (extensions !== null) {\n this.#extensions = extensions\n }\n\n // 3. Change the protocol attribute’s value to the subprotocol in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9\n const protocol = response.headersList.get('sec-websocket-protocol')\n\n if (protocol !== null) {\n this.#protocol = protocol\n }\n\n // 4. Fire an event named open at the WebSocket object.\n fireEvent('open', this)\n }\n}\n\n// https://websockets.spec.whatwg.org/#dom-websocket-connecting\nWebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING\n// https://websockets.spec.whatwg.org/#dom-websocket-open\nWebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN\n// https://websockets.spec.whatwg.org/#dom-websocket-closing\nWebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING\n// https://websockets.spec.whatwg.org/#dom-websocket-closed\nWebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED\n\nObject.defineProperties(WebSocket.prototype, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors,\n url: kEnumerableProperty,\n readyState: kEnumerableProperty,\n bufferedAmount: kEnumerableProperty,\n onopen: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onclose: kEnumerableProperty,\n close: kEnumerableProperty,\n onmessage: kEnumerableProperty,\n binaryType: kEnumerableProperty,\n send: kEnumerableProperty,\n extensions: kEnumerableProperty,\n protocol: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'WebSocket',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(WebSocket, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors\n})\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.DOMString\n)\n\nwebidl.converters['DOMString or sequence'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {\n return webidl.converters['sequence'](V)\n }\n\n return webidl.converters.DOMString(V)\n}\n\n// This implements the propsal made in https://github.com/whatwg/websockets/issues/42\nwebidl.converters.WebSocketInit = webidl.dictionaryConverter([\n {\n key: 'protocols',\n converter: webidl.converters['DOMString or sequence'],\n get defaultValue () {\n return []\n }\n },\n {\n key: 'dispatcher',\n converter: (V) => V,\n get defaultValue () {\n return getGlobalDispatcher()\n }\n },\n {\n key: 'headers',\n converter: webidl.nullableConverter(webidl.converters.HeadersInit)\n }\n])\n\nwebidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {\n return webidl.converters.WebSocketInit(V)\n }\n\n return { protocols: webidl.converters['DOMString or sequence'](V) }\n}\n\nwebidl.converters.WebSocketSendData = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {\n return webidl.converters.BufferSource(V)\n }\n }\n\n return webidl.converters.USVString(V)\n}\n\nmodule.exports = {\n WebSocket\n}\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n\n return \"\";\n}\n\nexports.getUserAgent = getUserAgent;\n//# sourceMappingURL=index.js.map\n","// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"assert\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"async_hooks\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"buffer\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"child_process\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"console\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"crypto\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"diagnostics_channel\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"events\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"fs\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"http\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"http2\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"https\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"net\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"node:crypto\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"node:events\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"node:stream\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"node:util\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"os\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"path\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"perf_hooks\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"querystring\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"stream\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"stream/web\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"string_decoder\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"timers\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"tls\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"url\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"util\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"util/types\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"worker_threads\");","module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"zlib\");","'use strict'\n\nconst WritableStream = require('node:stream').Writable\nconst inherits = require('node:util').inherits\n\nconst StreamSearch = require('../../streamsearch/sbmh')\n\nconst PartStream = require('./PartStream')\nconst HeaderParser = require('./HeaderParser')\n\nconst DASH = 45\nconst B_ONEDASH = Buffer.from('-')\nconst B_CRLF = Buffer.from('\\r\\n')\nconst EMPTY_FN = function () {}\n\nfunction Dicer (cfg) {\n if (!(this instanceof Dicer)) { return new Dicer(cfg) }\n WritableStream.call(this, cfg)\n\n if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }\n\n if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }\n\n this._headerFirst = cfg.headerFirst\n\n this._dashes = 0\n this._parts = 0\n this._finished = false\n this._realFinish = false\n this._isPreamble = true\n this._justMatched = false\n this._firstWrite = true\n this._inHeader = true\n this._part = undefined\n this._cb = undefined\n this._ignoreData = false\n this._partOpts = { highWaterMark: cfg.partHwm }\n this._pause = false\n\n const self = this\n this._hparser = new HeaderParser(cfg)\n this._hparser.on('header', function (header) {\n self._inHeader = false\n self._part.emit('header', header)\n })\n}\ninherits(Dicer, WritableStream)\n\nDicer.prototype.emit = function (ev) {\n if (ev === 'finish' && !this._realFinish) {\n if (!this._finished) {\n const self = this\n process.nextTick(function () {\n self.emit('error', new Error('Unexpected end of multipart data'))\n if (self._part && !self._ignoreData) {\n const type = (self._isPreamble ? 'Preamble' : 'Part')\n self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))\n self._part.push(null)\n process.nextTick(function () {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n })\n return\n }\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n })\n }\n } else { WritableStream.prototype.emit.apply(this, arguments) }\n}\n\nDicer.prototype._write = function (data, encoding, cb) {\n // ignore unexpected data (e.g. extra trailer data after finished)\n if (!this._hparser && !this._bparser) { return cb() }\n\n if (this._headerFirst && this._isPreamble) {\n if (!this._part) {\n this._part = new PartStream(this._partOpts)\n if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() }\n }\n const r = this._hparser.push(data)\n if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }\n }\n\n // allows for \"easier\" testing\n if (this._firstWrite) {\n this._bparser.push(B_CRLF)\n this._firstWrite = false\n }\n\n this._bparser.push(data)\n\n if (this._pause) { this._cb = cb } else { cb() }\n}\n\nDicer.prototype.reset = function () {\n this._part = undefined\n this._bparser = undefined\n this._hparser = undefined\n}\n\nDicer.prototype.setBoundary = function (boundary) {\n const self = this\n this._bparser = new StreamSearch('\\r\\n--' + boundary)\n this._bparser.on('info', function (isMatch, data, start, end) {\n self._oninfo(isMatch, data, start, end)\n })\n}\n\nDicer.prototype._ignore = function () {\n if (this._part && !this._ignoreData) {\n this._ignoreData = true\n this._part.on('error', EMPTY_FN)\n // we must perform some kind of read on the stream even though we are\n // ignoring the data, otherwise node's Readable stream will not emit 'end'\n // after pushing null to the stream\n this._part.resume()\n }\n}\n\nDicer.prototype._oninfo = function (isMatch, data, start, end) {\n let buf; const self = this; let i = 0; let r; let shouldWriteMore = true\n\n if (!this._part && this._justMatched && data) {\n while (this._dashes < 2 && (start + i) < end) {\n if (data[start + i] === DASH) {\n ++i\n ++this._dashes\n } else {\n if (this._dashes) { buf = B_ONEDASH }\n this._dashes = 0\n break\n }\n }\n if (this._dashes === 2) {\n if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) }\n this.reset()\n this._finished = true\n // no more parts will be added\n if (self._parts === 0) {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n }\n }\n if (this._dashes) { return }\n }\n if (this._justMatched) { this._justMatched = false }\n if (!this._part) {\n this._part = new PartStream(this._partOpts)\n this._part._read = function (n) {\n self._unpause()\n }\n if (this._isPreamble && this.listenerCount('preamble') !== 0) {\n this.emit('preamble', this._part)\n } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {\n this.emit('part', this._part)\n } else {\n this._ignore()\n }\n if (!this._isPreamble) { this._inHeader = true }\n }\n if (data && start < end && !this._ignoreData) {\n if (this._isPreamble || !this._inHeader) {\n if (buf) { shouldWriteMore = this._part.push(buf) }\n shouldWriteMore = this._part.push(data.slice(start, end))\n if (!shouldWriteMore) { this._pause = true }\n } else if (!this._isPreamble && this._inHeader) {\n if (buf) { this._hparser.push(buf) }\n r = this._hparser.push(data.slice(start, end))\n if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }\n }\n }\n if (isMatch) {\n this._hparser.reset()\n if (this._isPreamble) { this._isPreamble = false } else {\n if (start !== end) {\n ++this._parts\n this._part.on('end', function () {\n if (--self._parts === 0) {\n if (self._finished) {\n self._realFinish = true\n self.emit('finish')\n self._realFinish = false\n } else {\n self._unpause()\n }\n }\n })\n }\n }\n this._part.push(null)\n this._part = undefined\n this._ignoreData = false\n this._justMatched = true\n this._dashes = 0\n }\n}\n\nDicer.prototype._unpause = function () {\n if (!this._pause) { return }\n\n this._pause = false\n if (this._cb) {\n const cb = this._cb\n this._cb = undefined\n cb()\n }\n}\n\nmodule.exports = Dicer\n","'use strict'\n\nconst EventEmitter = require('node:events').EventEmitter\nconst inherits = require('node:util').inherits\nconst getLimit = require('../../../lib/utils/getLimit')\n\nconst StreamSearch = require('../../streamsearch/sbmh')\n\nconst B_DCRLF = Buffer.from('\\r\\n\\r\\n')\nconst RE_CRLF = /\\r\\n/g\nconst RE_HDR = /^([^:]+):[ \\t]?([\\x00-\\xFF]+)?$/ // eslint-disable-line no-control-regex\n\nfunction HeaderParser (cfg) {\n EventEmitter.call(this)\n\n cfg = cfg || {}\n const self = this\n this.nread = 0\n this.maxed = false\n this.npairs = 0\n this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)\n this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)\n this.buffer = ''\n this.header = {}\n this.finished = false\n this.ss = new StreamSearch(B_DCRLF)\n this.ss.on('info', function (isMatch, data, start, end) {\n if (data && !self.maxed) {\n if (self.nread + end - start >= self.maxHeaderSize) {\n end = self.maxHeaderSize - self.nread + start\n self.nread = self.maxHeaderSize\n self.maxed = true\n } else { self.nread += (end - start) }\n\n self.buffer += data.toString('binary', start, end)\n }\n if (isMatch) { self._finish() }\n })\n}\ninherits(HeaderParser, EventEmitter)\n\nHeaderParser.prototype.push = function (data) {\n const r = this.ss.push(data)\n if (this.finished) { return r }\n}\n\nHeaderParser.prototype.reset = function () {\n this.finished = false\n this.buffer = ''\n this.header = {}\n this.ss.reset()\n}\n\nHeaderParser.prototype._finish = function () {\n if (this.buffer) { this._parseHeader() }\n this.ss.matches = this.ss.maxMatches\n const header = this.header\n this.header = {}\n this.buffer = ''\n this.finished = true\n this.nread = this.npairs = 0\n this.maxed = false\n this.emit('header', header)\n}\n\nHeaderParser.prototype._parseHeader = function () {\n if (this.npairs === this.maxHeaderPairs) { return }\n\n const lines = this.buffer.split(RE_CRLF)\n const len = lines.length\n let m, h\n\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n if (lines[i].length === 0) { continue }\n if (lines[i][0] === '\\t' || lines[i][0] === ' ') {\n // folded header content\n // RFC2822 says to just remove the CRLF and not the whitespace following\n // it, so we follow the RFC and include the leading whitespace ...\n if (h) {\n this.header[h][this.header[h].length - 1] += lines[i]\n continue\n }\n }\n\n const posColon = lines[i].indexOf(':')\n if (\n posColon === -1 ||\n posColon === 0\n ) {\n return\n }\n m = RE_HDR.exec(lines[i])\n h = m[1].toLowerCase()\n this.header[h] = this.header[h] || []\n this.header[h].push((m[2] || ''))\n if (++this.npairs === this.maxHeaderPairs) { break }\n }\n}\n\nmodule.exports = HeaderParser\n","'use strict'\n\nconst inherits = require('node:util').inherits\nconst ReadableStream = require('node:stream').Readable\n\nfunction PartStream (opts) {\n ReadableStream.call(this, opts)\n}\ninherits(PartStream, ReadableStream)\n\nPartStream.prototype._read = function (n) {}\n\nmodule.exports = PartStream\n","'use strict'\n\n/**\n * Copyright Brian White. All rights reserved.\n *\n * @see https://github.com/mscdex/streamsearch\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation\n * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool\n */\nconst EventEmitter = require('node:events').EventEmitter\nconst inherits = require('node:util').inherits\n\nfunction SBMH (needle) {\n if (typeof needle === 'string') {\n needle = Buffer.from(needle)\n }\n\n if (!Buffer.isBuffer(needle)) {\n throw new TypeError('The needle has to be a String or a Buffer.')\n }\n\n const needleLength = needle.length\n\n if (needleLength === 0) {\n throw new Error('The needle cannot be an empty String/Buffer.')\n }\n\n if (needleLength > 256) {\n throw new Error('The needle cannot have a length bigger than 256.')\n }\n\n this.maxMatches = Infinity\n this.matches = 0\n\n this._occ = new Array(256)\n .fill(needleLength) // Initialize occurrence table.\n this._lookbehind_size = 0\n this._needle = needle\n this._bufpos = 0\n\n this._lookbehind = Buffer.alloc(needleLength)\n\n // Populate occurrence table with analysis of the needle,\n // ignoring last letter.\n for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var\n this._occ[needle[i]] = needleLength - 1 - i\n }\n}\ninherits(SBMH, EventEmitter)\n\nSBMH.prototype.reset = function () {\n this._lookbehind_size = 0\n this.matches = 0\n this._bufpos = 0\n}\n\nSBMH.prototype.push = function (chunk, pos) {\n if (!Buffer.isBuffer(chunk)) {\n chunk = Buffer.from(chunk, 'binary')\n }\n const chlen = chunk.length\n this._bufpos = pos || 0\n let r\n while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }\n return r\n}\n\nSBMH.prototype._sbmh_feed = function (data) {\n const len = data.length\n const needle = this._needle\n const needleLength = needle.length\n const lastNeedleChar = needle[needleLength - 1]\n\n // Positive: points to a position in `data`\n // pos == 3 points to data[3]\n // Negative: points to a position in the lookbehind buffer\n // pos == -2 points to lookbehind[lookbehind_size - 2]\n let pos = -this._lookbehind_size\n let ch\n\n if (pos < 0) {\n // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool\n // search with character lookup code that considers both the\n // lookbehind buffer and the current round's haystack data.\n //\n // Loop until\n // there is a match.\n // or until\n // we've moved past the position that requires the\n // lookbehind buffer. In this case we switch to the\n // optimized loop.\n // or until\n // the character to look at lies outside the haystack.\n while (pos < 0 && pos <= len - needleLength) {\n ch = this._sbmh_lookup_char(data, pos + needleLength - 1)\n\n if (\n ch === lastNeedleChar &&\n this._sbmh_memcmp(data, pos, needleLength - 1)\n ) {\n this._lookbehind_size = 0\n ++this.matches\n this.emit('info', true)\n\n return (this._bufpos = pos + needleLength)\n }\n pos += this._occ[ch]\n }\n\n // No match.\n\n if (pos < 0) {\n // There's too few data for Boyer-Moore-Horspool to run,\n // so let's use a different algorithm to skip as much as\n // we can.\n // Forward pos until\n // the trailing part of lookbehind + data\n // looks like the beginning of the needle\n // or until\n // pos == 0\n while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }\n }\n\n if (pos >= 0) {\n // Discard lookbehind buffer.\n this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)\n this._lookbehind_size = 0\n } else {\n // Cut off part of the lookbehind buffer that has\n // been processed and append the entire haystack\n // into it.\n const bytesToCutOff = this._lookbehind_size + pos\n if (bytesToCutOff > 0) {\n // The cut off data is guaranteed not to contain the needle.\n this.emit('info', false, this._lookbehind, 0, bytesToCutOff)\n }\n\n this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,\n this._lookbehind_size - bytesToCutOff)\n this._lookbehind_size -= bytesToCutOff\n\n data.copy(this._lookbehind, this._lookbehind_size)\n this._lookbehind_size += len\n\n this._bufpos = len\n return len\n }\n }\n\n pos += (pos >= 0) * this._bufpos\n\n // Lookbehind buffer is now empty. We only need to check if the\n // needle is in the haystack.\n if (data.indexOf(needle, pos) !== -1) {\n pos = data.indexOf(needle, pos)\n ++this.matches\n if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }\n\n return (this._bufpos = pos + needleLength)\n } else {\n pos = len - needleLength\n }\n\n // There was no match. If there's trailing haystack data that we cannot\n // match yet using the Boyer-Moore-Horspool algorithm (because the trailing\n // data is less than the needle size) then match using a modified\n // algorithm that starts matching from the beginning instead of the end.\n // Whatever trailing data is left after running this algorithm is added to\n // the lookbehind buffer.\n while (\n pos < len &&\n (\n data[pos] !== needle[0] ||\n (\n (Buffer.compare(\n data.subarray(pos, pos + len - pos),\n needle.subarray(0, len - pos)\n ) !== 0)\n )\n )\n ) {\n ++pos\n }\n if (pos < len) {\n data.copy(this._lookbehind, 0, pos, pos + (len - pos))\n this._lookbehind_size = len - pos\n }\n\n // Everything until pos is guaranteed not to contain needle data.\n if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }\n\n this._bufpos = len\n return len\n}\n\nSBMH.prototype._sbmh_lookup_char = function (data, pos) {\n return (pos < 0)\n ? this._lookbehind[this._lookbehind_size + pos]\n : data[pos]\n}\n\nSBMH.prototype._sbmh_memcmp = function (data, pos, len) {\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }\n }\n return true\n}\n\nmodule.exports = SBMH\n","'use strict'\n\nconst WritableStream = require('node:stream').Writable\nconst { inherits } = require('node:util')\nconst Dicer = require('../deps/dicer/lib/Dicer')\n\nconst MultipartParser = require('./types/multipart')\nconst UrlencodedParser = require('./types/urlencoded')\nconst parseParams = require('./utils/parseParams')\n\nfunction Busboy (opts) {\n if (!(this instanceof Busboy)) { return new Busboy(opts) }\n\n if (typeof opts !== 'object') {\n throw new TypeError('Busboy expected an options-Object.')\n }\n if (typeof opts.headers !== 'object') {\n throw new TypeError('Busboy expected an options-Object with headers-attribute.')\n }\n if (typeof opts.headers['content-type'] !== 'string') {\n throw new TypeError('Missing Content-Type-header.')\n }\n\n const {\n headers,\n ...streamOptions\n } = opts\n\n this.opts = {\n autoDestroy: false,\n ...streamOptions\n }\n WritableStream.call(this, this.opts)\n\n this._done = false\n this._parser = this.getParserByHeaders(headers)\n this._finished = false\n}\ninherits(Busboy, WritableStream)\n\nBusboy.prototype.emit = function (ev) {\n if (ev === 'finish') {\n if (!this._done) {\n this._parser?.end()\n return\n } else if (this._finished) {\n return\n }\n this._finished = true\n }\n WritableStream.prototype.emit.apply(this, arguments)\n}\n\nBusboy.prototype.getParserByHeaders = function (headers) {\n const parsed = parseParams(headers['content-type'])\n\n const cfg = {\n defCharset: this.opts.defCharset,\n fileHwm: this.opts.fileHwm,\n headers,\n highWaterMark: this.opts.highWaterMark,\n isPartAFile: this.opts.isPartAFile,\n limits: this.opts.limits,\n parsedConType: parsed,\n preservePath: this.opts.preservePath\n }\n\n if (MultipartParser.detect.test(parsed[0])) {\n return new MultipartParser(this, cfg)\n }\n if (UrlencodedParser.detect.test(parsed[0])) {\n return new UrlencodedParser(this, cfg)\n }\n throw new Error('Unsupported Content-Type.')\n}\n\nBusboy.prototype._write = function (chunk, encoding, cb) {\n this._parser.write(chunk, cb)\n}\n\nmodule.exports = Busboy\nmodule.exports.default = Busboy\nmodule.exports.Busboy = Busboy\n\nmodule.exports.Dicer = Dicer\n","'use strict'\n\n// TODO:\n// * support 1 nested multipart level\n// (see second multipart example here:\n// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)\n// * support limits.fieldNameSize\n// -- this will require modifications to utils.parseParams\n\nconst { Readable } = require('node:stream')\nconst { inherits } = require('node:util')\n\nconst Dicer = require('../../deps/dicer/lib/Dicer')\n\nconst parseParams = require('../utils/parseParams')\nconst decodeText = require('../utils/decodeText')\nconst basename = require('../utils/basename')\nconst getLimit = require('../utils/getLimit')\n\nconst RE_BOUNDARY = /^boundary$/i\nconst RE_FIELD = /^form-data$/i\nconst RE_CHARSET = /^charset$/i\nconst RE_FILENAME = /^filename$/i\nconst RE_NAME = /^name$/i\n\nMultipart.detect = /^multipart\\/form-data/i\nfunction Multipart (boy, cfg) {\n let i\n let len\n const self = this\n let boundary\n const limits = cfg.limits\n const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))\n const parsedConType = cfg.parsedConType || []\n const defCharset = cfg.defCharset || 'utf8'\n const preservePath = cfg.preservePath\n const fileOpts = { highWaterMark: cfg.fileHwm }\n\n for (i = 0, len = parsedConType.length; i < len; ++i) {\n if (Array.isArray(parsedConType[i]) &&\n RE_BOUNDARY.test(parsedConType[i][0])) {\n boundary = parsedConType[i][1]\n break\n }\n }\n\n function checkFinished () {\n if (nends === 0 && finished && !boy._done) {\n finished = false\n self.end()\n }\n }\n\n if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }\n\n const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)\n const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)\n const filesLimit = getLimit(limits, 'files', Infinity)\n const fieldsLimit = getLimit(limits, 'fields', Infinity)\n const partsLimit = getLimit(limits, 'parts', Infinity)\n const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)\n const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)\n\n let nfiles = 0\n let nfields = 0\n let nends = 0\n let curFile\n let curField\n let finished = false\n\n this._needDrain = false\n this._pause = false\n this._cb = undefined\n this._nparts = 0\n this._boy = boy\n\n const parserCfg = {\n boundary,\n maxHeaderPairs: headerPairsLimit,\n maxHeaderSize: headerSizeLimit,\n partHwm: fileOpts.highWaterMark,\n highWaterMark: cfg.highWaterMark\n }\n\n this.parser = new Dicer(parserCfg)\n this.parser.on('drain', function () {\n self._needDrain = false\n if (self._cb && !self._pause) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n }).on('part', function onPart (part) {\n if (++self._nparts > partsLimit) {\n self.parser.removeListener('part', onPart)\n self.parser.on('part', skipPart)\n boy.hitPartsLimit = true\n boy.emit('partsLimit')\n return skipPart(part)\n }\n\n // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let\n // us emit 'end' early since we know the part has ended if we are already\n // seeing the next part\n if (curField) {\n const field = curField\n field.emit('end')\n field.removeAllListeners('end')\n }\n\n part.on('header', function (header) {\n let contype\n let fieldname\n let parsed\n let charset\n let encoding\n let filename\n let nsize = 0\n\n if (header['content-type']) {\n parsed = parseParams(header['content-type'][0])\n if (parsed[0]) {\n contype = parsed[0].toLowerCase()\n for (i = 0, len = parsed.length; i < len; ++i) {\n if (RE_CHARSET.test(parsed[i][0])) {\n charset = parsed[i][1].toLowerCase()\n break\n }\n }\n }\n }\n\n if (contype === undefined) { contype = 'text/plain' }\n if (charset === undefined) { charset = defCharset }\n\n if (header['content-disposition']) {\n parsed = parseParams(header['content-disposition'][0])\n if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }\n for (i = 0, len = parsed.length; i < len; ++i) {\n if (RE_NAME.test(parsed[i][0])) {\n fieldname = parsed[i][1]\n } else if (RE_FILENAME.test(parsed[i][0])) {\n filename = parsed[i][1]\n if (!preservePath) { filename = basename(filename) }\n }\n }\n } else { return skipPart(part) }\n\n if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }\n\n let onData,\n onEnd\n\n if (isPartAFile(fieldname, contype, filename)) {\n // file/binary field\n if (nfiles === filesLimit) {\n if (!boy.hitFilesLimit) {\n boy.hitFilesLimit = true\n boy.emit('filesLimit')\n }\n return skipPart(part)\n }\n\n ++nfiles\n\n if (boy.listenerCount('file') === 0) {\n self.parser._ignore()\n return\n }\n\n ++nends\n const file = new FileStream(fileOpts)\n curFile = file\n file.on('end', function () {\n --nends\n self._pause = false\n checkFinished()\n if (self._cb && !self._needDrain) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n })\n file._read = function (n) {\n if (!self._pause) { return }\n self._pause = false\n if (self._cb && !self._needDrain) {\n const cb = self._cb\n self._cb = undefined\n cb()\n }\n }\n boy.emit('file', fieldname, file, filename, encoding, contype)\n\n onData = function (data) {\n if ((nsize += data.length) > fileSizeLimit) {\n const extralen = fileSizeLimit - nsize + data.length\n if (extralen > 0) { file.push(data.slice(0, extralen)) }\n file.truncated = true\n file.bytesRead = fileSizeLimit\n part.removeAllListeners('data')\n file.emit('limit')\n return\n } else if (!file.push(data)) { self._pause = true }\n\n file.bytesRead = nsize\n }\n\n onEnd = function () {\n curFile = undefined\n file.push(null)\n }\n } else {\n // non-file field\n if (nfields === fieldsLimit) {\n if (!boy.hitFieldsLimit) {\n boy.hitFieldsLimit = true\n boy.emit('fieldsLimit')\n }\n return skipPart(part)\n }\n\n ++nfields\n ++nends\n let buffer = ''\n let truncated = false\n curField = part\n\n onData = function (data) {\n if ((nsize += data.length) > fieldSizeLimit) {\n const extralen = (fieldSizeLimit - (nsize - data.length))\n buffer += data.toString('binary', 0, extralen)\n truncated = true\n part.removeAllListeners('data')\n } else { buffer += data.toString('binary') }\n }\n\n onEnd = function () {\n curField = undefined\n if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }\n boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)\n --nends\n checkFinished()\n }\n }\n\n /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become\n broken. Streams2/streams3 is a huge black box of confusion, but\n somehow overriding the sync state seems to fix things again (and still\n seems to work for previous node versions).\n */\n part._readableState.sync = false\n\n part.on('data', onData)\n part.on('end', onEnd)\n }).on('error', function (err) {\n if (curFile) { curFile.emit('error', err) }\n })\n }).on('error', function (err) {\n boy.emit('error', err)\n }).on('finish', function () {\n finished = true\n checkFinished()\n })\n}\n\nMultipart.prototype.write = function (chunk, cb) {\n const r = this.parser.write(chunk)\n if (r && !this._pause) {\n cb()\n } else {\n this._needDrain = !r\n this._cb = cb\n }\n}\n\nMultipart.prototype.end = function () {\n const self = this\n\n if (self.parser.writable) {\n self.parser.end()\n } else if (!self._boy._done) {\n process.nextTick(function () {\n self._boy._done = true\n self._boy.emit('finish')\n })\n }\n}\n\nfunction skipPart (part) {\n part.resume()\n}\n\nfunction FileStream (opts) {\n Readable.call(this, opts)\n\n this.bytesRead = 0\n\n this.truncated = false\n}\n\ninherits(FileStream, Readable)\n\nFileStream.prototype._read = function (n) {}\n\nmodule.exports = Multipart\n","'use strict'\n\nconst Decoder = require('../utils/Decoder')\nconst decodeText = require('../utils/decodeText')\nconst getLimit = require('../utils/getLimit')\n\nconst RE_CHARSET = /^charset$/i\n\nUrlEncoded.detect = /^application\\/x-www-form-urlencoded/i\nfunction UrlEncoded (boy, cfg) {\n const limits = cfg.limits\n const parsedConType = cfg.parsedConType\n this.boy = boy\n\n this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)\n this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)\n this.fieldsLimit = getLimit(limits, 'fields', Infinity)\n\n let charset\n for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var\n if (Array.isArray(parsedConType[i]) &&\n RE_CHARSET.test(parsedConType[i][0])) {\n charset = parsedConType[i][1].toLowerCase()\n break\n }\n }\n\n if (charset === undefined) { charset = cfg.defCharset || 'utf8' }\n\n this.decoder = new Decoder()\n this.charset = charset\n this._fields = 0\n this._state = 'key'\n this._checkingBytes = true\n this._bytesKey = 0\n this._bytesVal = 0\n this._key = ''\n this._val = ''\n this._keyTrunc = false\n this._valTrunc = false\n this._hitLimit = false\n}\n\nUrlEncoded.prototype.write = function (data, cb) {\n if (this._fields === this.fieldsLimit) {\n if (!this.boy.hitFieldsLimit) {\n this.boy.hitFieldsLimit = true\n this.boy.emit('fieldsLimit')\n }\n return cb()\n }\n\n let idxeq; let idxamp; let i; let p = 0; const len = data.length\n\n while (p < len) {\n if (this._state === 'key') {\n idxeq = idxamp = undefined\n for (i = p; i < len; ++i) {\n if (!this._checkingBytes) { ++p }\n if (data[i] === 0x3D/* = */) {\n idxeq = i\n break\n } else if (data[i] === 0x26/* & */) {\n idxamp = i\n break\n }\n if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {\n this._hitLimit = true\n break\n } else if (this._checkingBytes) { ++this._bytesKey }\n }\n\n if (idxeq !== undefined) {\n // key with assignment\n if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }\n this._state = 'val'\n\n this._hitLimit = false\n this._checkingBytes = true\n this._val = ''\n this._bytesVal = 0\n this._valTrunc = false\n this.decoder.reset()\n\n p = idxeq + 1\n } else if (idxamp !== undefined) {\n // key with no assignment\n ++this._fields\n let key; const keyTrunc = this._keyTrunc\n if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }\n\n this._hitLimit = false\n this._checkingBytes = true\n this._key = ''\n this._bytesKey = 0\n this._keyTrunc = false\n this.decoder.reset()\n\n if (key.length) {\n this.boy.emit('field', decodeText(key, 'binary', this.charset),\n '',\n keyTrunc,\n false)\n }\n\n p = idxamp + 1\n if (this._fields === this.fieldsLimit) { return cb() }\n } else if (this._hitLimit) {\n // we may not have hit the actual limit if there are encoded bytes...\n if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }\n p = i\n if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {\n // yep, we actually did hit the limit\n this._checkingBytes = false\n this._keyTrunc = true\n }\n } else {\n if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }\n p = len\n }\n } else {\n idxamp = undefined\n for (i = p; i < len; ++i) {\n if (!this._checkingBytes) { ++p }\n if (data[i] === 0x26/* & */) {\n idxamp = i\n break\n }\n if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {\n this._hitLimit = true\n break\n } else if (this._checkingBytes) { ++this._bytesVal }\n }\n\n if (idxamp !== undefined) {\n ++this._fields\n if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n decodeText(this._val, 'binary', this.charset),\n this._keyTrunc,\n this._valTrunc)\n this._state = 'key'\n\n this._hitLimit = false\n this._checkingBytes = true\n this._key = ''\n this._bytesKey = 0\n this._keyTrunc = false\n this.decoder.reset()\n\n p = idxamp + 1\n if (this._fields === this.fieldsLimit) { return cb() }\n } else if (this._hitLimit) {\n // we may not have hit the actual limit if there are encoded bytes...\n if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }\n p = i\n if ((this._val === '' && this.fieldSizeLimit === 0) ||\n (this._bytesVal = this._val.length) === this.fieldSizeLimit) {\n // yep, we actually did hit the limit\n this._checkingBytes = false\n this._valTrunc = true\n }\n } else {\n if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }\n p = len\n }\n }\n }\n cb()\n}\n\nUrlEncoded.prototype.end = function () {\n if (this.boy._done) { return }\n\n if (this._state === 'key' && this._key.length > 0) {\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n '',\n this._keyTrunc,\n false)\n } else if (this._state === 'val') {\n this.boy.emit('field', decodeText(this._key, 'binary', this.charset),\n decodeText(this._val, 'binary', this.charset),\n this._keyTrunc,\n this._valTrunc)\n }\n this.boy._done = true\n this.boy.emit('finish')\n}\n\nmodule.exports = UrlEncoded\n","'use strict'\n\nconst RE_PLUS = /\\+/g\n\nconst HEX = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n]\n\nfunction Decoder () {\n this.buffer = undefined\n}\nDecoder.prototype.write = function (str) {\n // Replace '+' with ' ' before decoding\n str = str.replace(RE_PLUS, ' ')\n let res = ''\n let i = 0; let p = 0; const len = str.length\n for (; i < len; ++i) {\n if (this.buffer !== undefined) {\n if (!HEX[str.charCodeAt(i)]) {\n res += '%' + this.buffer\n this.buffer = undefined\n --i // retry character\n } else {\n this.buffer += str[i]\n ++p\n if (this.buffer.length === 2) {\n res += String.fromCharCode(parseInt(this.buffer, 16))\n this.buffer = undefined\n }\n }\n } else if (str[i] === '%') {\n if (i > p) {\n res += str.substring(p, i)\n p = i\n }\n this.buffer = ''\n ++p\n }\n }\n if (p < len && this.buffer === undefined) { res += str.substring(p) }\n return res\n}\nDecoder.prototype.reset = function () {\n this.buffer = undefined\n}\n\nmodule.exports = Decoder\n","'use strict'\n\nmodule.exports = function basename (path) {\n if (typeof path !== 'string') { return '' }\n for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var\n switch (path.charCodeAt(i)) {\n case 0x2F: // '/'\n case 0x5C: // '\\'\n path = path.slice(i + 1)\n return (path === '..' || path === '.' ? '' : path)\n }\n }\n return (path === '..' || path === '.' ? '' : path)\n}\n","'use strict'\n\n// Node has always utf-8\nconst utf8Decoder = new TextDecoder('utf-8')\nconst textDecoders = new Map([\n ['utf-8', utf8Decoder],\n ['utf8', utf8Decoder]\n])\n\nfunction getDecoder (charset) {\n let lc\n while (true) {\n switch (charset) {\n case 'utf-8':\n case 'utf8':\n return decoders.utf8\n case 'latin1':\n case 'ascii': // TODO: Make these a separate, strict decoder?\n case 'us-ascii':\n case 'iso-8859-1':\n case 'iso8859-1':\n case 'iso88591':\n case 'iso_8859-1':\n case 'windows-1252':\n case 'iso_8859-1:1987':\n case 'cp1252':\n case 'x-cp1252':\n return decoders.latin1\n case 'utf16le':\n case 'utf-16le':\n case 'ucs2':\n case 'ucs-2':\n return decoders.utf16le\n case 'base64':\n return decoders.base64\n default:\n if (lc === undefined) {\n lc = true\n charset = charset.toLowerCase()\n continue\n }\n return decoders.other.bind(charset)\n }\n }\n}\n\nconst decoders = {\n utf8: (data, sourceEncoding) => {\n if (data.length === 0) {\n return ''\n }\n if (typeof data === 'string') {\n data = Buffer.from(data, sourceEncoding)\n }\n return data.utf8Slice(0, data.length)\n },\n\n latin1: (data, sourceEncoding) => {\n if (data.length === 0) {\n return ''\n }\n if (typeof data === 'string') {\n return data\n }\n return data.latin1Slice(0, data.length)\n },\n\n utf16le: (data, sourceEncoding) => {\n if (data.length === 0) {\n return ''\n }\n if (typeof data === 'string') {\n data = Buffer.from(data, sourceEncoding)\n }\n return data.ucs2Slice(0, data.length)\n },\n\n base64: (data, sourceEncoding) => {\n if (data.length === 0) {\n return ''\n }\n if (typeof data === 'string') {\n data = Buffer.from(data, sourceEncoding)\n }\n return data.base64Slice(0, data.length)\n },\n\n other: (data, sourceEncoding) => {\n if (data.length === 0) {\n return ''\n }\n if (typeof data === 'string') {\n data = Buffer.from(data, sourceEncoding)\n }\n\n if (textDecoders.has(this.toString())) {\n try {\n return textDecoders.get(this).decode(data)\n } catch {}\n }\n return typeof data === 'string'\n ? data\n : data.toString()\n }\n}\n\nfunction decodeText (text, sourceEncoding, destEncoding) {\n if (text) {\n return getDecoder(destEncoding)(text, sourceEncoding)\n }\n return text\n}\n\nmodule.exports = decodeText\n","'use strict'\n\nmodule.exports = function getLimit (limits, name, defaultLimit) {\n if (\n !limits ||\n limits[name] === undefined ||\n limits[name] === null\n ) { return defaultLimit }\n\n if (\n typeof limits[name] !== 'number' ||\n isNaN(limits[name])\n ) { throw new TypeError('Limit ' + name + ' is not a valid number') }\n\n return limits[name]\n}\n","/* eslint-disable object-property-newline */\n'use strict'\n\nconst decodeText = require('./decodeText')\n\nconst RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g\n\nconst EncodedLookup = {\n '%00': '\\x00', '%01': '\\x01', '%02': '\\x02', '%03': '\\x03', '%04': '\\x04',\n '%05': '\\x05', '%06': '\\x06', '%07': '\\x07', '%08': '\\x08', '%09': '\\x09',\n '%0a': '\\x0a', '%0A': '\\x0a', '%0b': '\\x0b', '%0B': '\\x0b', '%0c': '\\x0c',\n '%0C': '\\x0c', '%0d': '\\x0d', '%0D': '\\x0d', '%0e': '\\x0e', '%0E': '\\x0e',\n '%0f': '\\x0f', '%0F': '\\x0f', '%10': '\\x10', '%11': '\\x11', '%12': '\\x12',\n '%13': '\\x13', '%14': '\\x14', '%15': '\\x15', '%16': '\\x16', '%17': '\\x17',\n '%18': '\\x18', '%19': '\\x19', '%1a': '\\x1a', '%1A': '\\x1a', '%1b': '\\x1b',\n '%1B': '\\x1b', '%1c': '\\x1c', '%1C': '\\x1c', '%1d': '\\x1d', '%1D': '\\x1d',\n '%1e': '\\x1e', '%1E': '\\x1e', '%1f': '\\x1f', '%1F': '\\x1f', '%20': '\\x20',\n '%21': '\\x21', '%22': '\\x22', '%23': '\\x23', '%24': '\\x24', '%25': '\\x25',\n '%26': '\\x26', '%27': '\\x27', '%28': '\\x28', '%29': '\\x29', '%2a': '\\x2a',\n '%2A': '\\x2a', '%2b': '\\x2b', '%2B': '\\x2b', '%2c': '\\x2c', '%2C': '\\x2c',\n '%2d': '\\x2d', '%2D': '\\x2d', '%2e': '\\x2e', '%2E': '\\x2e', '%2f': '\\x2f',\n '%2F': '\\x2f', '%30': '\\x30', '%31': '\\x31', '%32': '\\x32', '%33': '\\x33',\n '%34': '\\x34', '%35': '\\x35', '%36': '\\x36', '%37': '\\x37', '%38': '\\x38',\n '%39': '\\x39', '%3a': '\\x3a', '%3A': '\\x3a', '%3b': '\\x3b', '%3B': '\\x3b',\n '%3c': '\\x3c', '%3C': '\\x3c', '%3d': '\\x3d', '%3D': '\\x3d', '%3e': '\\x3e',\n '%3E': '\\x3e', '%3f': '\\x3f', '%3F': '\\x3f', '%40': '\\x40', '%41': '\\x41',\n '%42': '\\x42', '%43': '\\x43', '%44': '\\x44', '%45': '\\x45', '%46': '\\x46',\n '%47': '\\x47', '%48': '\\x48', '%49': '\\x49', '%4a': '\\x4a', '%4A': '\\x4a',\n '%4b': '\\x4b', '%4B': '\\x4b', '%4c': '\\x4c', '%4C': '\\x4c', '%4d': '\\x4d',\n '%4D': '\\x4d', '%4e': '\\x4e', '%4E': '\\x4e', '%4f': '\\x4f', '%4F': '\\x4f',\n '%50': '\\x50', '%51': '\\x51', '%52': '\\x52', '%53': '\\x53', '%54': '\\x54',\n '%55': '\\x55', '%56': '\\x56', '%57': '\\x57', '%58': '\\x58', '%59': '\\x59',\n '%5a': '\\x5a', '%5A': '\\x5a', '%5b': '\\x5b', '%5B': '\\x5b', '%5c': '\\x5c',\n '%5C': '\\x5c', '%5d': '\\x5d', '%5D': '\\x5d', '%5e': '\\x5e', '%5E': '\\x5e',\n '%5f': '\\x5f', '%5F': '\\x5f', '%60': '\\x60', '%61': '\\x61', '%62': '\\x62',\n '%63': '\\x63', '%64': '\\x64', '%65': '\\x65', '%66': '\\x66', '%67': '\\x67',\n '%68': '\\x68', '%69': '\\x69', '%6a': '\\x6a', '%6A': '\\x6a', '%6b': '\\x6b',\n '%6B': '\\x6b', '%6c': '\\x6c', '%6C': '\\x6c', '%6d': '\\x6d', '%6D': '\\x6d',\n '%6e': '\\x6e', '%6E': '\\x6e', '%6f': '\\x6f', '%6F': '\\x6f', '%70': '\\x70',\n '%71': '\\x71', '%72': '\\x72', '%73': '\\x73', '%74': '\\x74', '%75': '\\x75',\n '%76': '\\x76', '%77': '\\x77', '%78': '\\x78', '%79': '\\x79', '%7a': '\\x7a',\n '%7A': '\\x7a', '%7b': '\\x7b', '%7B': '\\x7b', '%7c': '\\x7c', '%7C': '\\x7c',\n '%7d': '\\x7d', '%7D': '\\x7d', '%7e': '\\x7e', '%7E': '\\x7e', '%7f': '\\x7f',\n '%7F': '\\x7f', '%80': '\\x80', '%81': '\\x81', '%82': '\\x82', '%83': '\\x83',\n '%84': '\\x84', '%85': '\\x85', '%86': '\\x86', '%87': '\\x87', '%88': '\\x88',\n '%89': '\\x89', '%8a': '\\x8a', '%8A': '\\x8a', '%8b': '\\x8b', '%8B': '\\x8b',\n '%8c': '\\x8c', '%8C': '\\x8c', '%8d': '\\x8d', '%8D': '\\x8d', '%8e': '\\x8e',\n '%8E': '\\x8e', '%8f': '\\x8f', '%8F': '\\x8f', '%90': '\\x90', '%91': '\\x91',\n '%92': '\\x92', '%93': '\\x93', '%94': '\\x94', '%95': '\\x95', '%96': '\\x96',\n '%97': '\\x97', '%98': '\\x98', '%99': '\\x99', '%9a': '\\x9a', '%9A': '\\x9a',\n '%9b': '\\x9b', '%9B': '\\x9b', '%9c': '\\x9c', '%9C': '\\x9c', '%9d': '\\x9d',\n '%9D': '\\x9d', '%9e': '\\x9e', '%9E': '\\x9e', '%9f': '\\x9f', '%9F': '\\x9f',\n '%a0': '\\xa0', '%A0': '\\xa0', '%a1': '\\xa1', '%A1': '\\xa1', '%a2': '\\xa2',\n '%A2': '\\xa2', '%a3': '\\xa3', '%A3': '\\xa3', '%a4': '\\xa4', '%A4': '\\xa4',\n '%a5': '\\xa5', '%A5': '\\xa5', '%a6': '\\xa6', '%A6': '\\xa6', '%a7': '\\xa7',\n '%A7': '\\xa7', '%a8': '\\xa8', '%A8': '\\xa8', '%a9': '\\xa9', '%A9': '\\xa9',\n '%aa': '\\xaa', '%Aa': '\\xaa', '%aA': '\\xaa', '%AA': '\\xaa', '%ab': '\\xab',\n '%Ab': '\\xab', '%aB': '\\xab', '%AB': '\\xab', '%ac': '\\xac', '%Ac': '\\xac',\n '%aC': '\\xac', '%AC': '\\xac', '%ad': '\\xad', '%Ad': '\\xad', '%aD': '\\xad',\n '%AD': '\\xad', '%ae': '\\xae', '%Ae': '\\xae', '%aE': '\\xae', '%AE': '\\xae',\n '%af': '\\xaf', '%Af': '\\xaf', '%aF': '\\xaf', '%AF': '\\xaf', '%b0': '\\xb0',\n '%B0': '\\xb0', '%b1': '\\xb1', '%B1': '\\xb1', '%b2': '\\xb2', '%B2': '\\xb2',\n '%b3': '\\xb3', '%B3': '\\xb3', '%b4': '\\xb4', '%B4': '\\xb4', '%b5': '\\xb5',\n '%B5': '\\xb5', '%b6': '\\xb6', '%B6': '\\xb6', '%b7': '\\xb7', '%B7': '\\xb7',\n '%b8': '\\xb8', '%B8': '\\xb8', '%b9': '\\xb9', '%B9': '\\xb9', '%ba': '\\xba',\n '%Ba': '\\xba', '%bA': '\\xba', '%BA': '\\xba', '%bb': '\\xbb', '%Bb': '\\xbb',\n '%bB': '\\xbb', '%BB': '\\xbb', '%bc': '\\xbc', '%Bc': '\\xbc', '%bC': '\\xbc',\n '%BC': '\\xbc', '%bd': '\\xbd', '%Bd': '\\xbd', '%bD': '\\xbd', '%BD': '\\xbd',\n '%be': '\\xbe', '%Be': '\\xbe', '%bE': '\\xbe', '%BE': '\\xbe', '%bf': '\\xbf',\n '%Bf': '\\xbf', '%bF': '\\xbf', '%BF': '\\xbf', '%c0': '\\xc0', '%C0': '\\xc0',\n '%c1': '\\xc1', '%C1': '\\xc1', '%c2': '\\xc2', '%C2': '\\xc2', '%c3': '\\xc3',\n '%C3': '\\xc3', '%c4': '\\xc4', '%C4': '\\xc4', '%c5': '\\xc5', '%C5': '\\xc5',\n '%c6': '\\xc6', '%C6': '\\xc6', '%c7': '\\xc7', '%C7': '\\xc7', '%c8': '\\xc8',\n '%C8': '\\xc8', '%c9': '\\xc9', '%C9': '\\xc9', '%ca': '\\xca', '%Ca': '\\xca',\n '%cA': '\\xca', '%CA': '\\xca', '%cb': '\\xcb', '%Cb': '\\xcb', '%cB': '\\xcb',\n '%CB': '\\xcb', '%cc': '\\xcc', '%Cc': '\\xcc', '%cC': '\\xcc', '%CC': '\\xcc',\n '%cd': '\\xcd', '%Cd': '\\xcd', '%cD': '\\xcd', '%CD': '\\xcd', '%ce': '\\xce',\n '%Ce': '\\xce', '%cE': '\\xce', '%CE': '\\xce', '%cf': '\\xcf', '%Cf': '\\xcf',\n '%cF': '\\xcf', '%CF': '\\xcf', '%d0': '\\xd0', '%D0': '\\xd0', '%d1': '\\xd1',\n '%D1': '\\xd1', '%d2': '\\xd2', '%D2': '\\xd2', '%d3': '\\xd3', '%D3': '\\xd3',\n '%d4': '\\xd4', '%D4': '\\xd4', '%d5': '\\xd5', '%D5': '\\xd5', '%d6': '\\xd6',\n '%D6': '\\xd6', '%d7': '\\xd7', '%D7': '\\xd7', '%d8': '\\xd8', '%D8': '\\xd8',\n '%d9': '\\xd9', '%D9': '\\xd9', '%da': '\\xda', '%Da': '\\xda', '%dA': '\\xda',\n '%DA': '\\xda', '%db': '\\xdb', '%Db': '\\xdb', '%dB': '\\xdb', '%DB': '\\xdb',\n '%dc': '\\xdc', '%Dc': '\\xdc', '%dC': '\\xdc', '%DC': '\\xdc', '%dd': '\\xdd',\n '%Dd': '\\xdd', '%dD': '\\xdd', '%DD': '\\xdd', '%de': '\\xde', '%De': '\\xde',\n '%dE': '\\xde', '%DE': '\\xde', '%df': '\\xdf', '%Df': '\\xdf', '%dF': '\\xdf',\n '%DF': '\\xdf', '%e0': '\\xe0', '%E0': '\\xe0', '%e1': '\\xe1', '%E1': '\\xe1',\n '%e2': '\\xe2', '%E2': '\\xe2', '%e3': '\\xe3', '%E3': '\\xe3', '%e4': '\\xe4',\n '%E4': '\\xe4', '%e5': '\\xe5', '%E5': '\\xe5', '%e6': '\\xe6', '%E6': '\\xe6',\n '%e7': '\\xe7', '%E7': '\\xe7', '%e8': '\\xe8', '%E8': '\\xe8', '%e9': '\\xe9',\n '%E9': '\\xe9', '%ea': '\\xea', '%Ea': '\\xea', '%eA': '\\xea', '%EA': '\\xea',\n '%eb': '\\xeb', '%Eb': '\\xeb', '%eB': '\\xeb', '%EB': '\\xeb', '%ec': '\\xec',\n '%Ec': '\\xec', '%eC': '\\xec', '%EC': '\\xec', '%ed': '\\xed', '%Ed': '\\xed',\n '%eD': '\\xed', '%ED': '\\xed', '%ee': '\\xee', '%Ee': '\\xee', '%eE': '\\xee',\n '%EE': '\\xee', '%ef': '\\xef', '%Ef': '\\xef', '%eF': '\\xef', '%EF': '\\xef',\n '%f0': '\\xf0', '%F0': '\\xf0', '%f1': '\\xf1', '%F1': '\\xf1', '%f2': '\\xf2',\n '%F2': '\\xf2', '%f3': '\\xf3', '%F3': '\\xf3', '%f4': '\\xf4', '%F4': '\\xf4',\n '%f5': '\\xf5', '%F5': '\\xf5', '%f6': '\\xf6', '%F6': '\\xf6', '%f7': '\\xf7',\n '%F7': '\\xf7', '%f8': '\\xf8', '%F8': '\\xf8', '%f9': '\\xf9', '%F9': '\\xf9',\n '%fa': '\\xfa', '%Fa': '\\xfa', '%fA': '\\xfa', '%FA': '\\xfa', '%fb': '\\xfb',\n '%Fb': '\\xfb', '%fB': '\\xfb', '%FB': '\\xfb', '%fc': '\\xfc', '%Fc': '\\xfc',\n '%fC': '\\xfc', '%FC': '\\xfc', '%fd': '\\xfd', '%Fd': '\\xfd', '%fD': '\\xfd',\n '%FD': '\\xfd', '%fe': '\\xfe', '%Fe': '\\xfe', '%fE': '\\xfe', '%FE': '\\xfe',\n '%ff': '\\xff', '%Ff': '\\xff', '%fF': '\\xff', '%FF': '\\xff'\n}\n\nfunction encodedReplacer (match) {\n return EncodedLookup[match]\n}\n\nconst STATE_KEY = 0\nconst STATE_VALUE = 1\nconst STATE_CHARSET = 2\nconst STATE_LANG = 3\n\nfunction parseParams (str) {\n const res = []\n let state = STATE_KEY\n let charset = ''\n let inquote = false\n let escaping = false\n let p = 0\n let tmp = ''\n const len = str.length\n\n for (var i = 0; i < len; ++i) { // eslint-disable-line no-var\n const char = str[i]\n if (char === '\\\\' && inquote) {\n if (escaping) { escaping = false } else {\n escaping = true\n continue\n }\n } else if (char === '\"') {\n if (!escaping) {\n if (inquote) {\n inquote = false\n state = STATE_KEY\n } else { inquote = true }\n continue\n } else { escaping = false }\n } else {\n if (escaping && inquote) { tmp += '\\\\' }\n escaping = false\n if ((state === STATE_CHARSET || state === STATE_LANG) && char === \"'\") {\n if (state === STATE_CHARSET) {\n state = STATE_LANG\n charset = tmp.substring(1)\n } else { state = STATE_VALUE }\n tmp = ''\n continue\n } else if (state === STATE_KEY &&\n (char === '*' || char === '=') &&\n res.length) {\n state = char === '*'\n ? STATE_CHARSET\n : STATE_VALUE\n res[p] = [tmp, undefined]\n tmp = ''\n continue\n } else if (!inquote && char === ';') {\n state = STATE_KEY\n if (charset) {\n if (tmp.length) {\n tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),\n 'binary',\n charset)\n }\n charset = ''\n } else if (tmp.length) {\n tmp = decodeText(tmp, 'binary', 'utf8')\n }\n if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }\n tmp = ''\n ++p\n continue\n } else if (!inquote && (char === ' ' || char === '\\t')) { continue }\n }\n tmp += char\n }\n if (charset && tmp.length) {\n tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),\n 'binary',\n charset)\n } else if (tmp) {\n tmp = decodeText(tmp, 'binary', 'utf8')\n }\n\n if (res[p] === undefined) {\n if (tmp) { res[p] = tmp }\n } else { res[p][1] = tmp }\n\n return res\n}\n\nmodule.exports = parseParams\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\\/\\/\\/\\w:/) ? 1 : 0, -1) + \"/\";","//#region rolldown:runtime\nvar __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n};\n\n//#endregion\nexport { __export };","//#region src/singletons/async_local_storage/globals.ts\nconst TRACING_ALS_KEY = Symbol.for(\"ls:tracing_async_local_storage\");\nconst _CONTEXT_VARIABLES_KEY = Symbol.for(\"lc:context_variables\");\nconst setGlobalAsyncLocalStorageInstance = (instance) => {\n\tglobalThis[TRACING_ALS_KEY] = instance;\n};\nconst getGlobalAsyncLocalStorageInstance = () => {\n\treturn globalThis[TRACING_ALS_KEY];\n};\n\n//#endregion\nexport { _CONTEXT_VARIABLES_KEY, getGlobalAsyncLocalStorageInstance, setGlobalAsyncLocalStorageInstance };\n//# sourceMappingURL=globals.js.map","import snakeCase from \"decamelize\";\nimport camelCase from \"camelcase\";\n\n//#region src/load/map_keys.ts\nfunction keyToJson(key, map) {\n\treturn map?.[key] || snakeCase(key);\n}\nfunction keyFromJson(key, map) {\n\treturn map?.[key] || camelCase(key);\n}\nfunction mapKeys(fields, mapper, map) {\n\tconst mapped = {};\n\tfor (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key];\n\treturn mapped;\n}\n\n//#endregion\nexport { keyFromJson, keyToJson, mapKeys };\n//# sourceMappingURL=map_keys.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { keyToJson, mapKeys } from \"./map_keys.js\";\n\n//#region src/load/serializable.ts\nvar serializable_exports = {};\n__export(serializable_exports, {\n\tSerializable: () => Serializable,\n\tget_lc_unique_name: () => get_lc_unique_name\n});\nfunction shallowCopy(obj) {\n\treturn Array.isArray(obj) ? [...obj] : { ...obj };\n}\nfunction replaceSecrets(root, secretsMap) {\n\tconst result = shallowCopy(root);\n\tfor (const [path, secretId] of Object.entries(secretsMap)) {\n\t\tconst [last, ...partsReverse] = path.split(\".\").reverse();\n\t\tlet current = result;\n\t\tfor (const part of partsReverse.reverse()) {\n\t\t\tif (current[part] === void 0) break;\n\t\t\tcurrent[part] = shallowCopy(current[part]);\n\t\t\tcurrent = current[part];\n\t\t}\n\t\tif (current[last] !== void 0) current[last] = {\n\t\t\tlc: 1,\n\t\t\ttype: \"secret\",\n\t\t\tid: [secretId]\n\t\t};\n\t}\n\treturn result;\n}\n/**\n* Get a unique name for the module, rather than parent class implementations.\n* Should not be subclassed, subclass lc_name above instead.\n*/\nfunction get_lc_unique_name(serializableClass) {\n\tconst parentClass = Object.getPrototypeOf(serializableClass);\n\tconst lcNameIsSubclassed = typeof serializableClass.lc_name === \"function\" && (typeof parentClass.lc_name !== \"function\" || serializableClass.lc_name() !== parentClass.lc_name());\n\tif (lcNameIsSubclassed) return serializableClass.lc_name();\n\telse return serializableClass.name;\n}\nvar Serializable = class Serializable {\n\tlc_serializable = false;\n\tlc_kwargs;\n\t/**\n\t* The name of the serializable. Override to provide an alias or\n\t* to preserve the serialized module name in minified environments.\n\t*\n\t* Implemented as a static method to support loading logic.\n\t*/\n\tstatic lc_name() {\n\t\treturn this.name;\n\t}\n\t/**\n\t* The final serialized identifier for the module.\n\t*/\n\tget lc_id() {\n\t\treturn [...this.lc_namespace, get_lc_unique_name(this.constructor)];\n\t}\n\t/**\n\t* A map of secrets, which will be omitted from serialization.\n\t* Keys are paths to the secret in constructor args, e.g. \"foo.bar.baz\".\n\t* Values are the secret ids, which will be used when deserializing.\n\t*/\n\tget lc_secrets() {\n\t\treturn void 0;\n\t}\n\t/**\n\t* A map of additional attributes to merge with constructor args.\n\t* Keys are the attribute names, e.g. \"foo\".\n\t* Values are the attribute values, which will be serialized.\n\t* These attributes need to be accepted by the constructor as arguments.\n\t*/\n\tget lc_attributes() {\n\t\treturn void 0;\n\t}\n\t/**\n\t* A map of aliases for constructor args.\n\t* Keys are the attribute names, e.g. \"foo\".\n\t* Values are the alias that will replace the key in serialization.\n\t* This is used to eg. make argument names match Python.\n\t*/\n\tget lc_aliases() {\n\t\treturn void 0;\n\t}\n\t/**\n\t* A manual list of keys that should be serialized.\n\t* If not overridden, all fields passed into the constructor will be serialized.\n\t*/\n\tget lc_serializable_keys() {\n\t\treturn void 0;\n\t}\n\tconstructor(kwargs, ..._args) {\n\t\tif (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key)));\n\t\telse this.lc_kwargs = kwargs ?? {};\n\t}\n\ttoJSON() {\n\t\tif (!this.lc_serializable) return this.toJSONNotImplemented();\n\t\tif (this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== \"object\" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented();\n\t\tconst aliases = {};\n\t\tconst secrets = {};\n\t\tconst kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {\n\t\t\tacc[key] = key in this ? this[key] : this.lc_kwargs[key];\n\t\t\treturn acc;\n\t\t}, {});\n\t\tfor (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {\n\t\t\tObject.assign(aliases, Reflect.get(current, \"lc_aliases\", this));\n\t\t\tObject.assign(secrets, Reflect.get(current, \"lc_secrets\", this));\n\t\t\tObject.assign(kwargs, Reflect.get(current, \"lc_attributes\", this));\n\t\t}\n\t\tObject.keys(secrets).forEach((keyPath) => {\n\t\t\tlet read = this;\n\t\t\tlet write = kwargs;\n\t\t\tconst [last, ...partsReverse] = keyPath.split(\".\").reverse();\n\t\t\tfor (const key of partsReverse.reverse()) {\n\t\t\t\tif (!(key in read) || read[key] === void 0) return;\n\t\t\t\tif (!(key in write) || write[key] === void 0) {\n\t\t\t\t\tif (typeof read[key] === \"object\" && read[key] != null) write[key] = {};\n\t\t\t\t\telse if (Array.isArray(read[key])) write[key] = [];\n\t\t\t\t}\n\t\t\t\tread = read[key];\n\t\t\t\twrite = write[key];\n\t\t\t}\n\t\t\tif (last in read && read[last] !== void 0) write[last] = write[last] || read[last];\n\t\t});\n\t\treturn {\n\t\t\tlc: 1,\n\t\t\ttype: \"constructor\",\n\t\t\tid: this.lc_id,\n\t\t\tkwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)\n\t\t};\n\t}\n\ttoJSONNotImplemented() {\n\t\treturn {\n\t\t\tlc: 1,\n\t\t\ttype: \"not_implemented\",\n\t\t\tid: this.lc_id\n\t\t};\n\t}\n};\n\n//#endregion\nexport { Serializable, get_lc_unique_name, serializable_exports };\n//# sourceMappingURL=serializable.js.map","//#region src/messages/content/data.ts\n/**\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction isDataContentBlock(content_block) {\n\treturn typeof content_block === \"object\" && content_block !== null && \"type\" in content_block && typeof content_block.type === \"string\" && \"source_type\" in content_block && (content_block.source_type === \"url\" || content_block.source_type === \"base64\" || content_block.source_type === \"text\" || content_block.source_type === \"id\");\n}\n/**\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction isURLContentBlock(content_block) {\n\treturn isDataContentBlock(content_block) && content_block.source_type === \"url\" && \"url\" in content_block && typeof content_block.url === \"string\";\n}\n/**\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction isBase64ContentBlock(content_block) {\n\treturn isDataContentBlock(content_block) && content_block.source_type === \"base64\" && \"data\" in content_block && typeof content_block.data === \"string\";\n}\n/**\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction isPlainTextContentBlock(content_block) {\n\treturn isDataContentBlock(content_block) && content_block.source_type === \"text\" && \"text\" in content_block && typeof content_block.text === \"string\";\n}\n/**\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction isIDContentBlock(content_block) {\n\treturn isDataContentBlock(content_block) && content_block.source_type === \"id\" && \"id\" in content_block && typeof content_block.id === \"string\";\n}\n/**\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction convertToOpenAIImageBlock(content_block) {\n\tif (isDataContentBlock(content_block)) {\n\t\tif (content_block.source_type === \"url\") return {\n\t\t\ttype: \"image_url\",\n\t\t\timage_url: { url: content_block.url }\n\t\t};\n\t\tif (content_block.source_type === \"base64\") {\n\t\t\tif (!content_block.mime_type) throw new Error(\"mime_type key is required for base64 data.\");\n\t\t\tconst mime_type = content_block.mime_type;\n\t\t\treturn {\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: { url: `data:${mime_type};base64,${content_block.data}` }\n\t\t\t};\n\t\t}\n\t}\n\tthrow new Error(\"Unsupported source type. Only 'url' and 'base64' are supported.\");\n}\n/**\n* Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters.\n*\n* @param mime_type - The mime type to parse.\n* @returns An object containing the type, subtype, and parameters.\n*\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction parseMimeType(mime_type) {\n\tconst parts = mime_type.split(\";\")[0].split(\"/\");\n\tif (parts.length !== 2) throw new Error(`Invalid mime type: \"${mime_type}\" - does not match type/subtype format.`);\n\tconst type = parts[0].trim();\n\tconst subtype = parts[1].trim();\n\tif (type === \"\" || subtype === \"\") throw new Error(`Invalid mime type: \"${mime_type}\" - type or subtype is empty.`);\n\tconst parameters = {};\n\tfor (const parameterKvp of mime_type.split(\";\").slice(1)) {\n\t\tconst parameterParts = parameterKvp.split(\"=\");\n\t\tif (parameterParts.length !== 2) throw new Error(`Invalid parameter syntax in mime type: \"${mime_type}\".`);\n\t\tconst key = parameterParts[0].trim();\n\t\tconst value = parameterParts[1].trim();\n\t\tif (key === \"\") throw new Error(`Invalid parameter syntax in mime type: \"${mime_type}\".`);\n\t\tparameters[key] = value;\n\t}\n\treturn {\n\t\ttype,\n\t\tsubtype,\n\t\tparameters\n\t};\n}\n/**\n* Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string.\n*\n* @param dataUrl - The base64 data URL to parse.\n* @param asTypedArray - Whether to return the data as a typed array.\n* @returns The parsed data and mime type, or undefined if the data URL is invalid.\n*\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) {\n\tconst formatMatch = data_url.match(/^data:(\\w+\\/\\w+);base64,([A-Za-z0-9+/]+=*)$/);\n\tlet mime_type;\n\tif (formatMatch) {\n\t\tmime_type = formatMatch[1].toLowerCase();\n\t\tconst data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2];\n\t\treturn {\n\t\t\tmime_type,\n\t\t\tdata\n\t\t};\n\t}\n\treturn void 0;\n}\n/**\n* Convert from a standard data content block to a provider's proprietary data content block format.\n*\n* Don't override this method. Instead, override the more specific conversion methods and use this\n* method unmodified.\n*\n* @param block - The standard data content block to convert.\n* @returns The provider data content block.\n* @throws An error if the standard data content block type is not supported.\n*\n* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead.\n*/\nfunction convertToProviderContentBlock(block, converter) {\n\tif (block.type === \"text\") {\n\t\tif (!converter.fromStandardTextBlock) throw new Error(`Converter for ${converter.providerName} does not implement \\`fromStandardTextBlock\\` method.`);\n\t\treturn converter.fromStandardTextBlock(block);\n\t}\n\tif (block.type === \"image\") {\n\t\tif (!converter.fromStandardImageBlock) throw new Error(`Converter for ${converter.providerName} does not implement \\`fromStandardImageBlock\\` method.`);\n\t\treturn converter.fromStandardImageBlock(block);\n\t}\n\tif (block.type === \"audio\") {\n\t\tif (!converter.fromStandardAudioBlock) throw new Error(`Converter for ${converter.providerName} does not implement \\`fromStandardAudioBlock\\` method.`);\n\t\treturn converter.fromStandardAudioBlock(block);\n\t}\n\tif (block.type === \"file\") {\n\t\tif (!converter.fromStandardFileBlock) throw new Error(`Converter for ${converter.providerName} does not implement \\`fromStandardFileBlock\\` method.`);\n\t\treturn converter.fromStandardFileBlock(block);\n\t}\n\tthrow new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`);\n}\n\n//#endregion\nexport { convertToOpenAIImageBlock, convertToProviderContentBlock, isBase64ContentBlock, isDataContentBlock, isIDContentBlock, isPlainTextContentBlock, isURLContentBlock, parseBase64DataUrl, parseMimeType };\n//# sourceMappingURL=data.js.map","//#region src/messages/block_translators/utils.ts\nfunction _isContentBlock(block, type) {\n\treturn _isObject(block) && block.type === type;\n}\nfunction _isObject(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction _isArray(value) {\n\treturn Array.isArray(value);\n}\nfunction _isString(value) {\n\treturn typeof value === \"string\";\n}\nfunction _isNumber(value) {\n\treturn typeof value === \"number\";\n}\nfunction _isBytesArray(value) {\n\treturn value instanceof Uint8Array;\n}\nfunction safeParseJson(value) {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn void 0;\n\t}\n}\nconst iife = (fn) => fn();\n\n//#endregion\nexport { _isArray, _isBytesArray, _isContentBlock, _isNumber, _isObject, _isString, iife, safeParseJson };\n//# sourceMappingURL=utils.js.map","import { _isArray, _isContentBlock, _isNumber, _isObject, _isString, iife, safeParseJson } from \"./utils.js\";\n\n//#region src/messages/block_translators/anthropic.ts\nfunction convertAnthropicAnnotation(citation) {\n\tif (citation.type === \"char_location\" && _isString(citation.document_title) && _isNumber(citation.start_char_index) && _isNumber(citation.end_char_index) && _isString(citation.cited_text)) {\n\t\tconst { document_title, start_char_index, end_char_index, cited_text,...rest } = citation;\n\t\treturn {\n\t\t\t...rest,\n\t\t\ttype: \"citation\",\n\t\t\tsource: \"char\",\n\t\t\ttitle: document_title ?? void 0,\n\t\t\tstartIndex: start_char_index,\n\t\t\tendIndex: end_char_index,\n\t\t\tcitedText: cited_text\n\t\t};\n\t}\n\tif (citation.type === \"page_location\" && _isString(citation.document_title) && _isNumber(citation.start_page_number) && _isNumber(citation.end_page_number) && _isString(citation.cited_text)) {\n\t\tconst { document_title, start_page_number, end_page_number, cited_text,...rest } = citation;\n\t\treturn {\n\t\t\t...rest,\n\t\t\ttype: \"citation\",\n\t\t\tsource: \"page\",\n\t\t\ttitle: document_title ?? void 0,\n\t\t\tstartIndex: start_page_number,\n\t\t\tendIndex: end_page_number,\n\t\t\tcitedText: cited_text\n\t\t};\n\t}\n\tif (citation.type === \"content_block_location\" && _isString(citation.document_title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) {\n\t\tconst { document_title, start_block_index, end_block_index, cited_text,...rest } = citation;\n\t\treturn {\n\t\t\t...rest,\n\t\t\ttype: \"citation\",\n\t\t\tsource: \"block\",\n\t\t\ttitle: document_title ?? void 0,\n\t\t\tstartIndex: start_block_index,\n\t\t\tendIndex: end_block_index,\n\t\t\tcitedText: cited_text\n\t\t};\n\t}\n\tif (citation.type === \"web_search_result_location\" && _isString(citation.url) && _isString(citation.title) && _isString(citation.encrypted_index) && _isString(citation.cited_text)) {\n\t\tconst { url, title, encrypted_index, cited_text,...rest } = citation;\n\t\treturn {\n\t\t\t...rest,\n\t\t\ttype: \"citation\",\n\t\t\tsource: \"url\",\n\t\t\turl,\n\t\t\ttitle,\n\t\t\tstartIndex: Number(encrypted_index),\n\t\t\tendIndex: Number(encrypted_index),\n\t\t\tcitedText: cited_text\n\t\t};\n\t}\n\tif (citation.type === \"search_result_location\" && _isString(citation.source) && _isString(citation.title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) {\n\t\tconst { source, title, start_block_index, end_block_index, cited_text,...rest } = citation;\n\t\treturn {\n\t\t\t...rest,\n\t\t\ttype: \"citation\",\n\t\t\tsource: \"search\",\n\t\t\turl: source,\n\t\t\ttitle: title ?? void 0,\n\t\t\tstartIndex: start_block_index,\n\t\t\tendIndex: end_block_index,\n\t\t\tcitedText: cited_text\n\t\t};\n\t}\n\treturn void 0;\n}\n/**\n* Converts an Anthropic content block to a standard V1 content block.\n*\n* This function handles the conversion of Anthropic-specific content blocks\n* (document and image blocks) to the standardized V1 format. It supports\n* various source types including base64 data, URLs, file IDs, and text data.\n*\n* @param block - The Anthropic content block to convert\n* @returns A standard V1 content block if conversion is successful, undefined otherwise\n*\n* @example\n* ```typescript\n* const anthropicBlock = {\n* type: \"image\",\n* source: {\n* type: \"base64\",\n* media_type: \"image/png\",\n* data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==\"\n* }\n* };\n*\n* const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock);\n* // Returns: { type: \"image\", mimeType: \"image/png\", data: \"...\" }\n* ```\n*/\nfunction convertToV1FromAnthropicContentBlock(block) {\n\tif (_isContentBlock(block, \"document\") && _isObject(block.source) && \"type\" in block.source) {\n\t\tif (block.source.type === \"base64\" && _isString(block.source.media_type) && _isString(block.source.data)) return {\n\t\t\ttype: \"file\",\n\t\t\tmimeType: block.source.media_type,\n\t\t\tdata: block.source.data\n\t\t};\n\t\telse if (block.source.type === \"url\" && _isString(block.source.url)) return {\n\t\t\ttype: \"file\",\n\t\t\turl: block.source.url\n\t\t};\n\t\telse if (block.source.type === \"file\" && _isString(block.source.file_id)) return {\n\t\t\ttype: \"file\",\n\t\t\tfileId: block.source.file_id\n\t\t};\n\t\telse if (block.source.type === \"text\" && _isString(block.source.data)) return {\n\t\t\ttype: \"file\",\n\t\t\tmimeType: String(block.source.media_type ?? \"text/plain\"),\n\t\t\tdata: block.source.data\n\t\t};\n\t} else if (_isContentBlock(block, \"image\") && _isObject(block.source) && \"type\" in block.source) {\n\t\tif (block.source.type === \"base64\" && _isString(block.source.media_type) && _isString(block.source.data)) return {\n\t\t\ttype: \"image\",\n\t\t\tmimeType: block.source.media_type,\n\t\t\tdata: block.source.data\n\t\t};\n\t\telse if (block.source.type === \"url\" && _isString(block.source.url)) return {\n\t\t\ttype: \"image\",\n\t\t\turl: block.source.url\n\t\t};\n\t\telse if (block.source.type === \"file\" && _isString(block.source.file_id)) return {\n\t\t\ttype: \"image\",\n\t\t\tfileId: block.source.file_id\n\t\t};\n\t}\n\treturn void 0;\n}\n/**\n* Converts an array of content blocks from Anthropic format to v1 standard format.\n*\n* This function processes each content block in the input array, attempting to convert\n* Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.)\n* to the standardized v1 content block format. If a block cannot be converted, it is\n* passed through as-is with a type assertion to ContentBlock.Standard.\n*\n* @param content - Array of content blocks in Anthropic format to be converted\n* @returns Array of content blocks in v1 standard format\n*/\nfunction convertToV1FromAnthropicInput(content) {\n\tfunction* iterateContent() {\n\t\tfor (const block of content) {\n\t\t\tconst stdBlock = convertToV1FromAnthropicContentBlock(block);\n\t\t\tif (stdBlock) yield stdBlock;\n\t\t\telse yield block;\n\t\t}\n\t}\n\treturn Array.from(iterateContent());\n}\n/**\n* Converts an Anthropic AI message to an array of v1 standard content blocks.\n*\n* This function processes an AI message containing Anthropic-specific content blocks\n* and converts them to the standardized v1 content block format.\n*\n* @param message - The AI message containing Anthropic-formatted content blocks\n* @returns Array of content blocks in v1 standard format\n*\n* @example\n* ```typescript\n* const message = new AIMessage([\n* { type: \"text\", text: \"Hello world\" },\n* { type: \"thinking\", text: \"Let me think about this...\" },\n* { type: \"tool_use\", id: \"123\", name: \"calculator\", input: { a: 1, b: 2 } }\n* ]);\n*\n* const standardBlocks = convertToV1FromAnthropicMessage(message);\n* // Returns:\n* // [\n* // { type: \"text\", text: \"Hello world\" },\n* // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n* // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }\n* // ]\n* ```\n*/\nfunction convertToV1FromAnthropicMessage(message) {\n\tfunction* iterateContent() {\n\t\tconst content = typeof message.content === \"string\" ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: message.content\n\t\t}] : message.content;\n\t\tfor (const block of content) {\n\t\t\tif (_isContentBlock(block, \"text\") && _isString(block.text)) {\n\t\t\t\tconst { text, citations,...rest } = block;\n\t\t\t\tif (_isArray(citations) && citations.length) {\n\t\t\t\t\tconst _citations = citations.reduce((acc, item) => {\n\t\t\t\t\t\tconst citation = convertAnthropicAnnotation(item);\n\t\t\t\t\t\tif (citation) return [...acc, citation];\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, []);\n\t\t\t\t\tyield {\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\tannotations: _citations\n\t\t\t\t\t};\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tyield {\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext\n\t\t\t\t\t};\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (_isContentBlock(block, \"thinking\") && _isString(block.thinking)) {\n\t\t\t\tconst { thinking, signature,...rest } = block;\n\t\t\t\tyield {\n\t\t\t\t\t...rest,\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\treasoning: thinking,\n\t\t\t\t\tsignature\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"redacted_thinking\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"tool_use\") && _isString(block.name) && _isString(block.id)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname: block.name,\n\t\t\t\t\targs: block.input\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"input_json_delta\")) {\n\t\t\t\tif (_isAIMessageChunk(message) && message.tool_call_chunks?.length) {\n\t\t\t\t\tconst tool_call_chunk = message.tool_call_chunks[0];\n\t\t\t\t\tyield {\n\t\t\t\t\t\ttype: \"tool_call_chunk\",\n\t\t\t\t\t\tid: tool_call_chunk.id,\n\t\t\t\t\t\tname: tool_call_chunk.name,\n\t\t\t\t\t\targs: tool_call_chunk.args,\n\t\t\t\t\t\tindex: tool_call_chunk.index\n\t\t\t\t\t};\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (_isContentBlock(block, \"server_tool_use\") && _isString(block.name) && _isString(block.id)) {\n\t\t\t\tconst { name, id } = block;\n\t\t\t\tif (name === \"web_search\") {\n\t\t\t\t\tconst query = iife(() => {\n\t\t\t\t\t\tif (typeof block.input === \"string\") return block.input;\n\t\t\t\t\t\telse if (_isObject(block.input) && _isString(block.input.query)) return block.input.query;\n\t\t\t\t\t\telse if (_isString(block.partial_json)) {\n\t\t\t\t\t\t\tconst json = safeParseJson(block.partial_json);\n\t\t\t\t\t\t\tif (json?.query) return json.query;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t});\n\t\t\t\t\tyield {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\t\tname: \"web_search\",\n\t\t\t\t\t\targs: { query }\n\t\t\t\t\t};\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (block.name === \"code_execution\") {\n\t\t\t\t\tconst code = iife(() => {\n\t\t\t\t\t\tif (typeof block.input === \"string\") return block.input;\n\t\t\t\t\t\telse if (_isObject(block.input) && _isString(block.input.code)) return block.input.code;\n\t\t\t\t\t\telse if (_isString(block.partial_json)) {\n\t\t\t\t\t\t\tconst json = safeParseJson(block.partial_json);\n\t\t\t\t\t\t\tif (json?.code) return json.code;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t});\n\t\t\t\t\tyield {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\t\tname: \"code_execution\",\n\t\t\t\t\t\targs: { code }\n\t\t\t\t\t};\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (_isContentBlock(block, \"web_search_tool_result\") && _isString(block.tool_use_id) && _isArray(block.content)) {\n\t\t\t\tconst { content: content$1, tool_use_id } = block;\n\t\t\t\tconst urls = content$1.reduce((acc, content$2) => {\n\t\t\t\t\tif (_isContentBlock(content$2, \"web_search_result\")) return [...acc, content$2.url];\n\t\t\t\t\treturn acc;\n\t\t\t\t}, []);\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"server_tool_call_result\",\n\t\t\t\t\tname: \"web_search\",\n\t\t\t\t\ttoolCallId: tool_use_id,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\toutput: { urls }\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"code_execution_tool_result\") && _isString(block.tool_use_id) && _isObject(block.content)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"server_tool_call_result\",\n\t\t\t\t\tname: \"code_execution\",\n\t\t\t\t\ttoolCallId: block.tool_use_id,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\toutput: block.content\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"mcp_tool_use\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"mcp_tool_use\",\n\t\t\t\t\targs: block.input\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"mcp_tool_result\") && _isString(block.tool_use_id) && _isObject(block.content)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"server_tool_call_result\",\n\t\t\t\t\tname: \"mcp_tool_use\",\n\t\t\t\t\ttoolCallId: block.tool_use_id,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\toutput: block.content\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"container_upload\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"container_upload\",\n\t\t\t\t\targs: block.input\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"search_result\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"tool_result\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tconst stdBlock = convertToV1FromAnthropicContentBlock(block);\n\t\t\t\tif (stdBlock) {\n\t\t\t\t\tyield stdBlock;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tyield {\n\t\t\t\ttype: \"non_standard\",\n\t\t\t\tvalue: block\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateContent());\n}\nconst ChatAnthropicTranslator = {\n\ttranslateContent: convertToV1FromAnthropicMessage,\n\ttranslateContentChunk: convertToV1FromAnthropicMessage\n};\nfunction _isAIMessageChunk(message) {\n\treturn typeof message?._getType === \"function\" && typeof message.concat === \"function\" && message._getType() === \"ai\";\n}\n\n//#endregion\nexport { ChatAnthropicTranslator, convertToV1FromAnthropicInput };\n//# sourceMappingURL=anthropic.js.map","import { isBase64ContentBlock, isIDContentBlock, isURLContentBlock, parseBase64DataUrl } from \"../content/data.js\";\nimport { _isContentBlock, _isObject, _isString } from \"./utils.js\";\n\n//#region src/messages/block_translators/data.ts\nfunction convertToV1FromDataContentBlock(block) {\n\tif (isURLContentBlock(block)) return {\n\t\ttype: block.type,\n\t\tmimeType: block.mime_type,\n\t\turl: block.url,\n\t\tmetadata: block.metadata\n\t};\n\tif (isBase64ContentBlock(block)) return {\n\t\ttype: block.type,\n\t\tmimeType: block.mime_type ?? \"application/octet-stream\",\n\t\tdata: block.data,\n\t\tmetadata: block.metadata\n\t};\n\tif (isIDContentBlock(block)) return {\n\t\ttype: block.type,\n\t\tmimeType: block.mime_type,\n\t\tfileId: block.id,\n\t\tmetadata: block.metadata\n\t};\n\treturn block;\n}\nfunction convertToV1FromDataContent(content) {\n\treturn content.map(convertToV1FromDataContentBlock);\n}\nfunction isOpenAIDataBlock(block) {\n\tif (_isContentBlock(block, \"image_url\") && _isObject(block.image_url)) return true;\n\tif (_isContentBlock(block, \"input_audio\") && _isObject(block.input_audio)) return true;\n\tif (_isContentBlock(block, \"file\") && _isObject(block.file)) return true;\n\treturn false;\n}\nfunction convertToV1FromOpenAIDataBlock(block) {\n\tif (_isContentBlock(block, \"image_url\") && _isObject(block.image_url) && _isString(block.image_url.url)) {\n\t\tconst parsed = parseBase64DataUrl({ dataUrl: block.image_url.url });\n\t\tif (parsed) return {\n\t\t\ttype: \"image\",\n\t\t\tmimeType: parsed.mime_type,\n\t\t\tdata: parsed.data\n\t\t};\n\t\telse return {\n\t\t\ttype: \"image\",\n\t\t\turl: block.image_url.url\n\t\t};\n\t} else if (_isContentBlock(block, \"input_audio\") && _isObject(block.input_audio) && _isString(block.input_audio.data) && _isString(block.input_audio.format)) return {\n\t\ttype: \"audio\",\n\t\tdata: block.input_audio.data,\n\t\tmimeType: `audio/${block.input_audio.format}`\n\t};\n\telse if (_isContentBlock(block, \"file\") && _isObject(block.file) && _isString(block.file.data)) {\n\t\tconst parsed = parseBase64DataUrl({ dataUrl: block.file.data });\n\t\tif (parsed) return {\n\t\t\ttype: \"file\",\n\t\t\tdata: parsed.data,\n\t\t\tmimeType: parsed.mime_type\n\t\t};\n\t\telse if (_isString(block.file.file_id)) return {\n\t\t\ttype: \"file\",\n\t\t\tfileId: block.file.file_id\n\t\t};\n\t}\n\treturn block;\n}\n\n//#endregion\nexport { convertToV1FromDataContent, convertToV1FromOpenAIDataBlock, isOpenAIDataBlock };\n//# sourceMappingURL=data.js.map","import { _isArray, _isContentBlock, _isObject, _isString, iife } from \"./utils.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\n\n//#region src/messages/block_translators/openai.ts\n/**\n* Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n*\n* This function processes an AI message from ChatOpenAICompletions API format\n* and converts it to the standardized v1 content block format. It handles both\n* string content and structured content blocks, as well as tool calls.\n*\n* @param message - The AI message containing ChatOpenAICompletions formatted content\n* @returns Array of content blocks in v1 standard format\n*\n* @example\n* ```typescript\n* const message = new AIMessage(\"Hello world\");\n* const standardBlocks = convertToV1FromChatCompletions(message);\n* // Returns: [{ type: \"text\", text: \"Hello world\" }]\n* ```\n*\n* @example\n* ```typescript\n* const message = new AIMessage([\n* { type: \"text\", text: \"Hello\" },\n* { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n* ]);\n* message.tool_calls = [\n* { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n* ];\n*\n* const standardBlocks = convertToV1FromChatCompletions(message);\n* // Returns:\n* // [\n* // { type: \"text\", text: \"Hello\" },\n* // { type: \"image\", url: \"https://example.com/image.png\" },\n* // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n* // ]\n* ```\n*/\nfunction convertToV1FromChatCompletions(message) {\n\tconst blocks = [];\n\tif (typeof message.content === \"string\") blocks.push({\n\t\ttype: \"text\",\n\t\ttext: message.content\n\t});\n\telse blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n\tfor (const toolCall of message.tool_calls ?? []) blocks.push({\n\t\ttype: \"tool_call\",\n\t\tid: toolCall.id,\n\t\tname: toolCall.name,\n\t\targs: toolCall.args\n\t});\n\treturn blocks;\n}\n/**\n* Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n*\n* This function processes an AI message chunk from OpenAI's chat completions API and converts\n* it to the standardized v1 content block format. It handles both string and array content,\n* as well as tool calls that may be present in the chunk.\n*\n* @param message - The AI message chunk containing OpenAI-formatted content blocks\n* @returns Array of content blocks in v1 standard format\n*\n* @example\n* ```typescript\n* const chunk = new AIMessage(\"Hello\");\n* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n* // Returns: [{ type: \"text\", text: \"Hello\" }]\n* ```\n*\n* @example\n* ```typescript\n* const chunk = new AIMessage([\n* { type: \"text\", text: \"Processing...\" }\n* ]);\n* chunk.tool_calls = [\n* { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n* ];\n*\n* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n* // Returns:\n* // [\n* // { type: \"text\", text: \"Processing...\" },\n* // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n* // ]\n* ```\n*/\nfunction convertToV1FromChatCompletionsChunk(message) {\n\tconst blocks = [];\n\tif (typeof message.content === \"string\") blocks.push({\n\t\ttype: \"text\",\n\t\ttext: message.content\n\t});\n\telse blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n\tfor (const toolCall of message.tool_calls ?? []) blocks.push({\n\t\ttype: \"tool_call\",\n\t\tid: toolCall.id,\n\t\tname: toolCall.name,\n\t\targs: toolCall.args\n\t});\n\treturn blocks;\n}\n/**\n* Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n*\n* This function processes content blocks from OpenAI's Chat Completions API format\n* and converts them to the standardized v1 content block format. It handles both\n* OpenAI-specific data blocks (which require conversion) and standard blocks\n* (which are passed through with type assertion).\n*\n* @param blocks - Array of content blocks in ChatOpenAICompletions format\n* @returns Array of content blocks in v1 standard format\n*\n* @example\n* ```typescript\n* const openaiBlocks = [\n* { type: \"text\", text: \"Hello world\" },\n* { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n* ];\n*\n* const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n* // Returns:\n* // [\n* // { type: \"text\", text: \"Hello world\" },\n* // { type: \"image\", url: \"https://example.com/image.png\" }\n* // ]\n* ```\n*/\nfunction convertToV1FromChatCompletionsInput(blocks) {\n\tconst convertedBlocks = [];\n\tfor (const block of blocks) if (isOpenAIDataBlock(block)) convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n\telse convertedBlocks.push(block);\n\treturn convertedBlocks;\n}\nfunction convertResponsesAnnotation(annotation) {\n\tif (annotation.type === \"url_citation\") {\n\t\tconst { url, title, start_index, end_index } = annotation;\n\t\treturn {\n\t\t\ttype: \"citation\",\n\t\t\turl,\n\t\t\ttitle,\n\t\t\tstartIndex: start_index,\n\t\t\tendIndex: end_index\n\t\t};\n\t}\n\tif (annotation.type === \"file_citation\") {\n\t\tconst { file_id, filename, index } = annotation;\n\t\treturn {\n\t\t\ttype: \"citation\",\n\t\t\ttitle: filename,\n\t\t\tstartIndex: index,\n\t\t\tendIndex: index,\n\t\t\tfileId: file_id\n\t\t};\n\t}\n\treturn annotation;\n}\n/**\n* Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n*\n* This function processes an AI message containing OpenAI Responses-specific content blocks\n* and converts them to the standardized v1 content block format. It handles reasoning summaries,\n* text content with annotations, tool calls, and various tool outputs including code interpreter,\n* web search, file search, computer calls, and MCP-related blocks.\n*\n* @param message - The AI message containing OpenAI Responses-formatted content blocks\n* @returns Array of content blocks in v1 standard format\n*\n* @example\n* ```typescript\n* const message = new AIMessage({\n* content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n* tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n* additional_kwargs: {\n* reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n* tool_outputs: [\n* {\n* type: \"code_interpreter_call\",\n* code: \"print('hello')\",\n* outputs: [{ type: \"logs\", logs: \"hello\" }]\n* }\n* ]\n* }\n* });\n*\n* const standardBlocks = convertToV1FromResponses(message);\n* // Returns:\n* // [\n* // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n* // { type: \"text\", text: \"Hello world\", annotations: [] },\n* // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n* // { type: \"code_interpreter_call\", code: \"print('hello')\" },\n* // { type: \"code_interpreter_result\", output: [{ type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" }] }\n* // ]\n* ```\n*/\nfunction convertToV1FromResponses(message) {\n\tfunction* iterateContent() {\n\t\tif (_isObject(message.additional_kwargs?.reasoning) && _isArray(message.additional_kwargs.reasoning.summary)) {\n\t\t\tconst summary = message.additional_kwargs.reasoning.summary.reduce((acc, item) => {\n\t\t\t\tif (_isObject(item) && _isString(item.text)) return `${acc}${item.text}`;\n\t\t\t\treturn acc;\n\t\t\t}, \"\");\n\t\t\tyield {\n\t\t\t\ttype: \"reasoning\",\n\t\t\t\treasoning: summary\n\t\t\t};\n\t\t}\n\t\tconst content = typeof message.content === \"string\" ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: message.content\n\t\t}] : message.content;\n\t\tfor (const block of content) if (_isContentBlock(block, \"text\")) {\n\t\t\tconst { text, annotations,...rest } = block;\n\t\t\tif (Array.isArray(annotations)) yield {\n\t\t\t\t...rest,\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: String(text),\n\t\t\t\tannotations: annotations.map(convertResponsesAnnotation)\n\t\t\t};\n\t\t\telse yield {\n\t\t\t\t...rest,\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: String(text)\n\t\t\t};\n\t\t}\n\t\tfor (const toolCall of message.tool_calls ?? []) yield {\n\t\t\ttype: \"tool_call\",\n\t\t\tid: toolCall.id,\n\t\t\tname: toolCall.name,\n\t\t\targs: toolCall.args\n\t\t};\n\t\tif (_isObject(message.additional_kwargs) && _isArray(message.additional_kwargs.tool_outputs)) for (const toolOutput of message.additional_kwargs.tool_outputs) {\n\t\t\tif (_isContentBlock(toolOutput, \"web_search_call\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: toolOutput.id,\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"web_search\",\n\t\t\t\t\targs: { query: toolOutput.query }\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"file_search_call\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: toolOutput.id,\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"file_search\",\n\t\t\t\t\targs: { query: toolOutput.query }\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"computer_call\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: toolOutput\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n\t\t\t\tif (_isString(toolOutput.code)) yield {\n\t\t\t\t\tid: toolOutput.id,\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"code_interpreter\",\n\t\t\t\t\targs: { code: toolOutput.code }\n\t\t\t\t};\n\t\t\t\tif (_isArray(toolOutput.outputs)) {\n\t\t\t\t\tconst returnCode = iife(() => {\n\t\t\t\t\t\tif (toolOutput.status === \"in_progress\") return void 0;\n\t\t\t\t\t\tif (toolOutput.status === \"completed\") return 0;\n\t\t\t\t\t\tif (toolOutput.status === \"incomplete\") return 127;\n\t\t\t\t\t\tif (toolOutput.status === \"interpreting\") return void 0;\n\t\t\t\t\t\tif (toolOutput.status === \"failed\") return 1;\n\t\t\t\t\t\treturn void 0;\n\t\t\t\t\t});\n\t\t\t\t\tfor (const output of toolOutput.outputs) if (_isContentBlock(output, \"logs\")) {\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\ttype: \"server_tool_call_result\",\n\t\t\t\t\t\t\ttoolCallId: toolOutput.id ?? \"\",\n\t\t\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\ttype: \"code_interpreter_output\",\n\t\t\t\t\t\t\t\treturnCode: returnCode ?? 0,\n\t\t\t\t\t\t\t\tstderr: [0, void 0].includes(returnCode) ? void 0 : String(output.logs),\n\t\t\t\t\t\t\t\tstdout: [0, void 0].includes(returnCode) ? String(output.logs) : void 0\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"mcp_call\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: toolOutput.id,\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"mcp_call\",\n\t\t\t\t\targs: toolOutput.input\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n\t\t\t\tyield {\n\t\t\t\t\tid: toolOutput.id,\n\t\t\t\t\ttype: \"server_tool_call\",\n\t\t\t\t\tname: \"mcp_list_tools\",\n\t\t\t\t\targs: toolOutput.input\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: toolOutput\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: toolOutput\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (_isObject(toolOutput)) yield {\n\t\t\t\ttype: \"non_standard\",\n\t\t\t\tvalue: toolOutput\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateContent());\n}\n/**\n* Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n*\n* This function processes an AI message chunk containing OpenAI-specific content blocks\n* and converts them to the standardized v1 content block format. It handles both the\n* regular message content and tool call chunks that are specific to streaming responses.\n*\n* @param message - The AI message chunk containing OpenAI-formatted content blocks\n* @returns Array of content blocks in v1 standard format\n*\n* @example\n* ```typescript\n* const messageChunk = new AIMessageChunk({\n* content: [{ type: \"text\", text: \"Hello\" }],\n* tool_call_chunks: [\n* { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n* ]\n* });\n*\n* const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n* // Returns:\n* // [\n* // { type: \"text\", text: \"Hello\" },\n* // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n* // ]\n* ```\n*/\nfunction convertToV1FromResponsesChunk(message) {\n\tfunction* iterateContent() {\n\t\tyield* convertToV1FromResponses(message);\n\t\tfor (const toolCallChunk of message.tool_call_chunks ?? []) yield {\n\t\t\ttype: \"tool_call_chunk\",\n\t\t\tid: toolCallChunk.id,\n\t\t\tname: toolCallChunk.name,\n\t\t\targs: toolCallChunk.args\n\t\t};\n\t}\n\treturn Array.from(iterateContent());\n}\nconst ChatOpenAITranslator = {\n\ttranslateContent: (message) => {\n\t\tif (typeof message.content === \"string\") return convertToV1FromChatCompletions(message);\n\t\treturn convertToV1FromResponses(message);\n\t},\n\ttranslateContentChunk: (message) => {\n\t\tif (typeof message.content === \"string\") return convertToV1FromChatCompletionsChunk(message);\n\t\treturn convertToV1FromResponsesChunk(message);\n\t}\n};\n\n//#endregion\nexport { ChatOpenAITranslator, convertToV1FromChatCompletionsInput };\n//# sourceMappingURL=openai.js.map","//#region src/messages/message.ts\n/**\n* Type guard to check if a value is a valid Message object.\n*\n* @param message - The value to check\n* @returns true if the value is a valid Message object, false otherwise\n*/\nfunction isMessage(message) {\n\treturn typeof message === \"object\" && message !== null && \"type\" in message && \"content\" in message && (typeof message.content === \"string\" || Array.isArray(message.content));\n}\n\n//#endregion\nexport { isMessage };\n//# sourceMappingURL=message.js.map","//#region src/messages/format.ts\nfunction convertToFormattedString(message, format = \"pretty\") {\n\tif (format === \"pretty\") return convertToPrettyString(message);\n\treturn JSON.stringify(message);\n}\nfunction convertToPrettyString(message) {\n\tconst lines = [];\n\tconst title = ` ${message.type.charAt(0).toUpperCase() + message.type.slice(1)} Message `;\n\tconst sepLen = Math.floor((80 - title.length) / 2);\n\tconst sep = \"=\".repeat(sepLen);\n\tconst secondSep = title.length % 2 === 0 ? sep : `${sep}=`;\n\tlines.push(`${sep}${title}${secondSep}`);\n\tif (message.type === \"ai\") {\n\t\tconst aiMessage = message;\n\t\tif (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n\t\t\tlines.push(\"Tool Calls:\");\n\t\t\tfor (const tc of aiMessage.tool_calls) {\n\t\t\t\tlines.push(` ${tc.name} (${tc.id})`);\n\t\t\t\tlines.push(` Call ID: ${tc.id}`);\n\t\t\t\tlines.push(\" Args:\");\n\t\t\t\tfor (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${value}`);\n\t\t\t}\n\t\t}\n\t}\n\tif (message.type === \"tool\") {\n\t\tconst toolMessage = message;\n\t\tif (toolMessage.name) lines.push(`Name: ${toolMessage.name}`);\n\t}\n\tif (typeof message.content === \"string\" && message.content.trim()) {\n\t\tif (lines.length > 1) lines.push(\"\");\n\t\tlines.push(message.content);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n//#endregion\nexport { convertToFormattedString };\n//# sourceMappingURL=format.js.map","import { Serializable } from \"../load/serializable.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport { isMessage } from \"./message.js\";\nimport { convertToFormattedString } from \"./format.js\";\n\n//#region src/messages/base.ts\n/** @internal */\nconst MESSAGE_SYMBOL = Symbol.for(\"langchain.message\");\nfunction mergeContent(firstContent, secondContent) {\n\tif (typeof firstContent === \"string\") {\n\t\tif (firstContent === \"\") return secondContent;\n\t\tif (typeof secondContent === \"string\") return firstContent + secondContent;\n\t\telse if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) return [{\n\t\t\ttype: \"text\",\n\t\t\tsource_type: \"text\",\n\t\t\ttext: firstContent\n\t\t}, ...secondContent];\n\t\telse return [{\n\t\t\ttype: \"text\",\n\t\t\ttext: firstContent\n\t\t}, ...secondContent];\n\t} else if (Array.isArray(secondContent)) return _mergeLists(firstContent, secondContent) ?? [...firstContent, ...secondContent];\n\telse if (secondContent === \"\") return firstContent;\n\telse if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) return [...firstContent, {\n\t\ttype: \"file\",\n\t\tsource_type: \"text\",\n\t\ttext: secondContent\n\t}];\n\telse return [...firstContent, {\n\t\ttype: \"text\",\n\t\ttext: secondContent\n\t}];\n}\n/**\n* 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n* it will return 'success'.\n*\n* @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n* @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n* @returns {\"success\" | \"error\"} The 'merged' value.\n*/\nfunction _mergeStatus(left, right) {\n\tif (left === \"error\" || right === \"error\") return \"error\";\n\treturn \"success\";\n}\nfunction stringifyWithDepthLimit(obj, depthLimit) {\n\tfunction helper(obj$1, currentDepth) {\n\t\tif (typeof obj$1 !== \"object\" || obj$1 === null || obj$1 === void 0) return obj$1;\n\t\tif (currentDepth >= depthLimit) {\n\t\t\tif (Array.isArray(obj$1)) return \"[Array]\";\n\t\t\treturn \"[Object]\";\n\t\t}\n\t\tif (Array.isArray(obj$1)) return obj$1.map((item) => helper(item, currentDepth + 1));\n\t\tconst result = {};\n\t\tfor (const key of Object.keys(obj$1)) result[key] = helper(obj$1[key], currentDepth + 1);\n\t\treturn result;\n\t}\n\treturn JSON.stringify(helper(obj, 0), null, 2);\n}\n/**\n* Base class for all types of messages in a conversation. It includes\n* properties like `content`, `name`, and `additional_kwargs`. It also\n* includes methods like `toDict()` and `_getType()`.\n*/\nvar BaseMessage = class extends Serializable {\n\tlc_namespace = [\"langchain_core\", \"messages\"];\n\tlc_serializable = true;\n\tget lc_aliases() {\n\t\treturn {\n\t\t\tadditional_kwargs: \"additional_kwargs\",\n\t\t\tresponse_metadata: \"response_metadata\"\n\t\t};\n\t}\n\t[MESSAGE_SYMBOL] = true;\n\tid;\n\tname;\n\tcontent;\n\tadditional_kwargs;\n\tresponse_metadata;\n\t/**\n\t* @deprecated Use .getType() instead or import the proper typeguard.\n\t* For example:\n\t*\n\t* ```ts\n\t* import { isAIMessage } from \"@langchain/core/messages\";\n\t*\n\t* const message = new AIMessage(\"Hello!\");\n\t* isAIMessage(message); // true\n\t* ```\n\t*/\n\t_getType() {\n\t\treturn this.type;\n\t}\n\t/**\n\t* @deprecated Use .type instead\n\t* The type of the message.\n\t*/\n\tgetType() {\n\t\treturn this._getType();\n\t}\n\tconstructor(arg) {\n\t\tconst fields = typeof arg === \"string\" || Array.isArray(arg) ? { content: arg } : arg;\n\t\tif (!fields.additional_kwargs) fields.additional_kwargs = {};\n\t\tif (!fields.response_metadata) fields.response_metadata = {};\n\t\tsuper(fields);\n\t\tthis.name = fields.name;\n\t\tif (fields.content === void 0 && fields.contentBlocks !== void 0) {\n\t\t\tthis.content = fields.contentBlocks;\n\t\t\tthis.response_metadata = {\n\t\t\t\toutput_version: \"v1\",\n\t\t\t\t...fields.response_metadata\n\t\t\t};\n\t\t} else if (fields.content !== void 0) {\n\t\t\tthis.content = fields.content ?? [];\n\t\t\tthis.response_metadata = fields.response_metadata;\n\t\t} else {\n\t\t\tthis.content = [];\n\t\t\tthis.response_metadata = fields.response_metadata;\n\t\t}\n\t\tthis.additional_kwargs = fields.additional_kwargs;\n\t\tthis.id = fields.id;\n\t}\n\t/** Get text content of the message. */\n\tget text() {\n\t\tif (typeof this.content === \"string\") return this.content;\n\t\tif (!Array.isArray(this.content)) return \"\";\n\t\treturn this.content.map((c) => {\n\t\t\tif (typeof c === \"string\") return c;\n\t\t\tif (c.type === \"text\") return c.text;\n\t\t\treturn \"\";\n\t\t}).join(\"\");\n\t}\n\tget contentBlocks() {\n\t\tconst blocks = typeof this.content === \"string\" ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: this.content\n\t\t}] : this.content;\n\t\tconst parsingSteps = [\n\t\t\tconvertToV1FromDataContent,\n\t\t\tconvertToV1FromChatCompletionsInput,\n\t\t\tconvertToV1FromAnthropicInput\n\t\t];\n\t\tconst parsedBlocks = parsingSteps.reduce((blocks$1, step) => step(blocks$1), blocks);\n\t\treturn parsedBlocks;\n\t}\n\ttoDict() {\n\t\treturn {\n\t\t\ttype: this.getType(),\n\t\t\tdata: this.toJSON().kwargs\n\t\t};\n\t}\n\tstatic lc_name() {\n\t\treturn \"BaseMessage\";\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tcontent: this.content,\n\t\t\tname: this.name,\n\t\t\tadditional_kwargs: this.additional_kwargs,\n\t\t\tresponse_metadata: this.response_metadata\n\t\t};\n\t}\n\tstatic isInstance(obj) {\n\t\treturn typeof obj === \"object\" && obj !== null && MESSAGE_SYMBOL in obj && obj[MESSAGE_SYMBOL] === true && isMessage(obj);\n\t}\n\t_updateId(value) {\n\t\tthis.id = value;\n\t\tthis.lc_kwargs.id = value;\n\t}\n\tget [Symbol.toStringTag]() {\n\t\treturn this.constructor.lc_name();\n\t}\n\t[Symbol.for(\"nodejs.util.inspect.custom\")](depth) {\n\t\tif (depth === null) return this;\n\t\tconst printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth));\n\t\treturn `${this.constructor.lc_name()} ${printable}`;\n\t}\n\ttoFormattedString(format = \"pretty\") {\n\t\treturn convertToFormattedString(this, format);\n\t}\n};\nfunction isOpenAIToolCallArray(value) {\n\treturn Array.isArray(value) && value.every((v) => typeof v.index === \"number\");\n}\nfunction _mergeDicts(left = {}, right = {}) {\n\tconst merged = { ...left };\n\tfor (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value;\n\telse if (value == null) continue;\n\telse if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);\n\telse if (typeof merged[key] === \"string\") if (key === \"type\") continue;\n\telse if ([\n\t\t\"id\",\n\t\t\"name\",\n\t\t\"output_version\",\n\t\t\"model_provider\"\n\t].includes(key)) merged[key] = value;\n\telse merged[key] += value;\n\telse if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value);\n\telse if (Array.isArray(merged[key])) merged[key] = _mergeLists(merged[key], value);\n\telse if (merged[key] === value) continue;\n\telse console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`);\n\treturn merged;\n}\nfunction _mergeLists(left, right) {\n\tif (left === void 0 && right === void 0) return void 0;\n\telse if (left === void 0 || right === void 0) return left || right;\n\telse {\n\t\tconst merged = [...left];\n\t\tfor (const item of right) if (typeof item === \"object\" && item !== null && \"index\" in item && typeof item.index === \"number\") {\n\t\t\tconst toMerge = merged.findIndex((leftItem) => {\n\t\t\t\tconst isObject = typeof leftItem === \"object\";\n\t\t\t\tconst indiciesMatch = \"index\" in leftItem && leftItem.index === item.index;\n\t\t\t\tconst idsMatch = \"id\" in leftItem && \"id\" in item && leftItem?.id === item?.id;\n\t\t\t\tconst eitherItemMissingID = !(\"id\" in leftItem) || !leftItem?.id || !(\"id\" in item) || !item?.id;\n\t\t\t\treturn isObject && indiciesMatch && (idsMatch || eitherItemMissingID);\n\t\t\t});\n\t\t\tif (toMerge !== -1 && typeof merged[toMerge] === \"object\" && merged[toMerge] !== null) merged[toMerge] = _mergeDicts(merged[toMerge], item);\n\t\t\telse merged.push(item);\n\t\t} else if (typeof item === \"object\" && item !== null && \"text\" in item && item.text === \"\") continue;\n\t\telse merged.push(item);\n\t\treturn merged;\n\t}\n}\nfunction _mergeObj(left, right) {\n\tif (!left && !right) throw new Error(\"Cannot merge two undefined objects.\");\n\tif (!left || !right) return left || right;\n\telse if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`);\n\telse if (typeof left === \"string\" && typeof right === \"string\") return left + right;\n\telse if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right);\n\telse if (typeof left === \"object\" && typeof right === \"object\") return _mergeDicts(left, right);\n\telse if (left === right) return left;\n\telse throw new Error(`Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`);\n}\n/**\n* Represents a chunk of a message, which can be concatenated with other\n* message chunks. It includes a method `_merge_kwargs_dict()` for merging\n* additional keyword arguments from another `BaseMessageChunk` into this\n* one. It also overrides the `__add__()` method to support concatenation\n* of `BaseMessageChunk` instances.\n*/\nvar BaseMessageChunk = class extends BaseMessage {\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && \"concat\" in obj && typeof obj.concat === \"function\";\n\t}\n};\nfunction _isMessageFieldWithRole(x) {\n\treturn typeof x.role === \"string\";\n}\n/**\n* @deprecated Use {@link BaseMessage.isInstance} instead\n*/\nfunction isBaseMessage(messageLike) {\n\treturn typeof messageLike?._getType === \"function\";\n}\n/**\n* @deprecated Use {@link BaseMessageChunk.isInstance} instead\n*/\nfunction isBaseMessageChunk(messageLike) {\n\treturn isBaseMessage(messageLike) && typeof messageLike.concat === \"function\";\n}\n\n//#endregion\nexport { BaseMessage, BaseMessageChunk, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, isBaseMessage, isBaseMessageChunk, isOpenAIToolCallArray, mergeContent };\n//# sourceMappingURL=base.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BaseMessage, BaseMessageChunk, _mergeDicts, _mergeObj, _mergeStatus, mergeContent } from \"./base.js\";\n\n//#region src/messages/tool.ts\nvar tool_exports = {};\n__export(tool_exports, {\n\tToolMessage: () => ToolMessage,\n\tToolMessageChunk: () => ToolMessageChunk,\n\tdefaultToolCallParser: () => defaultToolCallParser,\n\tisDirectToolOutput: () => isDirectToolOutput,\n\tisToolMessage: () => isToolMessage,\n\tisToolMessageChunk: () => isToolMessageChunk\n});\nfunction isDirectToolOutput(x) {\n\treturn x != null && typeof x === \"object\" && \"lc_direct_tool_output\" in x && x.lc_direct_tool_output === true;\n}\n/**\n* Represents a tool message in a conversation.\n*/\nvar ToolMessage = class extends BaseMessage {\n\tstatic lc_name() {\n\t\treturn \"ToolMessage\";\n\t}\n\tget lc_aliases() {\n\t\treturn { tool_call_id: \"tool_call_id\" };\n\t}\n\tlc_direct_tool_output = true;\n\ttype = \"tool\";\n\t/**\n\t* Status of the tool invocation.\n\t* @version 0.2.19\n\t*/\n\tstatus;\n\ttool_call_id;\n\tmetadata;\n\t/**\n\t* Artifact of the Tool execution which is not meant to be sent to the model.\n\t*\n\t* Should only be specified if it is different from the message content, e.g. if only\n\t* a subset of the full tool output is being passed as message content but the full\n\t* output is needed in other parts of the code.\n\t*/\n\tartifact;\n\tconstructor(fields, tool_call_id, name) {\n\t\tconst toolMessageFields = typeof fields === \"string\" || Array.isArray(fields) ? {\n\t\t\tcontent: fields,\n\t\t\tname,\n\t\t\ttool_call_id\n\t\t} : fields;\n\t\tsuper(toolMessageFields);\n\t\tthis.tool_call_id = toolMessageFields.tool_call_id;\n\t\tthis.artifact = toolMessageFields.artifact;\n\t\tthis.status = toolMessageFields.status;\n\t\tthis.metadata = toolMessageFields.metadata;\n\t}\n\tstatic isInstance(message) {\n\t\treturn super.isInstance(message) && message.type === \"tool\";\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\ttool_call_id: this.tool_call_id,\n\t\t\tartifact: this.artifact\n\t\t};\n\t}\n};\n/**\n* Represents a chunk of a tool message, which can be concatenated\n* with other tool message chunks.\n*/\nvar ToolMessageChunk = class extends BaseMessageChunk {\n\ttype = \"tool\";\n\ttool_call_id;\n\t/**\n\t* Status of the tool invocation.\n\t* @version 0.2.19\n\t*/\n\tstatus;\n\t/**\n\t* Artifact of the Tool execution which is not meant to be sent to the model.\n\t*\n\t* Should only be specified if it is different from the message content, e.g. if only\n\t* a subset of the full tool output is being passed as message content but the full\n\t* output is needed in other parts of the code.\n\t*/\n\tartifact;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.tool_call_id = fields.tool_call_id;\n\t\tthis.artifact = fields.artifact;\n\t\tthis.status = fields.status;\n\t}\n\tstatic lc_name() {\n\t\treturn \"ToolMessageChunk\";\n\t}\n\tconcat(chunk) {\n\t\tconst Cls = this.constructor;\n\t\treturn new Cls({\n\t\t\tcontent: mergeContent(this.content, chunk.content),\n\t\t\tadditional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),\n\t\t\tresponse_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),\n\t\t\tartifact: _mergeObj(this.artifact, chunk.artifact),\n\t\t\ttool_call_id: this.tool_call_id,\n\t\t\tid: this.id ?? chunk.id,\n\t\t\tstatus: _mergeStatus(this.status, chunk.status)\n\t\t});\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\ttool_call_id: this.tool_call_id,\n\t\t\tartifact: this.artifact\n\t\t};\n\t}\n};\nfunction defaultToolCallParser(rawToolCalls) {\n\tconst toolCalls = [];\n\tconst invalidToolCalls = [];\n\tfor (const toolCall of rawToolCalls) if (!toolCall.function) continue;\n\telse {\n\t\tconst functionName = toolCall.function.name;\n\t\ttry {\n\t\t\tconst functionArgs = JSON.parse(toolCall.function.arguments);\n\t\t\ttoolCalls.push({\n\t\t\t\tname: functionName || \"\",\n\t\t\t\targs: functionArgs || {},\n\t\t\t\tid: toolCall.id\n\t\t\t});\n\t\t} catch {\n\t\t\tinvalidToolCalls.push({\n\t\t\t\tname: functionName,\n\t\t\t\targs: toolCall.function.arguments,\n\t\t\t\tid: toolCall.id,\n\t\t\t\terror: \"Malformed args.\"\n\t\t\t});\n\t\t}\n\t}\n\treturn [toolCalls, invalidToolCalls];\n}\n/**\n* @deprecated Use {@link ToolMessage.isInstance} instead\n*/\nfunction isToolMessage(x) {\n\treturn typeof x === \"object\" && x !== null && \"getType\" in x && typeof x.getType === \"function\" && x.getType() === \"tool\";\n}\n/**\n* @deprecated Use {@link ToolMessageChunk.isInstance} instead\n*/\nfunction isToolMessageChunk(x) {\n\treturn x._getType() === \"tool\";\n}\n\n//#endregion\nexport { ToolMessage, ToolMessageChunk, defaultToolCallParser, isDirectToolOutput, isToolMessage, isToolMessageChunk, tool_exports };\n//# sourceMappingURL=tool.js.map","//#region src/utils/json.ts\nfunction parseJsonMarkdown(s, parser = parsePartialJson) {\n\ts = s.trim();\n\tconst firstFenceIndex = s.indexOf(\"```\");\n\tif (firstFenceIndex === -1) return parser(s);\n\tlet contentAfterFence = s.substring(firstFenceIndex + 3);\n\tif (contentAfterFence.startsWith(\"json\\n\")) contentAfterFence = contentAfterFence.substring(5);\n\telse if (contentAfterFence.startsWith(\"json\")) contentAfterFence = contentAfterFence.substring(4);\n\telse if (contentAfterFence.startsWith(\"\\n\")) contentAfterFence = contentAfterFence.substring(1);\n\tconst closingFenceIndex = contentAfterFence.indexOf(\"```\");\n\tlet finalContent = contentAfterFence;\n\tif (closingFenceIndex !== -1) finalContent = contentAfterFence.substring(0, closingFenceIndex);\n\treturn parser(finalContent.trim());\n}\nfunction parsePartialJson(s) {\n\tif (typeof s === \"undefined\") return null;\n\ttry {\n\t\treturn JSON.parse(s);\n\t} catch {}\n\tlet new_s = \"\";\n\tconst stack = [];\n\tlet isInsideString = false;\n\tlet escaped = false;\n\tfor (let char of s) {\n\t\tif (isInsideString) if (char === \"\\\"\" && !escaped) isInsideString = false;\n\t\telse if (char === \"\\n\" && !escaped) char = \"\\\\n\";\n\t\telse if (char === \"\\\\\") escaped = !escaped;\n\t\telse escaped = false;\n\t\telse if (char === \"\\\"\") {\n\t\t\tisInsideString = true;\n\t\t\tescaped = false;\n\t\t} else if (char === \"{\") stack.push(\"}\");\n\t\telse if (char === \"[\") stack.push(\"]\");\n\t\telse if (char === \"}\" || char === \"]\") if (stack && stack[stack.length - 1] === char) stack.pop();\n\t\telse return null;\n\t\tnew_s += char;\n\t}\n\tif (isInsideString) new_s += \"\\\"\";\n\tfor (let i = stack.length - 1; i >= 0; i -= 1) new_s += stack[i];\n\ttry {\n\t\treturn JSON.parse(new_s);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n//#endregion\nexport { parseJsonMarkdown, parsePartialJson };\n//# sourceMappingURL=json.js.map","import { _isArray, _isBytesArray, _isContentBlock, _isNumber, _isObject, _isString, iife } from \"./utils.js\";\n\n//#region src/messages/block_translators/bedrock_converse.ts\nfunction convertFileFormatToMimeType(format) {\n\tswitch (format) {\n\t\tcase \"csv\": return \"text/csv\";\n\t\tcase \"doc\": return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n\t\tcase \"docx\": return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n\t\tcase \"html\": return \"text/html\";\n\t\tcase \"md\": return \"text/markdown\";\n\t\tcase \"pdf\": return \"application/pdf\";\n\t\tcase \"txt\": return \"text/plain\";\n\t\tcase \"xls\": return \"application/vnd.ms-excel\";\n\t\tcase \"xlsx\": return \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";\n\t\tcase \"gif\": return \"image/gif\";\n\t\tcase \"jpeg\": return \"image/jpeg\";\n\t\tcase \"jpg\": return \"image/jpeg\";\n\t\tcase \"png\": return \"image/png\";\n\t\tcase \"webp\": return \"image/webp\";\n\t\tcase \"flv\": return \"video/flv\";\n\t\tcase \"mkv\": return \"video/mkv\";\n\t\tcase \"mov\": return \"video/mov\";\n\t\tcase \"mp4\": return \"video/mp4\";\n\t\tcase \"mpeg\": return \"video/mpeg\";\n\t\tcase \"mpg\": return \"video/mpg\";\n\t\tcase \"three_gp\": return \"video/three_gp\";\n\t\tcase \"webm\": return \"video/webm\";\n\t\tcase \"wmv\": return \"video/wmv\";\n\t\tdefault: return \"application/octet-stream\";\n\t}\n}\nfunction convertConverseDocumentBlock(block) {\n\tif (_isObject(block.document) && _isObject(block.document.source)) {\n\t\tconst format = _isObject(block.document) && _isString(block.document.format) ? block.document.format : \"\";\n\t\tconst mimeType = convertFileFormatToMimeType(format);\n\t\tif (_isObject(block.document.source)) {\n\t\t\tif (_isObject(block.document.source.s3Location) && _isString(block.document.source.s3Location.uri)) return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmimeType,\n\t\t\t\tfileId: block.document.source.s3Location.uri\n\t\t\t};\n\t\t\tif (_isBytesArray(block.document.source.bytes)) return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmimeType,\n\t\t\t\tdata: block.document.source.bytes\n\t\t\t};\n\t\t\tif (_isString(block.document.source.text)) return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmimeType,\n\t\t\t\tdata: Buffer.from(block.document.source.text).toString(\"base64\")\n\t\t\t};\n\t\t\tif (_isArray(block.document.source.content)) {\n\t\t\t\tconst data = block.document.source.content.reduce((acc, item) => {\n\t\t\t\t\tif (_isObject(item) && _isString(item.text)) return acc + item.text;\n\t\t\t\t\treturn acc;\n\t\t\t\t}, \"\");\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tmimeType,\n\t\t\t\t\tdata\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\ttype: \"non_standard\",\n\t\tvalue: block\n\t};\n}\nfunction convertConverseImageBlock(block) {\n\tif (_isContentBlock(block, \"image\") && _isObject(block.image)) {\n\t\tconst format = _isObject(block.image) && _isString(block.image.format) ? block.image.format : \"\";\n\t\tconst mimeType = convertFileFormatToMimeType(format);\n\t\tif (_isObject(block.image.source)) {\n\t\t\tif (_isObject(block.image.source.s3Location) && _isString(block.image.source.s3Location.uri)) return {\n\t\t\t\ttype: \"image\",\n\t\t\t\tmimeType,\n\t\t\t\tfileId: block.image.source.s3Location.uri\n\t\t\t};\n\t\t\tif (_isBytesArray(block.image.source.bytes)) return {\n\t\t\t\ttype: \"image\",\n\t\t\t\tmimeType,\n\t\t\t\tdata: block.image.source.bytes\n\t\t\t};\n\t\t}\n\t}\n\treturn {\n\t\ttype: \"non_standard\",\n\t\tvalue: block\n\t};\n}\nfunction convertConverseVideoBlock(block) {\n\tif (_isContentBlock(block, \"video\") && _isObject(block.video)) {\n\t\tconst format = _isObject(block.video) && _isString(block.video.format) ? block.video.format : \"\";\n\t\tconst mimeType = convertFileFormatToMimeType(format);\n\t\tif (_isObject(block.video.source)) {\n\t\t\tif (_isObject(block.video.source.s3Location) && _isString(block.video.source.s3Location.uri)) return {\n\t\t\t\ttype: \"video\",\n\t\t\t\tmimeType,\n\t\t\t\tfileId: block.video.source.s3Location.uri\n\t\t\t};\n\t\t\tif (_isBytesArray(block.video.source.bytes)) return {\n\t\t\t\ttype: \"video\",\n\t\t\t\tmimeType,\n\t\t\t\tdata: block.video.source.bytes\n\t\t\t};\n\t\t}\n\t}\n\treturn {\n\t\ttype: \"non_standard\",\n\t\tvalue: block\n\t};\n}\nfunction convertToV1FromChatBedrockConverseMessage(message) {\n\tfunction* iterateContent() {\n\t\tconst content = typeof message.content === \"string\" ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: message.content\n\t\t}] : message.content;\n\t\tfor (const block of content) {\n\t\t\tif (_isContentBlock(block, \"cache_point\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"citations_content\") && _isObject(block.citationsContent)) {\n\t\t\t\tconst text = _isArray(block.citationsContent.content) ? block.citationsContent.content.reduce((acc, item) => {\n\t\t\t\t\tif (_isObject(item) && _isString(item.text)) return acc + item.text;\n\t\t\t\t\treturn acc;\n\t\t\t\t}, \"\") : \"\";\n\t\t\t\tconst annotations = _isArray(block.citationsContent.citations) ? block.citationsContent.citations.reduce((acc, item) => {\n\t\t\t\t\tif (_isObject(item)) {\n\t\t\t\t\t\tconst citedText = _isArray(item.sourceContent) ? item.sourceContent.reduce((acc$1, item$1) => {\n\t\t\t\t\t\t\tif (_isObject(item$1) && _isString(item$1.text)) return acc$1 + item$1.text;\n\t\t\t\t\t\t\treturn acc$1;\n\t\t\t\t\t\t}, \"\") : \"\";\n\t\t\t\t\t\tconst properties = iife(() => {\n\t\t\t\t\t\t\tif (_isObject(item.location)) {\n\t\t\t\t\t\t\t\tconst location = item.location.documentChar || item.location.documentPage || item.location.documentChunk;\n\t\t\t\t\t\t\t\tif (_isObject(location)) return {\n\t\t\t\t\t\t\t\t\tsource: _isNumber(location.documentIndex) ? location.documentIndex.toString() : void 0,\n\t\t\t\t\t\t\t\t\tstartIndex: _isNumber(location.start) ? location.start : void 0,\n\t\t\t\t\t\t\t\t\tendIndex: _isNumber(location.end) ? location.end : void 0\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn {};\n\t\t\t\t\t\t});\n\t\t\t\t\t\tacc.push({\n\t\t\t\t\t\t\ttype: \"citation\",\n\t\t\t\t\t\t\tcitedText,\n\t\t\t\t\t\t\t...properties\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn acc;\n\t\t\t\t}, []) : [];\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext,\n\t\t\t\t\tannotations\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"document\") && _isObject(block.document)) {\n\t\t\t\tyield convertConverseDocumentBlock(block);\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"guard_content\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"image\") && _isObject(block.image)) {\n\t\t\t\tyield convertConverseImageBlock(block);\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"reasoning_content\") && _isString(block.reasoningText)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\treasoning: block.reasoningText\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"text\") && _isString(block.text)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: block.text\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"tool_result\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"tool_call\")) continue;\n\t\t\telse if (_isContentBlock(block, \"video\") && _isObject(block.video)) {\n\t\t\t\tyield convertConverseVideoBlock(block);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tyield {\n\t\t\t\ttype: \"non_standard\",\n\t\t\t\tvalue: block\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateContent());\n}\nconst ChatBedrockConverseTranslator = {\n\ttranslateContent: convertToV1FromChatBedrockConverseMessage,\n\ttranslateContentChunk: convertToV1FromChatBedrockConverseMessage\n};\n\n//#endregion\nexport { ChatBedrockConverseTranslator };\n//# sourceMappingURL=bedrock_converse.js.map","import { _isContentBlock, _isObject, _isString } from \"./utils.js\";\n\n//#region src/messages/block_translators/google_genai.ts\nfunction convertToV1FromChatGoogleMessage(message) {\n\tfunction* iterateContent() {\n\t\tconst content = typeof message.content === \"string\" ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: message.content\n\t\t}] : message.content;\n\t\tfor (const block of content) {\n\t\t\tif (_isContentBlock(block, \"text\") && _isString(block.text)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: block.text\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"inlineData\") && _isObject(block.inlineData) && _isString(block.inlineData.mimeType) && _isString(block.inlineData.data)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tmimeType: block.inlineData.mimeType,\n\t\t\t\t\tdata: block.inlineData.data\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"functionCall\") && _isObject(block.functionCall) && _isString(block.functionCall.name) && _isObject(block.functionCall.args)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tid: message.id,\n\t\t\t\t\tname: block.functionCall.name,\n\t\t\t\t\targs: block.functionCall.args\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"functionResponse\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"fileData\") && _isObject(block.fileData) && _isString(block.fileData.mimeType) && _isString(block.fileData.fileUri)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tmimeType: block.fileData.mimeType,\n\t\t\t\t\tfileId: block.fileData.fileUri\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"executableCode\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"codeExecutionResult\")) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"non_standard\",\n\t\t\t\t\tvalue: block\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tyield {\n\t\t\t\ttype: \"non_standard\",\n\t\t\t\tvalue: block\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateContent());\n}\nconst ChatGoogleGenAITranslator = {\n\ttranslateContent: convertToV1FromChatGoogleMessage,\n\ttranslateContentChunk: convertToV1FromChatGoogleMessage\n};\n\n//#endregion\nexport { ChatGoogleGenAITranslator };\n//# sourceMappingURL=google_genai.js.map","import { _isArray, _isContentBlock, _isString, iife } from \"./utils.js\";\n\n//#region src/messages/block_translators/google_vertexai.ts\nfunction convertToV1FromChatVertexMessage(message) {\n\tfunction* iterateContent() {\n\t\tconst content = typeof message.content === \"string\" ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: message.content\n\t\t}] : message.content;\n\t\tfor (const block of content) {\n\t\t\tif (_isContentBlock(block, \"reasoning\") && _isString(block.reasoning)) {\n\t\t\t\tconst signature = iife(() => {\n\t\t\t\t\tconst reasoningIndex = content.indexOf(block);\n\t\t\t\t\tif (_isArray(message.additional_kwargs?.signatures) && reasoningIndex >= 0) return message.additional_kwargs.signatures.at(reasoningIndex);\n\t\t\t\t\treturn void 0;\n\t\t\t\t});\n\t\t\t\tif (_isString(signature)) yield {\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\treasoning: block.reasoning,\n\t\t\t\t\tsignature\n\t\t\t\t};\n\t\t\t\telse yield {\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\treasoning: block.reasoning\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"text\") && _isString(block.text)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: block.text\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"image_url\")) {\n\t\t\t\tif (_isString(block.image_url)) if (block.image_url.startsWith(\"data:\")) {\n\t\t\t\t\tconst dataUrlRegex = /^data:([^;]+);base64,(.+)$/;\n\t\t\t\t\tconst match = block.image_url.match(dataUrlRegex);\n\t\t\t\t\tif (match) yield {\n\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\tdata: match[2],\n\t\t\t\t\t\tmimeType: match[1]\n\t\t\t\t\t};\n\t\t\t\t\telse yield {\n\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\turl: block.image_url\n\t\t\t\t\t};\n\t\t\t\t} else yield {\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\turl: block.image_url\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t} else if (_isContentBlock(block, \"media\") && _isString(block.mimeType) && _isString(block.data)) {\n\t\t\t\tyield {\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tmimeType: block.mimeType,\n\t\t\t\t\tdata: block.data\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tyield {\n\t\t\t\ttype: \"non_standard\",\n\t\t\t\tvalue: block\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateContent());\n}\nconst ChatVertexTranslator = {\n\ttranslateContent: convertToV1FromChatVertexMessage,\n\ttranslateContentChunk: convertToV1FromChatVertexMessage\n};\n\n//#endregion\nexport { ChatVertexTranslator };\n//# sourceMappingURL=google_vertexai.js.map","import { ChatAnthropicTranslator } from \"./anthropic.js\";\nimport { ChatOpenAITranslator } from \"./openai.js\";\nimport { ChatBedrockConverseTranslator } from \"./bedrock_converse.js\";\nimport { ChatGoogleGenAITranslator } from \"./google_genai.js\";\nimport { ChatVertexTranslator } from \"./google_vertexai.js\";\n\n//#region src/messages/block_translators/index.ts\nglobalThis.lc_block_translators_registry ??= new Map([\n\t[\"anthropic\", ChatAnthropicTranslator],\n\t[\"bedrock-converse\", ChatBedrockConverseTranslator],\n\t[\"google-genai\", ChatGoogleGenAITranslator],\n\t[\"google-vertexai\", ChatVertexTranslator],\n\t[\"openai\", ChatOpenAITranslator]\n]);\nfunction getTranslator(modelProvider) {\n\treturn globalThis.lc_block_translators_registry.get(modelProvider);\n}\n\n//#endregion\nexport { getTranslator };\n//# sourceMappingURL=index.js.map","import { _mergeDicts } from \"./base.js\";\n\n//#region src/messages/metadata.ts\nfunction mergeResponseMetadata(a, b) {\n\tconst output = _mergeDicts(a ?? {}, b ?? {});\n\treturn output;\n}\nfunction mergeModalitiesTokenDetails(a, b) {\n\tconst output = {};\n\tif (a?.audio !== void 0 || b?.audio !== void 0) output.audio = (a?.audio ?? 0) + (b?.audio ?? 0);\n\tif (a?.image !== void 0 || b?.image !== void 0) output.image = (a?.image ?? 0) + (b?.image ?? 0);\n\tif (a?.video !== void 0 || b?.video !== void 0) output.video = (a?.video ?? 0) + (b?.video ?? 0);\n\tif (a?.document !== void 0 || b?.document !== void 0) output.document = (a?.document ?? 0) + (b?.document ?? 0);\n\tif (a?.text !== void 0 || b?.text !== void 0) output.text = (a?.text ?? 0) + (b?.text ?? 0);\n\treturn output;\n}\nfunction mergeInputTokenDetails(a, b) {\n\tconst output = { ...mergeModalitiesTokenDetails(a, b) };\n\tif (a?.cache_read !== void 0 || b?.cache_read !== void 0) output.cache_read = (a?.cache_read ?? 0) + (b?.cache_read ?? 0);\n\tif (a?.cache_creation !== void 0 || b?.cache_creation !== void 0) output.cache_creation = (a?.cache_creation ?? 0) + (b?.cache_creation ?? 0);\n\treturn output;\n}\nfunction mergeOutputTokenDetails(a, b) {\n\tconst output = { ...mergeModalitiesTokenDetails(a, b) };\n\tif (a?.reasoning !== void 0 || b?.reasoning !== void 0) output.reasoning = (a?.reasoning ?? 0) + (b?.reasoning ?? 0);\n\treturn output;\n}\nfunction mergeUsageMetadata(a, b) {\n\treturn {\n\t\tinput_tokens: (a?.input_tokens ?? 0) + (b?.input_tokens ?? 0),\n\t\toutput_tokens: (a?.output_tokens ?? 0) + (b?.output_tokens ?? 0),\n\t\ttotal_tokens: (a?.total_tokens ?? 0) + (b?.total_tokens ?? 0),\n\t\tinput_token_details: mergeInputTokenDetails(a?.input_token_details, b?.input_token_details),\n\t\toutput_token_details: mergeOutputTokenDetails(a?.output_token_details, b?.output_token_details)\n\t};\n}\n\n//#endregion\nexport { mergeResponseMetadata, mergeUsageMetadata };\n//# sourceMappingURL=metadata.js.map","import { parsePartialJson } from \"../utils/json.js\";\nimport { BaseMessage, BaseMessageChunk, _mergeDicts, _mergeLists, mergeContent } from \"./base.js\";\nimport { getTranslator } from \"./block_translators/index.js\";\nimport { mergeResponseMetadata, mergeUsageMetadata } from \"./metadata.js\";\nimport { defaultToolCallParser } from \"./tool.js\";\n\n//#region src/messages/ai.ts\nvar AIMessage = class extends BaseMessage {\n\ttype = \"ai\";\n\ttool_calls = [];\n\tinvalid_tool_calls = [];\n\tusage_metadata;\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\ttool_calls: \"tool_calls\",\n\t\t\tinvalid_tool_calls: \"invalid_tool_calls\"\n\t\t};\n\t}\n\tconstructor(fields) {\n\t\tlet initParams;\n\t\tif (typeof fields === \"string\" || Array.isArray(fields)) initParams = {\n\t\t\tcontent: fields,\n\t\t\ttool_calls: [],\n\t\t\tinvalid_tool_calls: [],\n\t\t\tadditional_kwargs: {}\n\t\t};\n\t\telse {\n\t\t\tinitParams = fields;\n\t\t\tconst rawToolCalls = initParams.additional_kwargs?.tool_calls;\n\t\t\tconst toolCalls = initParams.tool_calls;\n\t\t\tif (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) console.warn([\n\t\t\t\t\"New LangChain packages are available that more efficiently handle\",\n\t\t\t\t\"tool calling.\\n\\nPlease upgrade your packages to versions that set\",\n\t\t\t\t\"message tool calls. e.g., `pnpm install @langchain/anthropic`,\",\n\t\t\t\t\"pnpm install @langchain/openai`, etc.\"\n\t\t\t].join(\" \"));\n\t\t\ttry {\n\t\t\t\tif (!(rawToolCalls == null) && toolCalls === void 0) {\n\t\t\t\t\tconst [toolCalls$1, invalidToolCalls] = defaultToolCallParser(rawToolCalls);\n\t\t\t\t\tinitParams.tool_calls = toolCalls$1 ?? [];\n\t\t\t\t\tinitParams.invalid_tool_calls = invalidToolCalls ?? [];\n\t\t\t\t} else {\n\t\t\t\t\tinitParams.tool_calls = initParams.tool_calls ?? [];\n\t\t\t\t\tinitParams.invalid_tool_calls = initParams.invalid_tool_calls ?? [];\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tinitParams.tool_calls = [];\n\t\t\t\tinitParams.invalid_tool_calls = [];\n\t\t\t}\n\t\t\tif (initParams.response_metadata !== void 0 && \"output_version\" in initParams.response_metadata && initParams.response_metadata.output_version === \"v1\") {\n\t\t\t\tinitParams.contentBlocks = initParams.content;\n\t\t\t\tinitParams.content = void 0;\n\t\t\t}\n\t\t\tif (initParams.contentBlocks !== void 0) {\n\t\t\t\tinitParams.contentBlocks.push(...initParams.tool_calls.map((toolCall) => ({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\targs: toolCall.args\n\t\t\t\t})));\n\t\t\t\tconst missingToolCalls = initParams.contentBlocks.filter((block) => block.type === \"tool_call\").filter((block) => !initParams.tool_calls?.some((toolCall) => toolCall.id === block.id && toolCall.name === block.name));\n\t\t\t\tif (missingToolCalls.length > 0) initParams.tool_calls = missingToolCalls.map((block) => ({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname: block.name,\n\t\t\t\t\targs: block.args\n\t\t\t\t}));\n\t\t\t}\n\t\t}\n\t\tsuper(initParams);\n\t\tif (typeof initParams !== \"string\") {\n\t\t\tthis.tool_calls = initParams.tool_calls ?? this.tool_calls;\n\t\t\tthis.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;\n\t\t}\n\t\tthis.usage_metadata = initParams.usage_metadata;\n\t}\n\tstatic lc_name() {\n\t\treturn \"AIMessage\";\n\t}\n\tget contentBlocks() {\n\t\tif (this.response_metadata && \"output_version\" in this.response_metadata && this.response_metadata.output_version === \"v1\") return this.content;\n\t\tif (this.response_metadata && \"model_provider\" in this.response_metadata && typeof this.response_metadata.model_provider === \"string\") {\n\t\t\tconst translator = getTranslator(this.response_metadata.model_provider);\n\t\t\tif (translator) return translator.translateContent(this);\n\t\t}\n\t\tconst blocks = super.contentBlocks;\n\t\tif (this.tool_calls) {\n\t\t\tconst missingToolCalls = this.tool_calls.filter((block) => !blocks.some((b) => b.id === block.id && b.name === block.name));\n\t\t\tblocks.push(...missingToolCalls.map((block) => ({\n\t\t\t\t...block,\n\t\t\t\ttype: \"tool_call\",\n\t\t\t\tid: block.id,\n\t\t\t\tname: block.name,\n\t\t\t\targs: block.args\n\t\t\t})));\n\t\t}\n\t\treturn blocks;\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\ttool_calls: this.tool_calls,\n\t\t\tinvalid_tool_calls: this.invalid_tool_calls,\n\t\t\tusage_metadata: this.usage_metadata\n\t\t};\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"ai\";\n\t}\n};\n/**\n* @deprecated Use {@link AIMessage.isInstance} instead\n*/\nfunction isAIMessage(x) {\n\treturn x._getType() === \"ai\";\n}\n/**\n* @deprecated Use {@link AIMessageChunk.isInstance} instead\n*/\nfunction isAIMessageChunk(x) {\n\treturn x._getType() === \"ai\";\n}\n/**\n* Represents a chunk of an AI message, which can be concatenated with\n* other AI message chunks.\n*/\nvar AIMessageChunk = class extends BaseMessageChunk {\n\ttype = \"ai\";\n\ttool_calls = [];\n\tinvalid_tool_calls = [];\n\ttool_call_chunks = [];\n\tusage_metadata;\n\tconstructor(fields) {\n\t\tlet initParams;\n\t\tif (typeof fields === \"string\" || Array.isArray(fields)) initParams = {\n\t\t\tcontent: fields,\n\t\t\ttool_calls: [],\n\t\t\tinvalid_tool_calls: [],\n\t\t\ttool_call_chunks: []\n\t\t};\n\t\telse if (fields.tool_call_chunks === void 0 || fields.tool_call_chunks.length === 0) initParams = {\n\t\t\t...fields,\n\t\t\ttool_calls: fields.tool_calls ?? [],\n\t\t\tinvalid_tool_calls: [],\n\t\t\ttool_call_chunks: [],\n\t\t\tusage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0\n\t\t};\n\t\telse {\n\t\t\tconst toolCallChunks = fields.tool_call_chunks ?? [];\n\t\t\tconst groupedToolCallChunks = toolCallChunks.reduce((acc, chunk) => {\n\t\t\t\tconst matchedChunkIndex = acc.findIndex(([match]) => {\n\t\t\t\t\tif (\"id\" in chunk && chunk.id && \"index\" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index;\n\t\t\t\t\tif (\"id\" in chunk && chunk.id) return chunk.id === match.id;\n\t\t\t\t\tif (\"index\" in chunk && chunk.index !== void 0) return chunk.index === match.index;\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t\tif (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk);\n\t\t\t\telse acc.push([chunk]);\n\t\t\t\treturn acc;\n\t\t\t}, []);\n\t\t\tconst toolCalls = [];\n\t\t\tconst invalidToolCalls = [];\n\t\t\tfor (const chunks of groupedToolCallChunks) {\n\t\t\t\tlet parsedArgs = null;\n\t\t\t\tconst name = chunks[0]?.name ?? \"\";\n\t\t\t\tconst joinedArgs = chunks.map((c) => c.args || \"\").join(\"\");\n\t\t\t\tconst argsStr = joinedArgs.length ? joinedArgs : \"{}\";\n\t\t\t\tconst id = chunks[0]?.id;\n\t\t\t\ttry {\n\t\t\t\t\tparsedArgs = parsePartialJson(argsStr);\n\t\t\t\t\tif (!id || parsedArgs === null || typeof parsedArgs !== \"object\" || Array.isArray(parsedArgs)) throw new Error(\"Malformed tool call chunk args.\");\n\t\t\t\t\ttoolCalls.push({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\targs: parsedArgs,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\ttype: \"tool_call\"\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\tinvalidToolCalls.push({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\targs: argsStr,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: \"Malformed args.\",\n\t\t\t\t\t\ttype: \"invalid_tool_call\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tinitParams = {\n\t\t\t\t...fields,\n\t\t\t\ttool_calls: toolCalls,\n\t\t\t\tinvalid_tool_calls: invalidToolCalls,\n\t\t\t\tusage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0\n\t\t\t};\n\t\t}\n\t\tsuper(initParams);\n\t\tthis.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks;\n\t\tthis.tool_calls = initParams.tool_calls ?? this.tool_calls;\n\t\tthis.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;\n\t\tthis.usage_metadata = initParams.usage_metadata;\n\t}\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\ttool_calls: \"tool_calls\",\n\t\t\tinvalid_tool_calls: \"invalid_tool_calls\",\n\t\t\ttool_call_chunks: \"tool_call_chunks\"\n\t\t};\n\t}\n\tstatic lc_name() {\n\t\treturn \"AIMessageChunk\";\n\t}\n\tget contentBlocks() {\n\t\tif (this.response_metadata && \"output_version\" in this.response_metadata && this.response_metadata.output_version === \"v1\") return this.content;\n\t\tif (this.response_metadata && \"model_provider\" in this.response_metadata && typeof this.response_metadata.model_provider === \"string\") {\n\t\t\tconst translator = getTranslator(this.response_metadata.model_provider);\n\t\t\tif (translator) return translator.translateContent(this);\n\t\t}\n\t\tconst blocks = super.contentBlocks;\n\t\tif (this.tool_calls) {\n\t\t\tif (typeof this.content !== \"string\") {\n\t\t\t\tconst contentToolCalls = this.content.filter((block) => block.type === \"tool_call\").map((block) => block.id);\n\t\t\t\tfor (const toolCall of this.tool_calls) if (toolCall.id && !contentToolCalls.includes(toolCall.id)) blocks.push({\n\t\t\t\t\t...toolCall,\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\targs: toolCall.args\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn blocks;\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\ttool_calls: this.tool_calls,\n\t\t\ttool_call_chunks: this.tool_call_chunks,\n\t\t\tinvalid_tool_calls: this.invalid_tool_calls,\n\t\t\tusage_metadata: this.usage_metadata\n\t\t};\n\t}\n\tconcat(chunk) {\n\t\tconst combinedFields = {\n\t\t\tcontent: mergeContent(this.content, chunk.content),\n\t\t\tadditional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),\n\t\t\tresponse_metadata: mergeResponseMetadata(this.response_metadata, chunk.response_metadata),\n\t\t\ttool_call_chunks: [],\n\t\t\tid: this.id ?? chunk.id\n\t\t};\n\t\tif (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) {\n\t\t\tconst rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks);\n\t\t\tif (rawToolCalls !== void 0 && rawToolCalls.length > 0) combinedFields.tool_call_chunks = rawToolCalls;\n\t\t}\n\t\tif (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) combinedFields.usage_metadata = mergeUsageMetadata(this.usage_metadata, chunk.usage_metadata);\n\t\tconst Cls = this.constructor;\n\t\treturn new Cls(combinedFields);\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"ai\";\n\t}\n};\n\n//#endregion\nexport { AIMessage, AIMessageChunk, isAIMessage, isAIMessageChunk };\n//# sourceMappingURL=ai.js.map","import { BaseMessage, BaseMessageChunk, _mergeDicts, mergeContent } from \"./base.js\";\n\n//#region src/messages/chat.ts\n/**\n* Represents a chat message in a conversation.\n*/\nvar ChatMessage = class ChatMessage extends BaseMessage {\n\tstatic lc_name() {\n\t\treturn \"ChatMessage\";\n\t}\n\ttype = \"generic\";\n\trole;\n\tstatic _chatMessageClass() {\n\t\treturn ChatMessage;\n\t}\n\tconstructor(fields, role) {\n\t\tif (typeof fields === \"string\" || Array.isArray(fields)) fields = {\n\t\t\tcontent: fields,\n\t\t\trole\n\t\t};\n\t\tsuper(fields);\n\t\tthis.role = fields.role;\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"generic\";\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\trole: this.role\n\t\t};\n\t}\n};\n/**\n* Represents a chunk of a chat message, which can be concatenated with\n* other chat message chunks.\n*/\nvar ChatMessageChunk = class extends BaseMessageChunk {\n\tstatic lc_name() {\n\t\treturn \"ChatMessageChunk\";\n\t}\n\ttype = \"generic\";\n\trole;\n\tconstructor(fields, role) {\n\t\tif (typeof fields === \"string\" || Array.isArray(fields)) fields = {\n\t\t\tcontent: fields,\n\t\t\trole\n\t\t};\n\t\tsuper(fields);\n\t\tthis.role = fields.role;\n\t}\n\tconcat(chunk) {\n\t\tconst Cls = this.constructor;\n\t\treturn new Cls({\n\t\t\tcontent: mergeContent(this.content, chunk.content),\n\t\t\tadditional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),\n\t\t\tresponse_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),\n\t\t\trole: this.role,\n\t\t\tid: this.id ?? chunk.id\n\t\t});\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"generic\";\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\trole: this.role\n\t\t};\n\t}\n};\n/**\n* @deprecated Use {@link ChatMessage.isInstance} instead\n*/\nfunction isChatMessage(x) {\n\treturn x._getType() === \"generic\";\n}\n/**\n* @deprecated Use {@link ChatMessageChunk.isInstance} instead\n*/\nfunction isChatMessageChunk(x) {\n\treturn x._getType() === \"generic\";\n}\n\n//#endregion\nexport { ChatMessage, ChatMessageChunk, isChatMessage, isChatMessageChunk };\n//# sourceMappingURL=chat.js.map","import { BaseMessage, BaseMessageChunk, _mergeDicts, mergeContent } from \"./base.js\";\n\n//#region src/messages/function.ts\n/**\n* Represents a function message in a conversation.\n*/\nvar FunctionMessage = class extends BaseMessage {\n\tstatic lc_name() {\n\t\treturn \"FunctionMessage\";\n\t}\n\ttype = \"function\";\n\tname;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.name = fields.name;\n\t}\n};\n/**\n* Represents a chunk of a function message, which can be concatenated\n* with other function message chunks.\n*/\nvar FunctionMessageChunk = class extends BaseMessageChunk {\n\tstatic lc_name() {\n\t\treturn \"FunctionMessageChunk\";\n\t}\n\ttype = \"function\";\n\tconcat(chunk) {\n\t\tconst Cls = this.constructor;\n\t\treturn new Cls({\n\t\t\tcontent: mergeContent(this.content, chunk.content),\n\t\t\tadditional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),\n\t\t\tresponse_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),\n\t\t\tname: this.name ?? \"\",\n\t\t\tid: this.id ?? chunk.id\n\t\t});\n\t}\n};\nfunction isFunctionMessage(x) {\n\treturn x._getType() === \"function\";\n}\nfunction isFunctionMessageChunk(x) {\n\treturn x._getType() === \"function\";\n}\n\n//#endregion\nexport { FunctionMessage, FunctionMessageChunk, isFunctionMessage, isFunctionMessageChunk };\n//# sourceMappingURL=function.js.map","import { BaseMessage, BaseMessageChunk, _mergeDicts, mergeContent } from \"./base.js\";\n\n//#region src/messages/human.ts\n/**\n* Represents a human message in a conversation.\n*/\nvar HumanMessage = class extends BaseMessage {\n\tstatic lc_name() {\n\t\treturn \"HumanMessage\";\n\t}\n\ttype = \"human\";\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"human\";\n\t}\n};\n/**\n* Represents a chunk of a human message, which can be concatenated with\n* other human message chunks.\n*/\nvar HumanMessageChunk = class extends BaseMessageChunk {\n\tstatic lc_name() {\n\t\treturn \"HumanMessageChunk\";\n\t}\n\ttype = \"human\";\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t}\n\tconcat(chunk) {\n\t\tconst Cls = this.constructor;\n\t\treturn new Cls({\n\t\t\tcontent: mergeContent(this.content, chunk.content),\n\t\t\tadditional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),\n\t\t\tresponse_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),\n\t\t\tid: this.id ?? chunk.id\n\t\t});\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"human\";\n\t}\n};\n/**\n* @deprecated Use {@link HumanMessage.isInstance} instead\n*/\nfunction isHumanMessage(x) {\n\treturn x.getType() === \"human\";\n}\n/**\n* @deprecated Use {@link HumanMessageChunk.isInstance} instead\n*/\nfunction isHumanMessageChunk(x) {\n\treturn x.getType() === \"human\";\n}\n\n//#endregion\nexport { HumanMessage, HumanMessageChunk, isHumanMessage, isHumanMessageChunk };\n//# sourceMappingURL=human.js.map","import { BaseMessage, BaseMessageChunk, _mergeDicts, mergeContent } from \"./base.js\";\n\n//#region src/messages/system.ts\n/**\n* Represents a system message in a conversation.\n*/\nvar SystemMessage = class extends BaseMessage {\n\tstatic lc_name() {\n\t\treturn \"SystemMessage\";\n\t}\n\ttype = \"system\";\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"system\";\n\t}\n};\n/**\n* Represents a chunk of a system message, which can be concatenated with\n* other system message chunks.\n*/\nvar SystemMessageChunk = class extends BaseMessageChunk {\n\tstatic lc_name() {\n\t\treturn \"SystemMessageChunk\";\n\t}\n\ttype = \"system\";\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t}\n\tconcat(chunk) {\n\t\tconst Cls = this.constructor;\n\t\treturn new Cls({\n\t\t\tcontent: mergeContent(this.content, chunk.content),\n\t\t\tadditional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),\n\t\t\tresponse_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),\n\t\t\tid: this.id ?? chunk.id\n\t\t});\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"system\";\n\t}\n};\n/**\n* @deprecated Use {@link SystemMessage.isInstance} instead\n*/\nfunction isSystemMessage(x) {\n\treturn x._getType() === \"system\";\n}\n/**\n* @deprecated Use {@link SystemMessageChunk.isInstance} instead\n*/\nfunction isSystemMessageChunk(x) {\n\treturn x._getType() === \"system\";\n}\n\n//#endregion\nexport { SystemMessage, SystemMessageChunk, isSystemMessage, isSystemMessageChunk };\n//# sourceMappingURL=system.js.map","//#region src/errors/index.ts\nfunction addLangChainErrorFields(error, lc_error_code) {\n\terror.lc_error_code = lc_error_code;\n\terror.message = `${error.message}\\n\\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\\n`;\n\treturn error;\n}\n\n//#endregion\nexport { addLangChainErrorFields };\n//# sourceMappingURL=index.js.map","//#region src/tools/utils.ts\nfunction _isToolCall(toolCall) {\n\treturn !!(toolCall && typeof toolCall === \"object\" && \"type\" in toolCall && toolCall.type === \"tool_call\");\n}\nfunction _configHasToolCallId(config) {\n\treturn !!(config && typeof config === \"object\" && \"toolCall\" in config && config.toolCall != null && typeof config.toolCall === \"object\" && \"id\" in config.toolCall && typeof config.toolCall.id === \"string\");\n}\n/**\n* Custom error class used to handle exceptions related to tool input parsing.\n* It extends the built-in `Error` class and adds an optional `output`\n* property that can hold the output that caused the exception.\n*/\nvar ToolInputParsingException = class extends Error {\n\toutput;\n\tconstructor(message, output) {\n\t\tsuper(message);\n\t\tthis.output = output;\n\t}\n};\n\n//#endregion\nexport { ToolInputParsingException, _configHasToolCallId, _isToolCall };\n//# sourceMappingURL=utils.js.map","import { BaseMessage } from \"./base.js\";\n\n//#region src/messages/modifier.ts\n/**\n* Message responsible for deleting other messages.\n*/\nvar RemoveMessage = class extends BaseMessage {\n\ttype = \"remove\";\n\t/**\n\t* The ID of the message to remove.\n\t*/\n\tid;\n\tconstructor(fields) {\n\t\tsuper({\n\t\t\t...fields,\n\t\t\tcontent: []\n\t\t});\n\t\tthis.id = fields.id;\n\t}\n\tget _printableFields() {\n\t\treturn {\n\t\t\t...super._printableFields,\n\t\t\tid: this.id\n\t\t};\n\t}\n\tstatic isInstance(obj) {\n\t\treturn super.isInstance(obj) && obj.type === \"remove\";\n\t}\n};\n\n//#endregion\nexport { RemoveMessage };\n//# sourceMappingURL=modifier.js.map","import { _isMessageFieldWithRole, isBaseMessage } from \"./base.js\";\nimport { ToolMessage } from \"./tool.js\";\nimport { AIMessage, AIMessageChunk } from \"./ai.js\";\nimport { ChatMessage, ChatMessageChunk } from \"./chat.js\";\nimport { FunctionMessage, FunctionMessageChunk } from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk } from \"./human.js\";\nimport { SystemMessage, SystemMessageChunk } from \"./system.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\nimport { _isToolCall } from \"../tools/utils.js\";\nimport { RemoveMessage } from \"./modifier.js\";\n\n//#region src/messages/utils.ts\n/**\n* Immediately-invoked function expression.\n*\n* @param fn - The function to execute\n* @returns The result of the function\n*/\nconst iife = (fn) => fn();\nfunction _coerceToolCall(toolCall) {\n\tif (_isToolCall(toolCall)) return toolCall;\n\telse if (typeof toolCall.id === \"string\" && toolCall.type === \"function\" && typeof toolCall.function === \"object\" && toolCall.function !== null && \"arguments\" in toolCall.function && typeof toolCall.function.arguments === \"string\" && \"name\" in toolCall.function && typeof toolCall.function.name === \"string\") return {\n\t\tid: toolCall.id,\n\t\targs: JSON.parse(toolCall.function.arguments),\n\t\tname: toolCall.function.name,\n\t\ttype: \"tool_call\"\n\t};\n\telse return toolCall;\n}\nfunction isSerializedConstructor(x) {\n\treturn typeof x === \"object\" && x != null && x.lc === 1 && Array.isArray(x.id) && x.kwargs != null && typeof x.kwargs === \"object\";\n}\nfunction _constructMessageFromParams(params) {\n\tlet type;\n\tlet rest;\n\tif (isSerializedConstructor(params)) {\n\t\tconst className = params.id.at(-1);\n\t\tif (className === \"HumanMessage\" || className === \"HumanMessageChunk\") type = \"user\";\n\t\telse if (className === \"AIMessage\" || className === \"AIMessageChunk\") type = \"assistant\";\n\t\telse if (className === \"SystemMessage\" || className === \"SystemMessageChunk\") type = \"system\";\n\t\telse if (className === \"FunctionMessage\" || className === \"FunctionMessageChunk\") type = \"function\";\n\t\telse if (className === \"ToolMessage\" || className === \"ToolMessageChunk\") type = \"tool\";\n\t\telse type = \"unknown\";\n\t\trest = params.kwargs;\n\t} else {\n\t\tconst { type: extractedType,...otherParams } = params;\n\t\ttype = extractedType;\n\t\trest = otherParams;\n\t}\n\tif (type === \"human\" || type === \"user\") return new HumanMessage(rest);\n\telse if (type === \"ai\" || type === \"assistant\") {\n\t\tconst { tool_calls: rawToolCalls,...other } = rest;\n\t\tif (!Array.isArray(rawToolCalls)) return new AIMessage(rest);\n\t\tconst tool_calls = rawToolCalls.map(_coerceToolCall);\n\t\treturn new AIMessage({\n\t\t\t...other,\n\t\t\ttool_calls\n\t\t});\n\t} else if (type === \"system\") return new SystemMessage(rest);\n\telse if (type === \"developer\") return new SystemMessage({\n\t\t...rest,\n\t\tadditional_kwargs: {\n\t\t\t...rest.additional_kwargs,\n\t\t\t__openai_role__: \"developer\"\n\t\t}\n\t});\n\telse if (type === \"tool\" && \"tool_call_id\" in rest) return new ToolMessage({\n\t\t...rest,\n\t\tcontent: rest.content,\n\t\ttool_call_id: rest.tool_call_id,\n\t\tname: rest.name\n\t});\n\telse if (type === \"remove\" && \"id\" in rest && typeof rest.id === \"string\") return new RemoveMessage({\n\t\t...rest,\n\t\tid: rest.id\n\t});\n\telse {\n\t\tconst error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\\n\\nReceived: ${JSON.stringify(params, null, 2)}`), \"MESSAGE_COERCION_FAILURE\");\n\t\tthrow error;\n\t}\n}\nfunction coerceMessageLikeToMessage(messageLike) {\n\tif (typeof messageLike === \"string\") return new HumanMessage(messageLike);\n\telse if (isBaseMessage(messageLike)) return messageLike;\n\tif (Array.isArray(messageLike)) {\n\t\tconst [type, content] = messageLike;\n\t\treturn _constructMessageFromParams({\n\t\t\ttype,\n\t\t\tcontent\n\t\t});\n\t} else if (_isMessageFieldWithRole(messageLike)) {\n\t\tconst { role: type,...rest } = messageLike;\n\t\treturn _constructMessageFromParams({\n\t\t\t...rest,\n\t\t\ttype\n\t\t});\n\t} else return _constructMessageFromParams(messageLike);\n}\n/**\n* This function is used by memory classes to get a string representation\n* of the chat message history, based on the message content and role.\n*/\nfunction getBufferString(messages, humanPrefix = \"Human\", aiPrefix = \"AI\") {\n\tconst string_messages = [];\n\tfor (const m of messages) {\n\t\tlet role;\n\t\tif (m._getType() === \"human\") role = humanPrefix;\n\t\telse if (m._getType() === \"ai\") role = aiPrefix;\n\t\telse if (m._getType() === \"system\") role = \"System\";\n\t\telse if (m._getType() === \"tool\") role = \"Tool\";\n\t\telse if (m._getType() === \"generic\") role = m.role;\n\t\telse throw new Error(`Got unsupported message type: ${m._getType()}`);\n\t\tconst nameStr = m.name ? `${m.name}, ` : \"\";\n\t\tconst readableContent = typeof m.content === \"string\" ? m.content : JSON.stringify(m.content, null, 2);\n\t\tstring_messages.push(`${role}: ${nameStr}${readableContent}`);\n\t}\n\treturn string_messages.join(\"\\n\");\n}\n/**\n* Maps messages from an older format (V1) to the current `StoredMessage`\n* format. If the message is already in the `StoredMessage` format, it is\n* returned as is. Otherwise, it transforms the V1 message into a\n* `StoredMessage`. This function is important for maintaining\n* compatibility with older message formats.\n*/\nfunction mapV1MessageToStoredMessage(message) {\n\tif (message.data !== void 0) return message;\n\telse {\n\t\tconst v1Message = message;\n\t\treturn {\n\t\t\ttype: v1Message.type,\n\t\t\tdata: {\n\t\t\t\tcontent: v1Message.text,\n\t\t\t\trole: v1Message.role,\n\t\t\t\tname: void 0,\n\t\t\t\ttool_call_id: void 0\n\t\t\t}\n\t\t};\n\t}\n}\nfunction mapStoredMessageToChatMessage(message) {\n\tconst storedMessage = mapV1MessageToStoredMessage(message);\n\tswitch (storedMessage.type) {\n\t\tcase \"human\": return new HumanMessage(storedMessage.data);\n\t\tcase \"ai\": return new AIMessage(storedMessage.data);\n\t\tcase \"system\": return new SystemMessage(storedMessage.data);\n\t\tcase \"function\":\n\t\t\tif (storedMessage.data.name === void 0) throw new Error(\"Name must be defined for function messages\");\n\t\t\treturn new FunctionMessage(storedMessage.data);\n\t\tcase \"tool\":\n\t\t\tif (storedMessage.data.tool_call_id === void 0) throw new Error(\"Tool call ID must be defined for tool messages\");\n\t\t\treturn new ToolMessage(storedMessage.data);\n\t\tcase \"generic\":\n\t\t\tif (storedMessage.data.role === void 0) throw new Error(\"Role must be defined for chat messages\");\n\t\t\treturn new ChatMessage(storedMessage.data);\n\t\tdefault: throw new Error(`Got unexpected type: ${storedMessage.type}`);\n\t}\n}\n/**\n* Transforms an array of `StoredMessage` instances into an array of\n* `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage`\n* function to ensure all messages are in the `StoredMessage` format, then\n* creates new instances of the appropriate `BaseMessage` subclass based\n* on the type of each message. This function is used to prepare stored\n* messages for use in a chat context.\n*/\nfunction mapStoredMessagesToChatMessages(messages) {\n\treturn messages.map(mapStoredMessageToChatMessage);\n}\n/**\n* Transforms an array of `BaseMessage` instances into an array of\n* `StoredMessage` instances. It does this by calling the `toDict` method\n* on each `BaseMessage`, which returns a `StoredMessage`. This function\n* is used to prepare chat messages for storage.\n*/\nfunction mapChatMessagesToStoredMessages(messages) {\n\treturn messages.map((message) => message.toDict());\n}\nfunction convertToChunk(message) {\n\tconst type = message._getType();\n\tif (type === \"human\") return new HumanMessageChunk({ ...message });\n\telse if (type === \"ai\") {\n\t\tlet aiChunkFields = { ...message };\n\t\tif (\"tool_calls\" in aiChunkFields) aiChunkFields = {\n\t\t\t...aiChunkFields,\n\t\t\ttool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n\t\t\t\t...tc,\n\t\t\t\ttype: \"tool_call_chunk\",\n\t\t\t\tindex: void 0,\n\t\t\t\targs: JSON.stringify(tc.args)\n\t\t\t}))\n\t\t};\n\t\treturn new AIMessageChunk({ ...aiChunkFields });\n\t} else if (type === \"system\") return new SystemMessageChunk({ ...message });\n\telse if (type === \"function\") return new FunctionMessageChunk({ ...message });\n\telse if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message });\n\telse throw new Error(\"Unknown message type.\");\n}\n\n//#endregion\nexport { coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };\n//# sourceMappingURL=utils.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\n\n//#region src/utils/env.ts\nvar env_exports = {};\n__export(env_exports, {\n\tgetEnv: () => getEnv,\n\tgetEnvironmentVariable: () => getEnvironmentVariable,\n\tgetRuntimeEnvironment: () => getRuntimeEnvironment,\n\tisBrowser: () => isBrowser,\n\tisDeno: () => isDeno,\n\tisJsDom: () => isJsDom,\n\tisNode: () => isNode,\n\tisWebWorker: () => isWebWorker\n});\nconst isBrowser = () => typeof window !== \"undefined\" && typeof window.document !== \"undefined\";\nconst isWebWorker = () => typeof globalThis === \"object\" && globalThis.constructor && globalThis.constructor.name === \"DedicatedWorkerGlobalScope\";\nconst isJsDom = () => typeof window !== \"undefined\" && window.name === \"nodejs\" || typeof navigator !== \"undefined\" && navigator.userAgent.includes(\"jsdom\");\nconst isDeno = () => typeof Deno !== \"undefined\";\nconst isNode = () => typeof process !== \"undefined\" && typeof process.versions !== \"undefined\" && typeof process.versions.node !== \"undefined\" && !isDeno();\nconst getEnv = () => {\n\tlet env;\n\tif (isBrowser()) env = \"browser\";\n\telse if (isNode()) env = \"node\";\n\telse if (isWebWorker()) env = \"webworker\";\n\telse if (isJsDom()) env = \"jsdom\";\n\telse if (isDeno()) env = \"deno\";\n\telse env = \"other\";\n\treturn env;\n};\nlet runtimeEnvironment;\nfunction getRuntimeEnvironment() {\n\tif (runtimeEnvironment === void 0) {\n\t\tconst env = getEnv();\n\t\truntimeEnvironment = {\n\t\t\tlibrary: \"langchain-js\",\n\t\t\truntime: env\n\t\t};\n\t}\n\treturn runtimeEnvironment;\n}\nfunction getEnvironmentVariable(name) {\n\ttry {\n\t\tif (typeof process !== \"undefined\") return process.env?.[name];\n\t\telse if (isDeno()) return Deno?.env.get(name);\n\t\telse return void 0;\n\t} catch {\n\t\treturn void 0;\n\t}\n}\n\n//#endregion\nexport { env_exports, getEnv, getEnvironmentVariable, getRuntimeEnvironment, isBrowser, isDeno, isJsDom, isNode, isWebWorker };\n//# sourceMappingURL=env.js.map","import uuid from './dist/index.js';\nexport const v1 = uuid.v1;\nexport const v1ToV6 = uuid.v1ToV6;\nexport const v3 = uuid.v3;\nexport const v4 = uuid.v4;\nexport const v5 = uuid.v5;\nexport const v6 = uuid.v6;\nexport const v6ToV1 = uuid.v6ToV1;\nexport const v7 = uuid.v7;\nexport const NIL = uuid.NIL;\nexport const MAX = uuid.MAX;\nexport const version = uuid.version;\nexport const validate = uuid.validate;\nexport const stringify = uuid.stringify;\nexport const parse = uuid.parse;\n","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { Serializable, get_lc_unique_name } from \"../load/serializable.js\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\nimport * as uuid from \"uuid\";\n\n//#region src/callbacks/base.ts\nvar base_exports = {};\n__export(base_exports, {\n\tBaseCallbackHandler: () => BaseCallbackHandler,\n\tcallbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming,\n\tisBaseCallbackHandler: () => isBaseCallbackHandler\n});\n/**\n* Abstract class that provides a set of optional methods that can be\n* overridden in derived classes to handle various events during the\n* execution of a LangChain application.\n*/\nvar BaseCallbackHandlerMethodsClass = class {};\nfunction callbackHandlerPrefersStreaming(x) {\n\treturn \"lc_prefer_streaming\" in x && x.lc_prefer_streaming;\n}\n/**\n* Abstract base class for creating callback handlers in the LangChain\n* framework. It provides a set of optional methods that can be overridden\n* in derived classes to handle various events during the execution of a\n* LangChain application.\n*/\nvar BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass {\n\tlc_serializable = false;\n\tget lc_namespace() {\n\t\treturn [\n\t\t\t\"langchain_core\",\n\t\t\t\"callbacks\",\n\t\t\tthis.name\n\t\t];\n\t}\n\tget lc_secrets() {\n\t\treturn void 0;\n\t}\n\tget lc_attributes() {\n\t\treturn void 0;\n\t}\n\tget lc_aliases() {\n\t\treturn void 0;\n\t}\n\tget lc_serializable_keys() {\n\t\treturn void 0;\n\t}\n\t/**\n\t* The name of the serializable. Override to provide an alias or\n\t* to preserve the serialized module name in minified environments.\n\t*\n\t* Implemented as a static method to support loading logic.\n\t*/\n\tstatic lc_name() {\n\t\treturn this.name;\n\t}\n\t/**\n\t* The final serialized identifier for the module.\n\t*/\n\tget lc_id() {\n\t\treturn [...this.lc_namespace, get_lc_unique_name(this.constructor)];\n\t}\n\tlc_kwargs;\n\tignoreLLM = false;\n\tignoreChain = false;\n\tignoreAgent = false;\n\tignoreRetriever = false;\n\tignoreCustomEvent = false;\n\traiseError = false;\n\tawaitHandlers = getEnvironmentVariable(\"LANGCHAIN_CALLBACKS_BACKGROUND\") === \"false\";\n\tconstructor(input) {\n\t\tsuper();\n\t\tthis.lc_kwargs = input || {};\n\t\tif (input) {\n\t\t\tthis.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;\n\t\t\tthis.ignoreChain = input.ignoreChain ?? this.ignoreChain;\n\t\t\tthis.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;\n\t\t\tthis.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;\n\t\t\tthis.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent;\n\t\t\tthis.raiseError = input.raiseError ?? this.raiseError;\n\t\t\tthis.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers);\n\t\t}\n\t}\n\tcopy() {\n\t\treturn new this.constructor(this);\n\t}\n\ttoJSON() {\n\t\treturn Serializable.prototype.toJSON.call(this);\n\t}\n\ttoJSONNotImplemented() {\n\t\treturn Serializable.prototype.toJSONNotImplemented.call(this);\n\t}\n\tstatic fromMethods(methods) {\n\t\tclass Handler extends BaseCallbackHandler {\n\t\t\tname = uuid.v4();\n\t\t\tconstructor() {\n\t\t\t\tsuper();\n\t\t\t\tObject.assign(this, methods);\n\t\t\t}\n\t\t}\n\t\treturn new Handler();\n\t}\n};\nconst isBaseCallbackHandler = (x) => {\n\tconst callbackHandler = x;\n\treturn callbackHandler !== void 0 && typeof callbackHandler.copy === \"function\" && typeof callbackHandler.name === \"string\" && typeof callbackHandler.awaitHandlers === \"boolean\";\n};\n\n//#endregion\nexport { BaseCallbackHandler, base_exports, callbackHandlerPrefersStreaming, isBaseCallbackHandler };\n//# sourceMappingURL=base.js.map","import uuid from './dist/index.js';\nexport const v1 = uuid.v1;\nexport const v1ToV6 = uuid.v1ToV6;\nexport const v3 = uuid.v3;\nexport const v4 = uuid.v4;\nexport const v5 = uuid.v5;\nexport const v6 = uuid.v6;\nexport const v6ToV1 = uuid.v6ToV1;\nexport const v7 = uuid.v7;\nexport const NIL = uuid.NIL;\nexport const MAX = uuid.MAX;\nexport const version = uuid.version;\nexport const validate = uuid.validate;\nexport const stringify = uuid.stringify;\nexport const parse = uuid.parse;\n","// OpenTelemetry GenAI semantic convention attribute names\nexport const GEN_AI_OPERATION_NAME = \"gen_ai.operation.name\";\nexport const GEN_AI_SYSTEM = \"gen_ai.system\";\nexport const GEN_AI_REQUEST_MODEL = \"gen_ai.request.model\";\nexport const GEN_AI_RESPONSE_MODEL = \"gen_ai.response.model\";\nexport const GEN_AI_USAGE_INPUT_TOKENS = \"gen_ai.usage.input_tokens\";\nexport const GEN_AI_USAGE_OUTPUT_TOKENS = \"gen_ai.usage.output_tokens\";\nexport const GEN_AI_USAGE_TOTAL_TOKENS = \"gen_ai.usage.total_tokens\";\nexport const GEN_AI_REQUEST_MAX_TOKENS = \"gen_ai.request.max_tokens\";\nexport const GEN_AI_REQUEST_TEMPERATURE = \"gen_ai.request.temperature\";\nexport const GEN_AI_REQUEST_TOP_P = \"gen_ai.request.top_p\";\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY = \"gen_ai.request.frequency_penalty\";\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY = \"gen_ai.request.presence_penalty\";\nexport const GEN_AI_RESPONSE_FINISH_REASONS = \"gen_ai.response.finish_reasons\";\nexport const GENAI_PROMPT = \"gen_ai.prompt\";\nexport const GENAI_COMPLETION = \"gen_ai.completion\";\nexport const GEN_AI_REQUEST_EXTRA_QUERY = \"gen_ai.request.extra_query\";\nexport const GEN_AI_REQUEST_EXTRA_BODY = \"gen_ai.request.extra_body\";\nexport const GEN_AI_SERIALIZED_NAME = \"gen_ai.serialized.name\";\nexport const GEN_AI_SERIALIZED_SIGNATURE = \"gen_ai.serialized.signature\";\nexport const GEN_AI_SERIALIZED_DOC = \"gen_ai.serialized.doc\";\nexport const GEN_AI_RESPONSE_ID = \"gen_ai.response.id\";\nexport const GEN_AI_RESPONSE_SERVICE_TIER = \"gen_ai.response.service_tier\";\nexport const GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = \"gen_ai.response.system_fingerprint\";\nexport const GEN_AI_USAGE_INPUT_TOKEN_DETAILS = \"gen_ai.usage.input_token_details\";\nexport const GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = \"gen_ai.usage.output_token_details\";\n// LangSmith custom attributes\nexport const LANGSMITH_SESSION_ID = \"langsmith.trace.session_id\";\nexport const LANGSMITH_SESSION_NAME = \"langsmith.trace.session_name\";\nexport const LANGSMITH_RUN_TYPE = \"langsmith.span.kind\";\nexport const LANGSMITH_NAME = \"langsmith.trace.name\";\nexport const LANGSMITH_METADATA = \"langsmith.metadata\";\nexport const LANGSMITH_TAGS = \"langsmith.span.tags\";\nexport const LANGSMITH_RUNTIME = \"langsmith.span.runtime\";\nexport const LANGSMITH_REQUEST_STREAMING = \"langsmith.request.streaming\";\nexport const LANGSMITH_REQUEST_HEADERS = \"langsmith.request.headers\";\nexport const LANGSMITH_RUN_ID = \"langsmith.span.id\";\nexport const LANGSMITH_TRACE_ID = \"langsmith.trace.id\";\nexport const LANGSMITH_DOTTED_ORDER = \"langsmith.span.dotted_order\";\nexport const LANGSMITH_PARENT_RUN_ID = \"langsmith.span.parent_id\";\nexport const LANGSMITH_USAGE_METADATA = \"langsmith.usage_metadata\";\nexport const LANGSMITH_REFERENCE_EXAMPLE_ID = \"langsmith.reference_example_id\";\nexport const LANGSMITH_TRACEABLE = \"langsmith.traceable\";\nexport const LANGSMITH_IS_ROOT = \"langsmith.is_root\";\nexport const LANGSMITH_TRACEABLE_PARENT_OTEL_SPAN_ID = \"langsmith.traceable_parent_otel_span_id\";\n// GenAI event names\nexport const GEN_AI_SYSTEM_MESSAGE = \"gen_ai.system.message\";\nexport const GEN_AI_USER_MESSAGE = \"gen_ai.user.message\";\nexport const GEN_AI_ASSISTANT_MESSAGE = \"gen_ai.assistant.message\";\nexport const GEN_AI_CHOICE = \"gen_ai.choice\";\nexport const AI_SDK_LLM_OPERATIONS = [\n \"ai.generateText.doGenerate\",\n \"ai.streamText.doStream\",\n \"ai.generateObject.doGenerate\",\n \"ai.streamObject.doStream\",\n];\nexport const AI_SDK_TOOL_OPERATIONS = [\"ai.toolCall\"];\n","import { getLangSmithEnvironmentVariable } from \"../utils/env.js\";\n// Wrap the default fetch call due to issues with illegal invocations\n// in some environments:\n// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err\n// @ts-expect-error Broad typing to support a range of fetch implementations\nconst DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args);\nconst LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for(\"ls:fetch_implementation\");\n/**\n * Overrides the fetch implementation used for LangSmith calls.\n * You should use this if you need to use an implementation of fetch\n * other than the default global (e.g. for dealing with proxies).\n * @param fetch The new fetch functino to use.\n */\nexport const overrideFetchImplementation = (fetch) => {\n globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch;\n};\nexport const clearFetchImplementation = () => {\n delete globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY];\n};\nexport const _globalFetchImplementationIsNodeFetch = () => {\n const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY];\n if (!fetchImpl)\n return false;\n // Check if the implementation has node-fetch specific properties\n return (typeof fetchImpl === \"function\" &&\n \"Headers\" in fetchImpl &&\n \"Request\" in fetchImpl &&\n \"Response\" in fetchImpl);\n};\n/**\n * @internal\n */\nexport const _getFetchImplementation = (debug) => {\n return async (...args) => {\n if (debug || getLangSmithEnvironmentVariable(\"DEBUG\") === \"true\") {\n const [url, options] = args;\n console.log(`→ ${options?.method || \"GET\"} ${url}`);\n }\n const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ??\n DEFAULT_FETCH_IMPLEMENTATION)(...args);\n if (debug || getLangSmithEnvironmentVariable(\"DEBUG\") === \"true\") {\n console.log(`← ${res.status} ${res.statusText} ${res.url}`);\n }\n return res;\n };\n};\n","import { getEnvironmentVariable, getLangSmithEnvironmentVariable, } from \"./env.js\";\nexport const getDefaultProjectName = () => {\n return (getLangSmithEnvironmentVariable(\"PROJECT\") ??\n getEnvironmentVariable(\"LANGCHAIN_SESSION\") ?? // TODO: Deprecate\n \"default\");\n};\n","export { Client, } from \"./client.js\";\nexport { RunTree } from \"./run_trees.js\";\nexport { overrideFetchImplementation } from \"./singletons/fetch.js\";\nexport { getDefaultProjectName } from \"./utils/project.js\";\n// Update using yarn bump-version\nexport const __version__ = \"0.3.79\";\n","// Inlined from https://github.com/flexdinesh/browser-or-node\nimport { __version__ } from \"../index.js\";\nlet globalEnv;\nexport const isBrowser = () => typeof window !== \"undefined\" && typeof window.document !== \"undefined\";\nexport const isWebWorker = () => typeof globalThis === \"object\" &&\n globalThis.constructor &&\n globalThis.constructor.name === \"DedicatedWorkerGlobalScope\";\nexport const isJsDom = () => (typeof window !== \"undefined\" && window.name === \"nodejs\") ||\n (typeof navigator !== \"undefined\" && navigator.userAgent.includes(\"jsdom\"));\n// Supabase Edge Function provides a `Deno` global object\n// without `version` property\nexport const isDeno = () => typeof Deno !== \"undefined\";\n// Mark not-as-node if in Supabase Edge Function\nexport const isNode = () => typeof process !== \"undefined\" &&\n typeof process.versions !== \"undefined\" &&\n typeof process.versions.node !== \"undefined\" &&\n !isDeno();\nexport const getEnv = () => {\n if (globalEnv) {\n return globalEnv;\n }\n // @ts-expect-error Bun types are not imported due to conflicts with Node types\n if (typeof Bun !== \"undefined\") {\n globalEnv = \"bun\";\n }\n else if (isBrowser()) {\n globalEnv = \"browser\";\n }\n else if (isNode()) {\n globalEnv = \"node\";\n }\n else if (isWebWorker()) {\n globalEnv = \"webworker\";\n }\n else if (isJsDom()) {\n globalEnv = \"jsdom\";\n }\n else if (isDeno()) {\n globalEnv = \"deno\";\n }\n else {\n globalEnv = \"other\";\n }\n return globalEnv;\n};\nlet runtimeEnvironment;\nexport function getRuntimeEnvironment() {\n if (runtimeEnvironment === undefined) {\n const env = getEnv();\n const releaseEnv = getShas();\n runtimeEnvironment = {\n library: \"langsmith\",\n runtime: env,\n sdk: \"langsmith-js\",\n sdk_version: __version__,\n ...releaseEnv,\n };\n }\n return runtimeEnvironment;\n}\n/**\n * Retrieves the LangSmith-specific metadata from the current runtime environment.\n *\n * @returns {Record}\n * - A record of LangSmith-specific metadata environment variables.\n */\nexport function getLangSmithEnvVarsMetadata() {\n const allEnvVars = getLangSmithEnvironmentVariables();\n const envVars = {};\n const excluded = [\n \"LANGCHAIN_API_KEY\",\n \"LANGCHAIN_ENDPOINT\",\n \"LANGCHAIN_TRACING_V2\",\n \"LANGCHAIN_PROJECT\",\n \"LANGCHAIN_SESSION\",\n \"LANGSMITH_API_KEY\",\n \"LANGSMITH_ENDPOINT\",\n \"LANGSMITH_TRACING_V2\",\n \"LANGSMITH_PROJECT\",\n \"LANGSMITH_SESSION\",\n ];\n for (const [key, value] of Object.entries(allEnvVars)) {\n if (typeof value === \"string\" &&\n !excluded.includes(key) &&\n !key.toLowerCase().includes(\"key\") &&\n !key.toLowerCase().includes(\"secret\") &&\n !key.toLowerCase().includes(\"token\")) {\n if (key === \"LANGCHAIN_REVISION_ID\") {\n envVars[\"revision_id\"] = value;\n }\n else {\n envVars[key] = value;\n }\n }\n }\n return envVars;\n}\n/**\n * Retrieves only the LangChain/LangSmith-prefixed environment variables from the current runtime environment.\n * This is more efficient than copying all environment variables.\n *\n * @returns {Record}\n * - A record of LangChain/LangSmith environment variables.\n */\nexport function getLangSmithEnvironmentVariables() {\n const envVars = {};\n try {\n // Check for Node.js environment\n // eslint-disable-next-line no-process-env\n if (typeof process !== \"undefined\" && process.env) {\n // eslint-disable-next-line no-process-env\n for (const [key, value] of Object.entries(process.env)) {\n if ((key.startsWith(\"LANGCHAIN_\") || key.startsWith(\"LANGSMITH_\")) &&\n value != null) {\n if ((key.toLowerCase().includes(\"key\") ||\n key.toLowerCase().includes(\"secret\") ||\n key.toLowerCase().includes(\"token\")) &&\n typeof value === \"string\") {\n envVars[key] =\n value.slice(0, 2) +\n \"*\".repeat(value.length - 4) +\n value.slice(-2);\n }\n else {\n envVars[key] = value;\n }\n }\n }\n }\n }\n catch (e) {\n // Catch any errors that might occur while trying to access environment variables\n }\n return envVars;\n}\nexport function getEnvironmentVariable(name) {\n // Certain Deno setups will throw an error if you try to access environment variables\n // https://github.com/hwchase17/langchainjs/issues/1412\n try {\n return typeof process !== \"undefined\"\n ? // eslint-disable-next-line no-process-env\n process.env?.[name]\n : undefined;\n }\n catch (e) {\n return undefined;\n }\n}\nexport function getLangSmithEnvironmentVariable(name) {\n return (getEnvironmentVariable(`LANGSMITH_${name}`) ||\n getEnvironmentVariable(`LANGCHAIN_${name}`));\n}\nexport function setEnvironmentVariable(name, value) {\n if (typeof process !== \"undefined\") {\n // eslint-disable-next-line no-process-env\n process.env[name] = value;\n }\n}\nlet cachedCommitSHAs;\n/**\n * Get the Git commit SHA from common environment variables\n * used by different CI/CD platforms.\n * @returns {string | undefined} The Git commit SHA or undefined if not found.\n */\nexport function getShas() {\n if (cachedCommitSHAs !== undefined) {\n return cachedCommitSHAs;\n }\n const common_release_envs = [\n \"VERCEL_GIT_COMMIT_SHA\",\n \"NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA\",\n \"COMMIT_REF\",\n \"RENDER_GIT_COMMIT\",\n \"CI_COMMIT_SHA\",\n \"CIRCLE_SHA1\",\n \"CF_PAGES_COMMIT_SHA\",\n \"REACT_APP_GIT_SHA\",\n \"SOURCE_VERSION\",\n \"GITHUB_SHA\",\n \"TRAVIS_COMMIT\",\n \"GIT_COMMIT\",\n \"BUILD_VCS_NUMBER\",\n \"bamboo_planRepository_revision\",\n \"Build.SourceVersion\",\n \"BITBUCKET_COMMIT\",\n \"DRONE_COMMIT_SHA\",\n \"SEMAPHORE_GIT_SHA\",\n \"BUILDKITE_COMMIT\",\n ];\n const shas = {};\n for (const env of common_release_envs) {\n const envVar = getEnvironmentVariable(env);\n if (envVar !== undefined) {\n shas[env] = envVar;\n }\n }\n cachedCommitSHAs = shas;\n return shas;\n}\nexport function getOtelEnabled() {\n return (getEnvironmentVariable(\"OTEL_ENABLED\") === \"true\" ||\n getLangSmithEnvironmentVariable(\"OTEL_ENABLED\") === \"true\");\n}\n","// Should not import any OTEL packages to avoid pulling in optional deps.\nimport { getOtelEnabled } from \"../utils/env.js\";\nclass MockTracer {\n constructor() {\n Object.defineProperty(this, \"hasWarned\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n }\n startActiveSpan(_name, ...args) {\n if (!this.hasWarned && getOtelEnabled()) {\n console.warn(\"You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. \" +\n 'Please add:\\n```\\nimport { initializeOTEL } from \"langsmith/experimental/otel/setup\";\\ninitializeOTEL();\\n```\\nat the beginning of your code.');\n this.hasWarned = true;\n }\n // Handle different overloads:\n // startActiveSpan(name, fn)\n // startActiveSpan(name, options, fn)\n // startActiveSpan(name, options, context, fn)\n let fn;\n if (args.length === 1 && typeof args[0] === \"function\") {\n fn = args[0];\n }\n else if (args.length === 2 && typeof args[1] === \"function\") {\n fn = args[1];\n }\n else if (args.length === 3 && typeof args[2] === \"function\") {\n fn = args[2];\n }\n if (typeof fn === \"function\") {\n return fn();\n }\n return undefined;\n }\n}\nclass MockOTELTrace {\n constructor() {\n Object.defineProperty(this, \"mockTracer\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new MockTracer()\n });\n }\n getTracer(_name, _version) {\n return this.mockTracer;\n }\n getActiveSpan() {\n return undefined;\n }\n setSpan(context, _span) {\n return context;\n }\n getSpan(_context) {\n return undefined;\n }\n setSpanContext(context, _spanContext) {\n return context;\n }\n getTracerProvider() {\n return undefined;\n }\n setGlobalTracerProvider(_tracerProvider) {\n return false;\n }\n}\nclass MockOTELContext {\n active() {\n return {};\n }\n with(_context, fn) {\n return fn();\n }\n}\nconst OTEL_TRACE_KEY = Symbol.for(\"ls:otel_trace\");\nconst OTEL_CONTEXT_KEY = Symbol.for(\"ls:otel_context\");\nconst OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for(\"ls:otel_get_default_otlp_tracer_provider\");\nconst mockOTELTrace = new MockOTELTrace();\nconst mockOTELContext = new MockOTELContext();\nclass OTELProvider {\n getTraceInstance() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace;\n }\n getContextInstance() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext;\n }\n initializeGlobalInstances(otel) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (globalThis[OTEL_TRACE_KEY] === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n globalThis[OTEL_TRACE_KEY] = otel.trace;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (globalThis[OTEL_CONTEXT_KEY] === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n globalThis[OTEL_CONTEXT_KEY] = otel.context;\n }\n }\n setDefaultOTLPTracerComponents(components) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components;\n }\n getDefaultOTLPTracerComponents() {\n return (globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ??\n undefined);\n }\n}\nexport const OTELProviderSingleton = new OTELProvider();\n/**\n * Get the current OTEL trace instance.\n * Returns a mock implementation if OTEL is not available.\n */\nexport function getOTELTrace() {\n return OTELProviderSingleton.getTraceInstance();\n}\n/**\n * Get the current OTEL context instance.\n * Returns a mock implementation if OTEL is not available.\n */\nexport function getOTELContext() {\n return OTELProviderSingleton.getContextInstance();\n}\n/**\n * Initialize the global OTEL instances.\n * Should be called once when OTEL packages are available.\n */\nexport function setOTELInstances(otel) {\n OTELProviderSingleton.initializeGlobalInstances(otel);\n}\n/**\n * Set a getter function for the default OTLP tracer provider.\n * This allows lazy initialization of the tracer provider.\n */\nexport function setDefaultOTLPTracerComponents(components) {\n OTELProviderSingleton.setDefaultOTLPTracerComponents(components);\n}\n/**\n * Get the default OTLP tracer provider instance.\n * Returns undefined if not set.\n */\nexport function getDefaultOTLPTracerComponents() {\n return OTELProviderSingleton.getDefaultOTLPTracerComponents();\n}\n","import * as constants from \"./constants.js\";\nimport { getOTELTrace } from \"../../singletons/otel.js\";\nconst WELL_KNOWN_OPERATION_NAMES = {\n llm: \"chat\",\n tool: \"execute_tool\",\n retriever: \"embeddings\",\n embedding: \"embeddings\",\n prompt: \"chat\",\n};\nfunction getOperationName(runType) {\n return WELL_KNOWN_OPERATION_NAMES[runType] || runType;\n}\nexport class LangSmithToOTELTranslator {\n constructor() {\n Object.defineProperty(this, \"spans\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n }\n exportBatch(operations, otelContextMap) {\n for (const op of operations) {\n try {\n if (!op.run) {\n continue;\n }\n if (op.operation === \"post\") {\n const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id));\n if (span && !op.run.end_time) {\n this.spans.set(op.id, span);\n }\n }\n else {\n this.updateSpanForRun(op, op.run);\n }\n }\n catch (e) {\n console.error(`Error processing operation ${op.id}:`, e);\n }\n }\n }\n createSpanForRun(op, runInfo, otelContext) {\n const activeSpan = otelContext && getOTELTrace().getSpan(otelContext);\n if (!activeSpan) {\n return;\n }\n try {\n return this.finishSpanSetup(activeSpan, runInfo, op);\n }\n catch (e) {\n console.error(`Failed to create span for run ${op.id}:`, e);\n return undefined;\n }\n }\n finishSpanSetup(span, runInfo, op) {\n // Set all attributes\n this.setSpanAttributes(span, runInfo, op);\n // Set status based on error\n if (runInfo.error) {\n span.setStatus({ code: 2 }); // ERROR status\n span.recordException(new Error(runInfo.error));\n }\n else {\n span.setStatus({ code: 1 }); // OK status\n }\n // End the span if end_time is present\n if (runInfo.end_time) {\n span.end(new Date(runInfo.end_time));\n }\n return span;\n }\n updateSpanForRun(op, runInfo) {\n try {\n const span = this.spans.get(op.id);\n if (!span) {\n console.debug(`No span found for run ${op.id} during update`);\n return;\n }\n // Update attributes\n this.setSpanAttributes(span, runInfo, op);\n // Update status based on error\n if (runInfo.error) {\n span.setStatus({ code: 2 }); // ERROR status\n span.recordException(new Error(runInfo.error));\n }\n else {\n span.setStatus({ code: 1 }); // OK status\n }\n // End the span if end_time is present\n const endTime = runInfo.end_time;\n if (endTime) {\n span.end(new Date(endTime));\n this.spans.delete(op.id);\n }\n }\n catch (e) {\n console.error(`Failed to update span for run ${op.id}:`, e);\n }\n }\n extractModelName(runInfo) {\n // Try to get model name from metadata\n if (runInfo.extra?.metadata) {\n const metadata = runInfo.extra.metadata;\n // First check for ls_model_name in metadata\n if (metadata.ls_model_name) {\n return metadata.ls_model_name;\n }\n // Then check invocation_params for model info\n if (metadata.invocation_params) {\n const invocationParams = metadata.invocation_params;\n if (invocationParams.model) {\n return invocationParams.model;\n }\n else if (invocationParams.model_name) {\n return invocationParams.model_name;\n }\n }\n }\n return;\n }\n setSpanAttributes(span, runInfo, op) {\n if (\"run_type\" in runInfo && runInfo.run_type) {\n span.setAttribute(constants.LANGSMITH_RUN_TYPE, runInfo.run_type);\n // Set GenAI attributes according to OTEL semantic conventions\n const operationName = getOperationName(runInfo.run_type || \"chain\");\n span.setAttribute(constants.GEN_AI_OPERATION_NAME, operationName);\n }\n if (\"name\" in runInfo && runInfo.name) {\n span.setAttribute(constants.LANGSMITH_NAME, runInfo.name);\n }\n if (\"session_id\" in runInfo && runInfo.session_id) {\n span.setAttribute(constants.LANGSMITH_SESSION_ID, runInfo.session_id);\n }\n if (\"session_name\" in runInfo && runInfo.session_name) {\n span.setAttribute(constants.LANGSMITH_SESSION_NAME, runInfo.session_name);\n }\n // Set gen_ai.system\n this.setGenAiSystem(span, runInfo);\n // Set model name if available\n const modelName = this.extractModelName(runInfo);\n if (modelName) {\n span.setAttribute(constants.GEN_AI_REQUEST_MODEL, modelName);\n }\n // Set token usage information\n if (\"prompt_tokens\" in runInfo &&\n typeof runInfo.prompt_tokens === \"number\") {\n span.setAttribute(constants.GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens);\n }\n if (\"completion_tokens\" in runInfo &&\n typeof runInfo.completion_tokens === \"number\") {\n span.setAttribute(constants.GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens);\n }\n if (\"total_tokens\" in runInfo && typeof runInfo.total_tokens === \"number\") {\n span.setAttribute(constants.GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens);\n }\n // Set other parameters from invocation_params\n this.setInvocationParameters(span, runInfo);\n // Set metadata and tags if available\n const metadata = runInfo.extra?.metadata || {};\n for (const [key, value] of Object.entries(metadata)) {\n if (value !== null && value !== undefined) {\n span.setAttribute(`${constants.LANGSMITH_METADATA}.${key}`, String(value));\n }\n }\n const tags = runInfo.tags;\n if (tags && Array.isArray(tags)) {\n span.setAttribute(constants.LANGSMITH_TAGS, tags.join(\", \"));\n }\n else if (tags) {\n span.setAttribute(constants.LANGSMITH_TAGS, String(tags));\n }\n // Support additional serialized attributes, if present\n if (\"serialized\" in runInfo && typeof runInfo.serialized === \"object\") {\n const serialized = runInfo.serialized;\n if (serialized.name) {\n span.setAttribute(constants.GEN_AI_SERIALIZED_NAME, String(serialized.name));\n }\n if (serialized.signature) {\n span.setAttribute(constants.GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature));\n }\n if (serialized.doc) {\n span.setAttribute(constants.GEN_AI_SERIALIZED_DOC, String(serialized.doc));\n }\n }\n // Set inputs/outputs if available\n this.setIOAttributes(span, op);\n }\n setGenAiSystem(span, runInfo) {\n // Default to \"langchain\" if we can't determine the system\n let system = \"langchain\";\n // Extract model name to determine the system\n const modelName = this.extractModelName(runInfo);\n if (modelName) {\n const modelLower = modelName.toLowerCase();\n if (modelLower.includes(\"anthropic\") || modelLower.startsWith(\"claude\")) {\n system = \"anthropic\";\n }\n else if (modelLower.includes(\"bedrock\")) {\n system = \"aws.bedrock\";\n }\n else if (modelLower.includes(\"azure\") &&\n modelLower.includes(\"openai\")) {\n system = \"az.ai.openai\";\n }\n else if (modelLower.includes(\"azure\") &&\n modelLower.includes(\"inference\")) {\n system = \"az.ai.inference\";\n }\n else if (modelLower.includes(\"cohere\")) {\n system = \"cohere\";\n }\n else if (modelLower.includes(\"deepseek\")) {\n system = \"deepseek\";\n }\n else if (modelLower.includes(\"gemini\")) {\n system = \"gemini\";\n }\n else if (modelLower.includes(\"groq\")) {\n system = \"groq\";\n }\n else if (modelLower.includes(\"watson\") || modelLower.includes(\"ibm\")) {\n system = \"ibm.watsonx.ai\";\n }\n else if (modelLower.includes(\"mistral\")) {\n system = \"mistral_ai\";\n }\n else if (modelLower.includes(\"gpt\") || modelLower.includes(\"openai\")) {\n system = \"openai\";\n }\n else if (modelLower.includes(\"perplexity\") ||\n modelLower.includes(\"sonar\")) {\n system = \"perplexity\";\n }\n else if (modelLower.includes(\"vertex\")) {\n system = \"vertex_ai\";\n }\n else if (modelLower.includes(\"xai\") || modelLower.includes(\"grok\")) {\n system = \"xai\";\n }\n }\n span.setAttribute(constants.GEN_AI_SYSTEM, system);\n }\n setInvocationParameters(span, runInfo) {\n if (!runInfo.extra?.metadata?.invocation_params) {\n return;\n }\n const invocationParams = runInfo.extra.metadata.invocation_params;\n // Set relevant invocation parameters\n if (invocationParams.max_tokens !== undefined) {\n span.setAttribute(constants.GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens);\n }\n if (invocationParams.temperature !== undefined) {\n span.setAttribute(constants.GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature);\n }\n if (invocationParams.top_p !== undefined) {\n span.setAttribute(constants.GEN_AI_REQUEST_TOP_P, invocationParams.top_p);\n }\n if (invocationParams.frequency_penalty !== undefined) {\n span.setAttribute(constants.GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty);\n }\n if (invocationParams.presence_penalty !== undefined) {\n span.setAttribute(constants.GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty);\n }\n }\n setIOAttributes(span, op) {\n if (op.run.inputs) {\n try {\n const inputs = op.run.inputs;\n if (typeof inputs === \"object\" && inputs !== null) {\n if (inputs.model && Array.isArray(inputs.messages)) {\n span.setAttribute(constants.GEN_AI_REQUEST_MODEL, inputs.model);\n }\n // Set additional request attributes if available\n if (inputs.stream !== undefined) {\n span.setAttribute(constants.LANGSMITH_REQUEST_STREAMING, inputs.stream);\n }\n if (inputs.extra_headers) {\n span.setAttribute(constants.LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers));\n }\n if (inputs.extra_query) {\n span.setAttribute(constants.GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query));\n }\n if (inputs.extra_body) {\n span.setAttribute(constants.GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body));\n }\n }\n span.setAttribute(constants.GENAI_PROMPT, JSON.stringify(inputs));\n }\n catch (e) {\n console.debug(`Failed to process inputs for run ${op.id}`, e);\n }\n }\n if (op.run.outputs) {\n try {\n const outputs = op.run.outputs;\n // Extract token usage from outputs (for LLM runs)\n const tokenUsage = this.getUnifiedRunTokens(outputs);\n if (tokenUsage) {\n span.setAttribute(constants.GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]);\n span.setAttribute(constants.GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]);\n span.setAttribute(constants.GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]);\n }\n if (outputs && typeof outputs === \"object\") {\n if (outputs.model) {\n span.setAttribute(constants.GEN_AI_RESPONSE_MODEL, String(outputs.model));\n }\n // Extract additional response attributes\n if (outputs.id) {\n span.setAttribute(constants.GEN_AI_RESPONSE_ID, outputs.id);\n }\n if (outputs.choices && Array.isArray(outputs.choices)) {\n const finishReasons = outputs.choices\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map((choice) => choice.finish_reason)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .filter((reason) => reason)\n .map(String);\n if (finishReasons.length > 0) {\n span.setAttribute(constants.GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(\", \"));\n }\n }\n if (outputs.service_tier) {\n span.setAttribute(constants.GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier);\n }\n if (outputs.system_fingerprint) {\n span.setAttribute(constants.GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint);\n }\n if (outputs.usage_metadata &&\n typeof outputs.usage_metadata === \"object\") {\n const usageMetadata = outputs.usage_metadata;\n if (usageMetadata.input_token_details) {\n span.setAttribute(constants.GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details));\n }\n if (usageMetadata.output_token_details) {\n span.setAttribute(constants.GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details));\n }\n }\n }\n span.setAttribute(constants.GENAI_COMPLETION, JSON.stringify(outputs));\n }\n catch (e) {\n console.debug(`Failed to process outputs for run ${op.id}`, e);\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getUnifiedRunTokens(outputs) {\n if (!outputs) {\n return null;\n }\n // Search in non-generations lists\n let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata);\n if (tokenUsage) {\n return tokenUsage;\n }\n // Find if direct kwarg in outputs\n const keys = Object.keys(outputs);\n for (const key of keys) {\n const haystack = outputs[key];\n if (!haystack || typeof haystack !== \"object\") {\n continue;\n }\n tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata);\n if (tokenUsage) {\n return tokenUsage;\n }\n if (haystack.lc === 1 &&\n haystack.kwargs &&\n typeof haystack.kwargs === \"object\") {\n tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata);\n if (tokenUsage) {\n return tokenUsage;\n }\n }\n }\n // Find in generations\n const generations = outputs.generations || [];\n if (!Array.isArray(generations)) {\n return null;\n }\n const flatGenerations = Array.isArray(generations[0])\n ? generations.flat()\n : generations;\n for (const generation of flatGenerations) {\n if (typeof generation === \"object\" &&\n generation.message &&\n typeof generation.message === \"object\" &&\n generation.message.kwargs &&\n typeof generation.message.kwargs === \"object\") {\n tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata);\n if (tokenUsage) {\n return tokenUsage;\n }\n }\n }\n return null;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n extractUnifiedRunTokens(outputs) {\n if (!outputs || typeof outputs !== \"object\") {\n return null;\n }\n if (typeof outputs.input_tokens !== \"number\" ||\n typeof outputs.output_tokens !== \"number\") {\n return null;\n }\n return [outputs.input_tokens, outputs.output_tokens];\n }\n}\n","import pRetry from \"p-retry\";\nimport PQueueMod from \"p-queue\";\nconst STATUS_RETRYABLE = [\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n];\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of \"expensive\" external resource,\n * be it because it's rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nexport class AsyncCaller {\n constructor(params) {\n Object.defineProperty(this, \"maxConcurrency\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"maxRetries\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"queue\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"onFailedResponseHook\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n if (\"default\" in PQueueMod) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.queue = new PQueueMod.default({\n concurrency: this.maxConcurrency,\n });\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.queue = new PQueueMod({ concurrency: this.maxConcurrency });\n }\n this.onFailedResponseHook = params?.onFailedResponseHook;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n call(callable, ...args) {\n const onFailedResponseHook = this.onFailedResponseHook;\n return this.queue.add(() => pRetry(() => callable(...args).catch((error) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n }\n else {\n throw new Error(error);\n }\n }), {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async onFailedAttempt(error) {\n if (error.message.startsWith(\"Cancel\") ||\n error.message.startsWith(\"TimeoutError\") ||\n error.name === \"TimeoutError\" ||\n error.message.startsWith(\"AbortError\")) {\n throw error;\n }\n if (error?.code === \"ECONNABORTED\") {\n throw error;\n }\n const response = error?.response;\n if (onFailedResponseHook) {\n const handled = await onFailedResponseHook(response);\n if (handled) {\n return;\n }\n }\n const status = response?.status ?? error?.status;\n if (status) {\n if (!STATUS_RETRYABLE.includes(+status)) {\n throw error;\n }\n }\n },\n retries: this.maxRetries,\n randomize: true,\n }), { throwOnTimeout: true });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions(options, callable, ...args) {\n // Note this doesn't cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n return Promise.race([\n this.call(callable, ...args),\n new Promise((_, reject) => {\n options.signal?.addEventListener(\"abort\", () => {\n reject(new Error(\"AbortError\"));\n });\n }),\n ]);\n }\n return this.call(callable, ...args);\n }\n}\n","export function isLangChainMessage(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nmessage) {\n return typeof message?._getType === \"function\";\n}\nexport function convertLangChainMessageToExample(message) {\n const converted = {\n type: message._getType(),\n data: { content: message.content },\n };\n // Check for presence of keys in additional_kwargs\n if (message?.additional_kwargs &&\n Object.keys(message.additional_kwargs).length > 0) {\n converted.data.additional_kwargs = { ...message.additional_kwargs };\n }\n return converted;\n}\n","// Relaxed UUID validation regex (allows any valid UUID format including nil UUIDs)\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport function assertUuid(str, which) {\n // Use relaxed regex validation instead of strict uuid.validate()\n // This allows edge cases like nil UUIDs or test UUIDs that might not pass strict validation\n if (!UUID_REGEX.test(str)) {\n const msg = which !== undefined\n ? `Invalid UUID for ${which}: ${str}`\n : `Invalid UUID: ${str}`;\n throw new Error(msg);\n }\n return str;\n}\n","const warnedMessages = {};\nexport function warnOnce(message) {\n if (!warnedMessages[message]) {\n console.warn(message);\n warnedMessages[message] = true;\n }\n}\n","import { parse as parseVersion } from \"semver\";\nexport function isVersionGreaterOrEqual(current_version, target_version) {\n const current = parseVersion(current_version);\n const target = parseVersion(target_version);\n if (!current || !target) {\n throw new Error(\"Invalid version format.\");\n }\n return current.compare(target) >= 0;\n}\nexport function parsePromptIdentifier(identifier) {\n if (!identifier ||\n identifier.split(\"/\").length > 2 ||\n identifier.startsWith(\"/\") ||\n identifier.endsWith(\"/\") ||\n identifier.split(\":\").length > 2) {\n throw new Error(`Invalid identifier format: ${identifier}`);\n }\n const [ownerNamePart, commitPart] = identifier.split(\":\");\n const commit = commitPart || \"latest\";\n if (ownerNamePart.includes(\"/\")) {\n const [owner, name] = ownerNamePart.split(\"/\", 2);\n if (!owner || !name) {\n throw new Error(`Invalid identifier format: ${identifier}`);\n }\n return [owner, name, commit];\n }\n else {\n if (!ownerNamePart) {\n throw new Error(`Invalid identifier format: ${identifier}`);\n }\n return [\"-\", ownerNamePart, commit];\n }\n}\n","function getErrorStackTrace(e) {\n if (typeof e !== \"object\" || e == null)\n return undefined;\n if (!(\"stack\" in e) || typeof e.stack !== \"string\")\n return undefined;\n let stack = e.stack;\n const prevLine = `${e}`;\n if (stack.startsWith(prevLine)) {\n stack = stack.slice(prevLine.length);\n }\n if (stack.startsWith(\"\\n\")) {\n stack = stack.slice(1);\n }\n return stack;\n}\nexport function printErrorStackTrace(e) {\n const stack = getErrorStackTrace(e);\n if (stack == null)\n return;\n console.error(stack);\n}\n/**\n * LangSmithConflictError\n *\n * Represents an error that occurs when there's a conflict during an operation,\n * typically corresponding to HTTP 409 status code responses.\n *\n * This error is thrown when an attempt to create or modify a resource conflicts\n * with the current state of the resource on the server. Common scenarios include:\n * - Attempting to create a resource that already exists\n * - Trying to update a resource that has been modified by another process\n * - Violating a uniqueness constraint in the data\n *\n * @extends Error\n *\n * @example\n * try {\n * await createProject(\"existingProject\");\n * } catch (error) {\n * if (error instanceof ConflictError) {\n * console.log(\"A conflict occurred:\", error.message);\n * // Handle the conflict, e.g., by suggesting a different project name\n * } else {\n * // Handle other types of errors\n * }\n * }\n *\n * @property {string} name - Always set to 'ConflictError' for easy identification\n * @property {string} message - Detailed error message including server response\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409\n */\nexport class LangSmithConflictError extends Error {\n constructor(message) {\n super(message);\n Object.defineProperty(this, \"status\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = \"LangSmithConflictError\";\n this.status = 409;\n }\n}\n/**\n * Throws an appropriate error based on the response status and body.\n *\n * @param response - The fetch Response object\n * @param context - Additional context to include in the error message (e.g., operation being performed)\n * @throws {LangSmithConflictError} When the response status is 409\n * @throws {Error} For all other non-ok responses\n */\nexport async function raiseForStatus(response, context, consumeOnSuccess) {\n let errorBody;\n if (response.ok) {\n // consume the response body to release the connection\n // https://undici.nodejs.org/#/?id=garbage-collection\n if (consumeOnSuccess) {\n errorBody = await response.text();\n }\n return;\n }\n if (response.status === 403) {\n try {\n const errorData = await response.json();\n const errorCode = errorData?.error;\n if (errorCode === \"org_scoped_key_requires_workspace\") {\n errorBody =\n \"This API key is org-scoped and requires workspace specification. \" +\n \"Please provide 'workspaceId' parameter, \" +\n \"or set LANGSMITH_WORKSPACE_ID environment variable.\";\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n catch (e) {\n const errorWithStatus = new Error(`${response.status} ${response.statusText}`);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n errorWithStatus.status = response?.status;\n throw errorWithStatus;\n }\n }\n if (errorBody === undefined) {\n try {\n errorBody = await response.text();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n catch (e) {\n errorBody = \"\";\n }\n }\n const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;\n if (response.status === 409) {\n throw new LangSmithConflictError(fullMessage);\n }\n const err = new Error(fullMessage);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n err.status = response.status;\n throw err;\n}\nconst ERR_CONFLICTING_ENDPOINTS = \"ERR_CONFLICTING_ENDPOINTS\";\nexport class ConflictingEndpointsError extends Error {\n constructor() {\n super(\"You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT \" +\n \"and LANGSMITH_RUNS_ENDPOINTS.\");\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ERR_CONFLICTING_ENDPOINTS\n });\n this.name = \"ConflictingEndpointsError\"; // helpful in logs\n }\n}\nexport function isConflictingEndpointsError(err) {\n return (typeof err === \"object\" &&\n err !== null &&\n err.code === ERR_CONFLICTING_ENDPOINTS);\n}\n","/* eslint-disable */\n// @ts-nocheck\nimport { getLangSmithEnvironmentVariable } from \"../../utils/env.js\";\nvar LIMIT_REPLACE_NODE = \"[...]\";\nvar CIRCULAR_REPLACE_NODE = { result: \"[Circular]\" };\nvar arr = [];\nvar replacerStack = [];\nconst encoder = new TextEncoder();\nfunction defaultOptions() {\n return {\n depthLimit: Number.MAX_SAFE_INTEGER,\n edgesLimit: Number.MAX_SAFE_INTEGER,\n };\n}\nfunction encodeString(str) {\n return encoder.encode(str);\n}\n// Shared function to handle well-known types\nfunction serializeWellKnownTypes(val) {\n if (val && typeof val === \"object\" && val !== null) {\n if (val instanceof Map) {\n return Object.fromEntries(val);\n }\n else if (val instanceof Set) {\n return Array.from(val);\n }\n else if (val instanceof Date) {\n return val.toISOString();\n }\n else if (val instanceof RegExp) {\n return val.toString();\n }\n else if (val instanceof Error) {\n return {\n name: val.name,\n message: val.message,\n };\n }\n }\n else if (typeof val === \"bigint\") {\n return val.toString();\n }\n return val;\n}\n// Default replacer function to handle well-known types\nfunction createDefaultReplacer(userReplacer) {\n return function (key, val) {\n // Apply user replacer first if provided\n if (userReplacer) {\n const userResult = userReplacer.call(this, key, val);\n // If user replacer returned undefined, fall back to our serialization\n if (userResult !== undefined) {\n return userResult;\n }\n }\n // Fall back to our well-known type handling\n return serializeWellKnownTypes(val);\n };\n}\n// Regular stringify\nexport function serialize(obj, errorContext, replacer, spacer, options) {\n try {\n const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer);\n return encodeString(str);\n }\n catch (e) {\n // Fall back to more complex stringify if circular reference\n if (!e.message?.includes(\"Converting circular structure to JSON\")) {\n console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\\nContext: ${errorContext}` : \"\"}`);\n return encodeString(\"[Unserializable]\");\n }\n getLangSmithEnvironmentVariable(\"SUPPRESS_CIRCULAR_JSON_WARNINGS\") !==\n \"true\" &&\n console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\\nContext: ${errorContext}` : \"\"}`);\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n decirc(obj, \"\", 0, [], undefined, 0, options);\n let res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer);\n }\n else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);\n }\n }\n catch (_) {\n return encodeString(\"[unable to serialize, circular reference is too complex to analyze]\");\n }\n finally {\n while (arr.length !== 0) {\n const part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n }\n else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return encodeString(res);\n }\n}\nfunction setReplace(replace, val, k, parent) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: replace });\n arr.push([parent, k, val, propertyDescriptor]);\n }\n else {\n replacerStack.push([val, k, replace]);\n }\n }\n else {\n parent[k] = replace;\n arr.push([parent, k, val]);\n }\n}\nfunction decirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n if (typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n if (typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, i, stack, val, depth, options);\n }\n }\n else {\n // Handle well-known types before Object.keys iteration\n val = serializeWellKnownTypes(val);\n var keys = Object.keys(val);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n decirc(val[key], key, i, stack, val, depth, options);\n }\n }\n stack.pop();\n }\n}\n// Stable-stringify\nfunction compareFunction(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\nfunction deterministicStringify(obj, replacer, spacer, options) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n var tmp = deterministicDecirc(obj, \"\", 0, [], undefined, 0, options) || obj;\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer);\n }\n else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);\n }\n }\n catch (_) {\n return JSON.stringify(\"[unable to serialize, circular reference is too complex to analyze]\");\n }\n finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n }\n else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\nfunction deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n try {\n if (typeof val.toJSON === \"function\") {\n return;\n }\n }\n catch (_) {\n return;\n }\n if (typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n if (typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, i, stack, val, depth, options);\n }\n }\n else {\n // Handle well-known types before Object.keys iteration\n val = serializeWellKnownTypes(val);\n // Create a temporary object in the required way\n var tmp = {};\n var keys = Object.keys(val).sort(compareFunction);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n deterministicDecirc(val[key], key, i, stack, val, depth, options);\n tmp[key] = val[key];\n }\n if (typeof parent !== \"undefined\") {\n arr.push([parent, k, val]);\n parent[k] = tmp;\n }\n else {\n return tmp;\n }\n }\n stack.pop();\n }\n}\n// wraps replacer function to handle values we couldn't replace\n// and mark them as replaced value\nfunction replaceGetterValues(replacer) {\n replacer =\n typeof replacer !== \"undefined\"\n ? replacer\n : function (k, v) {\n return v;\n };\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i];\n if (part[1] === key && part[0] === val) {\n val = part[2];\n replacerStack.splice(i, 1);\n break;\n }\n }\n }\n return replacer.call(this, key, val);\n };\n}\n","import * as uuid from \"uuid\";\nimport { LangSmithToOTELTranslator, } from \"./experimental/otel/translator.js\";\nimport { getDefaultOTLPTracerComponents, getOTELTrace, getOTELContext, } from \"./singletons/otel.js\";\nimport { AsyncCaller } from \"./utils/async_caller.js\";\nimport { convertLangChainMessageToExample, isLangChainMessage, } from \"./utils/messages.js\";\nimport { getEnvironmentVariable, getLangSmithEnvVarsMetadata, getLangSmithEnvironmentVariable, getRuntimeEnvironment, getOtelEnabled, getEnv, } from \"./utils/env.js\";\nimport { __version__ } from \"./index.js\";\nimport { assertUuid } from \"./utils/_uuid.js\";\nimport { warnOnce } from \"./utils/warn.js\";\nimport { parsePromptIdentifier } from \"./utils/prompts.js\";\nimport { raiseForStatus } from \"./utils/error.js\";\nimport { _globalFetchImplementationIsNodeFetch, _getFetchImplementation, } from \"./singletons/fetch.js\";\nimport { serialize as serializePayloadForTracing } from \"./utils/fast-safe-stringify/index.js\";\nexport function mergeRuntimeEnvIntoRun(run, cachedEnvVars) {\n const runtimeEnv = getRuntimeEnvironment();\n const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata();\n const extra = run.extra ?? {};\n const metadata = extra.metadata;\n run.extra = {\n ...extra,\n runtime: {\n ...runtimeEnv,\n ...extra?.runtime,\n },\n metadata: {\n ...envVars,\n ...(envVars.revision_id || (\"revision_id\" in run && run.revision_id)\n ? {\n revision_id: (\"revision_id\" in run ? run.revision_id : undefined) ??\n envVars.revision_id,\n }\n : {}),\n ...metadata,\n },\n };\n return run;\n}\nconst getTracingSamplingRate = (configRate) => {\n const samplingRateStr = configRate?.toString() ??\n getLangSmithEnvironmentVariable(\"TRACING_SAMPLING_RATE\");\n if (samplingRateStr === undefined) {\n return undefined;\n }\n const samplingRate = parseFloat(samplingRateStr);\n if (samplingRate < 0 || samplingRate > 1) {\n throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`);\n }\n return samplingRate;\n};\n// utility functions\nconst isLocalhost = (url) => {\n const strippedUrl = url.replace(\"http://\", \"\").replace(\"https://\", \"\");\n const hostname = strippedUrl.split(\"/\")[0].split(\":\")[0];\n return (hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\");\n};\nasync function toArray(iterable) {\n const result = [];\n for await (const item of iterable) {\n result.push(item);\n }\n return result;\n}\nfunction trimQuotes(str) {\n if (str === undefined) {\n return undefined;\n }\n return str\n .trim()\n .replace(/^\"(.*)\"$/, \"$1\")\n .replace(/^'(.*)'$/, \"$1\");\n}\nconst handle429 = async (response) => {\n if (response?.status === 429) {\n const retryAfter = parseInt(response.headers.get(\"retry-after\") ?? \"10\", 10) * 1000;\n if (retryAfter > 0) {\n await new Promise((resolve) => setTimeout(resolve, retryAfter));\n // Return directly after calling this check\n return true;\n }\n }\n // Fall back to existing status checks\n return false;\n};\nfunction _formatFeedbackScore(score) {\n if (typeof score === \"number\") {\n // Truncate at 4 decimal places\n return Number(score.toFixed(4));\n }\n return score;\n}\nexport class AutoBatchQueue {\n constructor() {\n Object.defineProperty(this, \"items\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, \"sizeBytes\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n }\n peek() {\n return this.items[0];\n }\n push(item) {\n let itemPromiseResolve;\n const itemPromise = new Promise((resolve) => {\n // Setting itemPromiseResolve is synchronous with promise creation:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise\n itemPromiseResolve = resolve;\n });\n const size = serializePayloadForTracing(item.item, `Serializing run with id: ${item.item.id}`).length;\n this.items.push({\n action: item.action,\n payload: item.item,\n otelContext: item.otelContext,\n apiKey: item.apiKey,\n apiUrl: item.apiUrl,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n itemPromiseResolve: itemPromiseResolve,\n itemPromise,\n size,\n });\n this.sizeBytes += size;\n return itemPromise;\n }\n pop({ upToSizeBytes, upToSize, }) {\n if (upToSizeBytes < 1) {\n throw new Error(\"Number of bytes to pop off may not be less than 1.\");\n }\n const popped = [];\n let poppedSizeBytes = 0;\n // Pop items until we reach or exceed the size limit\n while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes &&\n this.items.length > 0 &&\n popped.length < upToSize) {\n const item = this.items.shift();\n if (item) {\n popped.push(item);\n poppedSizeBytes += item.size;\n this.sizeBytes -= item.size;\n }\n }\n // If there is an item on the queue we were unable to pop,\n // just return it as a single batch.\n if (popped.length === 0 && this.items.length > 0) {\n const item = this.items.shift();\n popped.push(item);\n poppedSizeBytes += item.size;\n this.sizeBytes -= item.size;\n }\n return [\n popped.map((it) => ({\n action: it.action,\n item: it.payload,\n otelContext: it.otelContext,\n apiKey: it.apiKey,\n apiUrl: it.apiUrl,\n })),\n () => popped.forEach((it) => it.itemPromiseResolve()),\n ];\n }\n}\nexport const DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 24 * 1024 * 1024;\nconst SERVER_INFO_REQUEST_TIMEOUT_MS = 10000;\n/** Maximum number of operations to batch in a single request. */\nconst DEFAULT_BATCH_SIZE_LIMIT = 100;\nconst DEFAULT_API_URL = \"https://api.smith.langchain.com\";\nexport class Client {\n get _fetch() {\n return this.fetchImplementation || _getFetchImplementation(this.debug);\n }\n constructor(config = {}) {\n Object.defineProperty(this, \"apiKey\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"apiUrl\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"webUrl\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"workspaceId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"caller\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"batchIngestCaller\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"timeout_ms\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_tenantId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: null\n });\n Object.defineProperty(this, \"hideInputs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"hideOutputs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"tracingSampleRate\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"filteredPostUuids\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Set()\n });\n Object.defineProperty(this, \"autoBatchTracing\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, \"autoBatchQueue\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new AutoBatchQueue()\n });\n Object.defineProperty(this, \"autoBatchTimeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"autoBatchAggregationDelayMs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 250\n });\n Object.defineProperty(this, \"batchSizeBytesLimit\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"batchSizeLimit\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"fetchOptions\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"settings\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"blockOnRootRunFinalization\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: getEnvironmentVariable(\"LANGSMITH_TRACING_BACKGROUND\") === \"false\"\n });\n Object.defineProperty(this, \"traceBatchConcurrency\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5\n });\n Object.defineProperty(this, \"_serverInfo\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Object.defineProperty(this, \"_getServerInfoPromise\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"manualFlushMode\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"langSmithToOTELTranslator\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"fetchImplementation\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"cachedLSEnvVarsForMetadata\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"multipartStreamingDisabled\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"debug\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: getEnvironmentVariable(\"LANGSMITH_DEBUG\") === \"true\"\n });\n const defaultConfig = Client.getDefaultClientConfig();\n this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate);\n this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? \"\";\n if (this.apiUrl.endsWith(\"/\")) {\n this.apiUrl = this.apiUrl.slice(0, -1);\n }\n this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey);\n this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl);\n if (this.webUrl?.endsWith(\"/\")) {\n this.webUrl = this.webUrl.slice(0, -1);\n }\n this.workspaceId = trimQuotes(config.workspaceId ?? getLangSmithEnvironmentVariable(\"WORKSPACE_ID\"));\n this.timeout_ms = config.timeout_ms ?? 90_000;\n this.caller = new AsyncCaller({\n ...(config.callerOptions ?? {}),\n maxRetries: 4,\n debug: config.debug ?? this.debug,\n });\n this.traceBatchConcurrency =\n config.traceBatchConcurrency ?? this.traceBatchConcurrency;\n if (this.traceBatchConcurrency < 1) {\n throw new Error(\"Trace batch concurrency must be positive.\");\n }\n this.debug = config.debug ?? this.debug;\n this.fetchImplementation = config.fetchImplementation;\n this.batchIngestCaller = new AsyncCaller({\n maxRetries: 2,\n maxConcurrency: this.traceBatchConcurrency,\n ...(config.callerOptions ?? {}),\n onFailedResponseHook: handle429,\n debug: config.debug ?? this.debug,\n });\n this.hideInputs =\n config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;\n this.hideOutputs =\n config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;\n this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;\n this.blockOnRootRunFinalization =\n config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;\n this.batchSizeBytesLimit = config.batchSizeBytesLimit;\n this.batchSizeLimit = config.batchSizeLimit;\n this.fetchOptions = config.fetchOptions || {};\n this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode;\n if (getOtelEnabled()) {\n this.langSmithToOTELTranslator = new LangSmithToOTELTranslator();\n }\n // Cache metadata env vars once during construction to avoid repeatedly scanning process.env\n this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata();\n }\n static getDefaultClientConfig() {\n const apiKey = getLangSmithEnvironmentVariable(\"API_KEY\");\n const apiUrl = getLangSmithEnvironmentVariable(\"ENDPOINT\") ?? DEFAULT_API_URL;\n const hideInputs = getLangSmithEnvironmentVariable(\"HIDE_INPUTS\") === \"true\";\n const hideOutputs = getLangSmithEnvironmentVariable(\"HIDE_OUTPUTS\") === \"true\";\n return {\n apiUrl: apiUrl,\n apiKey: apiKey,\n webUrl: undefined,\n hideInputs: hideInputs,\n hideOutputs: hideOutputs,\n };\n }\n getHostUrl() {\n if (this.webUrl) {\n return this.webUrl;\n }\n else if (isLocalhost(this.apiUrl)) {\n this.webUrl = \"http://localhost:3000\";\n return this.webUrl;\n }\n else if (this.apiUrl.endsWith(\"/api/v1\")) {\n this.webUrl = this.apiUrl.replace(\"/api/v1\", \"\");\n return this.webUrl;\n }\n else if (this.apiUrl.includes(\"/api\") &&\n !this.apiUrl.split(\".\", 1)[0].endsWith(\"api\")) {\n this.webUrl = this.apiUrl.replace(\"/api\", \"\");\n return this.webUrl;\n }\n else if (this.apiUrl.split(\".\", 1)[0].includes(\"dev\")) {\n this.webUrl = \"https://dev.smith.langchain.com\";\n return this.webUrl;\n }\n else if (this.apiUrl.split(\".\", 1)[0].includes(\"eu\")) {\n this.webUrl = \"https://eu.smith.langchain.com\";\n return this.webUrl;\n }\n else if (this.apiUrl.split(\".\", 1)[0].includes(\"beta\")) {\n this.webUrl = \"https://beta.smith.langchain.com\";\n return this.webUrl;\n }\n else {\n this.webUrl = \"https://smith.langchain.com\";\n return this.webUrl;\n }\n }\n get headers() {\n const headers = {\n \"User-Agent\": `langsmith-js/${__version__}`,\n };\n if (this.apiKey) {\n headers[\"x-api-key\"] = `${this.apiKey}`;\n }\n if (this.workspaceId) {\n headers[\"x-tenant-id\"] = this.workspaceId;\n }\n return headers;\n }\n _getPlatformEndpointPath(path) {\n // Check if apiUrl already ends with /v1 or /v1/ to avoid double /v1/v1/ paths\n const needsV1Prefix = this.apiUrl.slice(-3) !== \"/v1\" && this.apiUrl.slice(-4) !== \"/v1/\";\n return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`;\n }\n async processInputs(inputs) {\n if (this.hideInputs === false) {\n return inputs;\n }\n if (this.hideInputs === true) {\n return {};\n }\n if (typeof this.hideInputs === \"function\") {\n return this.hideInputs(inputs);\n }\n return inputs;\n }\n async processOutputs(outputs) {\n if (this.hideOutputs === false) {\n return outputs;\n }\n if (this.hideOutputs === true) {\n return {};\n }\n if (typeof this.hideOutputs === \"function\") {\n return this.hideOutputs(outputs);\n }\n return outputs;\n }\n async prepareRunCreateOrUpdateInputs(run) {\n const runParams = { ...run };\n if (runParams.inputs !== undefined) {\n runParams.inputs = await this.processInputs(runParams.inputs);\n }\n if (runParams.outputs !== undefined) {\n runParams.outputs = await this.processOutputs(runParams.outputs);\n }\n return runParams;\n }\n async _getResponse(path, queryParams) {\n const paramsString = queryParams?.toString() ?? \"\";\n const url = `${this.apiUrl}${path}?${paramsString}`;\n const response = await this.caller.call(async () => {\n const res = await this._fetch(url, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, `fetch ${path}`);\n return res;\n });\n return response;\n }\n async _get(path, queryParams) {\n const response = await this._getResponse(path, queryParams);\n return response.json();\n }\n async *_getPaginated(path, queryParams = new URLSearchParams(), transform) {\n let offset = Number(queryParams.get(\"offset\")) || 0;\n const limit = Number(queryParams.get(\"limit\")) || 100;\n while (true) {\n queryParams.set(\"offset\", String(offset));\n queryParams.set(\"limit\", String(limit));\n const url = `${this.apiUrl}${path}?${queryParams}`;\n const response = await this.caller.call(async () => {\n const res = await this._fetch(url, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, `fetch ${path}`);\n return res;\n });\n const items = transform\n ? transform(await response.json())\n : await response.json();\n if (items.length === 0) {\n break;\n }\n yield items;\n if (items.length < limit) {\n break;\n }\n offset += items.length;\n }\n }\n async *_getCursorPaginatedList(path, body = null, requestMethod = \"POST\", dataKey = \"runs\") {\n const bodyParams = body ? { ...body } : {};\n while (true) {\n const body = JSON.stringify(bodyParams);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}${path}`, {\n method: requestMethod,\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, `fetch ${path}`);\n return res;\n });\n const responseBody = await response.json();\n if (!responseBody) {\n break;\n }\n if (!responseBody[dataKey]) {\n break;\n }\n yield responseBody[dataKey];\n const cursors = responseBody.cursors;\n if (!cursors) {\n break;\n }\n if (!cursors.next) {\n break;\n }\n bodyParams.cursor = cursors.next;\n }\n }\n // Allows mocking for tests\n _shouldSample() {\n if (this.tracingSampleRate === undefined) {\n return true;\n }\n return Math.random() < this.tracingSampleRate;\n }\n _filterForSampling(runs, patch = false) {\n if (this.tracingSampleRate === undefined) {\n return runs;\n }\n if (patch) {\n const sampled = [];\n for (const run of runs) {\n if (!this.filteredPostUuids.has(run.trace_id)) {\n sampled.push(run);\n }\n else if (run.id === run.trace_id) {\n this.filteredPostUuids.delete(run.trace_id);\n }\n }\n return sampled;\n }\n else {\n // For new runs, sample at trace level to maintain consistency\n const sampled = [];\n for (const run of runs) {\n const traceId = run.trace_id ?? run.id;\n // If we've already made a decision about this trace, follow it\n if (this.filteredPostUuids.has(traceId)) {\n continue;\n }\n // For new traces, apply sampling\n if (run.id === traceId) {\n if (this._shouldSample()) {\n sampled.push(run);\n }\n else {\n this.filteredPostUuids.add(traceId);\n }\n }\n else {\n // Child runs follow their trace's sampling decision\n sampled.push(run);\n }\n }\n return sampled;\n }\n }\n async _getBatchSizeLimitBytes() {\n const serverInfo = await this._ensureServerInfo();\n return (this.batchSizeBytesLimit ??\n serverInfo.batch_ingest_config?.size_limit_bytes ??\n DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES);\n }\n /**\n * Get the maximum number of operations to batch in a single request.\n */\n async _getBatchSizeLimit() {\n const serverInfo = await this._ensureServerInfo();\n return (this.batchSizeLimit ??\n serverInfo.batch_ingest_config?.size_limit ??\n DEFAULT_BATCH_SIZE_LIMIT);\n }\n async _getDatasetExamplesMultiPartSupport() {\n const serverInfo = await this._ensureServerInfo();\n return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false);\n }\n drainAutoBatchQueue({ batchSizeLimitBytes, batchSizeLimit, }) {\n const promises = [];\n while (this.autoBatchQueue.items.length > 0) {\n const [batch, done] = this.autoBatchQueue.pop({\n upToSizeBytes: batchSizeLimitBytes,\n upToSize: batchSizeLimit,\n });\n if (!batch.length) {\n done();\n break;\n }\n const batchesByDestination = batch.reduce((acc, item) => {\n const apiUrl = item.apiUrl ?? this.apiUrl;\n const apiKey = item.apiKey ?? this.apiKey;\n const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl;\n const batchKey = isDefault ? \"default\" : `${apiUrl}|${apiKey}`;\n if (!acc[batchKey]) {\n acc[batchKey] = [];\n }\n acc[batchKey].push(item);\n return acc;\n }, {});\n const batchPromises = [];\n for (const [batchKey, batch] of Object.entries(batchesByDestination)) {\n const batchPromise = this._processBatch(batch, {\n apiUrl: batchKey === \"default\" ? undefined : batchKey.split(\"|\")[0],\n apiKey: batchKey === \"default\" ? undefined : batchKey.split(\"|\")[1],\n });\n batchPromises.push(batchPromise);\n }\n // Wait for all batches to complete, then call the overall done callback\n const allBatchesPromise = Promise.all(batchPromises).finally(done);\n promises.push(allBatchesPromise);\n }\n return Promise.all(promises);\n }\n async _processBatch(batch, options) {\n if (!batch.length) {\n return;\n }\n try {\n if (this.langSmithToOTELTranslator !== undefined) {\n this._sendBatchToOTELTranslator(batch);\n }\n else {\n const ingestParams = {\n runCreates: batch\n .filter((item) => item.action === \"create\")\n .map((item) => item.item),\n runUpdates: batch\n .filter((item) => item.action === \"update\")\n .map((item) => item.item),\n };\n const serverInfo = await this._ensureServerInfo();\n if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) {\n const useGzip = serverInfo?.instance_flags?.gzip_body_enabled;\n await this.multipartIngestRuns(ingestParams, { ...options, useGzip });\n }\n else {\n await this.batchIngestRuns(ingestParams, options);\n }\n }\n }\n catch (e) {\n console.error(\"Error exporting batch:\", e);\n }\n }\n _sendBatchToOTELTranslator(batch) {\n if (this.langSmithToOTELTranslator !== undefined) {\n const otelContextMap = new Map();\n const operations = [];\n for (const item of batch) {\n if (item.item.id && item.otelContext) {\n otelContextMap.set(item.item.id, item.otelContext);\n if (item.action === \"create\") {\n operations.push({\n operation: \"post\",\n id: item.item.id,\n trace_id: item.item.trace_id ?? item.item.id,\n run: item.item,\n });\n }\n else {\n operations.push({\n operation: \"patch\",\n id: item.item.id,\n trace_id: item.item.trace_id ?? item.item.id,\n run: item.item,\n });\n }\n }\n }\n this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap);\n }\n }\n async processRunOperation(item) {\n clearTimeout(this.autoBatchTimeout);\n this.autoBatchTimeout = undefined;\n item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata);\n const itemPromise = this.autoBatchQueue.push(item);\n if (this.manualFlushMode) {\n // Rely on manual flushing in serverless environments\n return itemPromise;\n }\n const sizeLimitBytes = await this._getBatchSizeLimitBytes();\n const sizeLimit = await this._getBatchSizeLimit();\n if (this.autoBatchQueue.sizeBytes > sizeLimitBytes ||\n this.autoBatchQueue.items.length > sizeLimit) {\n void this.drainAutoBatchQueue({\n batchSizeLimitBytes: sizeLimitBytes,\n batchSizeLimit: sizeLimit,\n });\n }\n if (this.autoBatchQueue.items.length > 0) {\n this.autoBatchTimeout = setTimeout(() => {\n this.autoBatchTimeout = undefined;\n void this.drainAutoBatchQueue({\n batchSizeLimitBytes: sizeLimitBytes,\n batchSizeLimit: sizeLimit,\n });\n }, this.autoBatchAggregationDelayMs);\n }\n return itemPromise;\n }\n async _getServerInfo() {\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/info`, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"get server info\");\n return res;\n });\n const json = await response.json();\n if (this.debug) {\n console.log(\"\\n=== LangSmith Server Configuration ===\\n\" +\n JSON.stringify(json, null, 2) +\n \"\\n\");\n }\n return json;\n }\n async _ensureServerInfo() {\n if (this._getServerInfoPromise === undefined) {\n this._getServerInfoPromise = (async () => {\n if (this._serverInfo === undefined) {\n try {\n this._serverInfo = await this._getServerInfo();\n }\n catch (e) {\n console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status ?? \"Unspecified status code\"} ${e.message}`);\n }\n }\n return this._serverInfo ?? {};\n })();\n }\n return this._getServerInfoPromise.then((serverInfo) => {\n if (this._serverInfo === undefined) {\n this._getServerInfoPromise = undefined;\n }\n return serverInfo;\n });\n }\n async _getSettings() {\n if (!this.settings) {\n this.settings = this._get(\"/settings\");\n }\n return await this.settings;\n }\n /**\n * Flushes current queued traces.\n */\n async flush() {\n const sizeLimitBytes = await this._getBatchSizeLimitBytes();\n const sizeLimit = await this._getBatchSizeLimit();\n await this.drainAutoBatchQueue({\n batchSizeLimitBytes: sizeLimitBytes,\n batchSizeLimit: sizeLimit,\n });\n }\n _cloneCurrentOTELContext() {\n const otel_trace = getOTELTrace();\n const otel_context = getOTELContext();\n if (this.langSmithToOTELTranslator !== undefined) {\n const currentSpan = otel_trace.getActiveSpan();\n if (currentSpan) {\n return otel_trace.setSpan(otel_context.active(), currentSpan);\n }\n }\n return undefined;\n }\n async createRun(run, options) {\n if (!this._filterForSampling([run]).length) {\n return;\n }\n const headers = {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n };\n const session_name = run.project_name;\n delete run.project_name;\n const runCreate = await this.prepareRunCreateOrUpdateInputs({\n session_name,\n ...run,\n start_time: run.start_time ?? Date.now(),\n });\n if (this.autoBatchTracing &&\n runCreate.trace_id !== undefined &&\n runCreate.dotted_order !== undefined) {\n const otelContext = this._cloneCurrentOTELContext();\n void this.processRunOperation({\n action: \"create\",\n item: runCreate,\n otelContext,\n apiKey: options?.apiKey,\n apiUrl: options?.apiUrl,\n }).catch(console.error);\n return;\n }\n const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata);\n if (options?.apiKey !== undefined) {\n headers[\"x-api-key\"] = options.apiKey;\n }\n if (options?.workspaceId !== undefined) {\n headers[\"x-tenant-id\"] = options.workspaceId;\n }\n const body = serializePayloadForTracing(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`);\n await this.caller.call(async () => {\n const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs`, {\n method: \"POST\",\n headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"create run\", true);\n return res;\n });\n }\n /**\n * Batch ingest/upsert multiple runs in the Langsmith system.\n * @param runs\n */\n async batchIngestRuns({ runCreates, runUpdates, }, options) {\n if (runCreates === undefined && runUpdates === undefined) {\n return;\n }\n let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []);\n let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []);\n if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {\n const createById = preparedCreateParams.reduce((params, run) => {\n if (!run.id) {\n return params;\n }\n params[run.id] = run;\n return params;\n }, {});\n const standaloneUpdates = [];\n for (const updateParam of preparedUpdateParams) {\n if (updateParam.id !== undefined && createById[updateParam.id]) {\n createById[updateParam.id] = {\n ...createById[updateParam.id],\n ...updateParam,\n };\n }\n else {\n standaloneUpdates.push(updateParam);\n }\n }\n preparedCreateParams = Object.values(createById);\n preparedUpdateParams = standaloneUpdates;\n }\n const rawBatch = {\n post: preparedCreateParams,\n patch: preparedUpdateParams,\n };\n if (!rawBatch.post.length && !rawBatch.patch.length) {\n return;\n }\n const batchChunks = {\n post: [],\n patch: [],\n };\n for (const k of [\"post\", \"patch\"]) {\n const key = k;\n const batchItems = rawBatch[key].reverse();\n let batchItem = batchItems.pop();\n while (batchItem !== undefined) {\n // Type is wrong but this is a deprecated code path anyway\n batchChunks[key].push(batchItem);\n batchItem = batchItems.pop();\n }\n }\n if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) {\n const runIds = batchChunks.post\n .map((item) => item.id)\n .concat(batchChunks.patch.map((item) => item.id))\n .join(\",\");\n await this._postBatchIngestRuns(serializePayloadForTracing(batchChunks, `Ingesting runs with ids: ${runIds}`), options);\n }\n }\n async _postBatchIngestRuns(body, options) {\n const headers = {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n };\n if (options?.apiKey !== undefined) {\n headers[\"x-api-key\"] = options.apiKey;\n }\n await this.batchIngestCaller.call(async () => {\n const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/batch`, {\n method: \"POST\",\n headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"batch create run\", true);\n return res;\n });\n }\n /**\n * Batch ingest/upsert multiple runs in the Langsmith system.\n * @param runs\n */\n async multipartIngestRuns({ runCreates, runUpdates, }, options) {\n if (runCreates === undefined && runUpdates === undefined) {\n return;\n }\n // transform and convert to dicts\n const allAttachments = {};\n let preparedCreateParams = [];\n for (const create of runCreates ?? []) {\n const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create);\n if (preparedCreate.id !== undefined &&\n preparedCreate.attachments !== undefined) {\n allAttachments[preparedCreate.id] = preparedCreate.attachments;\n }\n delete preparedCreate.attachments;\n preparedCreateParams.push(preparedCreate);\n }\n let preparedUpdateParams = [];\n for (const update of runUpdates ?? []) {\n preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update));\n }\n // require trace_id and dotted_order\n const invalidRunCreate = preparedCreateParams.find((runCreate) => {\n return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined);\n });\n if (invalidRunCreate !== undefined) {\n throw new Error(`Multipart ingest requires \"trace_id\" and \"dotted_order\" to be set when creating a run`);\n }\n const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => {\n return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined);\n });\n if (invalidRunUpdate !== undefined) {\n throw new Error(`Multipart ingest requires \"trace_id\" and \"dotted_order\" to be set when updating a run`);\n }\n // combine post and patch dicts where possible\n if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {\n const createById = preparedCreateParams.reduce((params, run) => {\n if (!run.id) {\n return params;\n }\n params[run.id] = run;\n return params;\n }, {});\n const standaloneUpdates = [];\n for (const updateParam of preparedUpdateParams) {\n if (updateParam.id !== undefined && createById[updateParam.id]) {\n createById[updateParam.id] = {\n ...createById[updateParam.id],\n ...updateParam,\n };\n }\n else {\n standaloneUpdates.push(updateParam);\n }\n }\n preparedCreateParams = Object.values(createById);\n preparedUpdateParams = standaloneUpdates;\n }\n if (preparedCreateParams.length === 0 &&\n preparedUpdateParams.length === 0) {\n return;\n }\n // send the runs in multipart requests\n const accumulatedContext = [];\n const accumulatedParts = [];\n for (const [method, payloads] of [\n [\"post\", preparedCreateParams],\n [\"patch\", preparedUpdateParams],\n ]) {\n for (const originalPayload of payloads) {\n // collect fields to be sent as separate parts\n const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload;\n const fields = { inputs, outputs, events, extra, error, serialized };\n // encode the main run payload\n const stringifiedPayload = serializePayloadForTracing(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`);\n accumulatedParts.push({\n name: `${method}.${payload.id}`,\n payload: new Blob([stringifiedPayload], {\n type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip\n }),\n });\n // encode the fields we collected\n for (const [key, value] of Object.entries(fields)) {\n if (value === undefined) {\n continue;\n }\n const stringifiedValue = serializePayloadForTracing(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`);\n accumulatedParts.push({\n name: `${method}.${payload.id}.${key}`,\n payload: new Blob([stringifiedValue], {\n type: `application/json; length=${stringifiedValue.length}`,\n }),\n });\n }\n // encode the attachments\n if (payload.id !== undefined) {\n const attachments = allAttachments[payload.id];\n if (attachments) {\n delete allAttachments[payload.id];\n for (const [name, attachment] of Object.entries(attachments)) {\n let contentType;\n let content;\n if (Array.isArray(attachment)) {\n [contentType, content] = attachment;\n }\n else {\n contentType = attachment.mimeType;\n content = attachment.data;\n }\n // Validate that the attachment name doesn't contain a '.'\n if (name.includes(\".\")) {\n console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` +\n `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);\n continue;\n }\n accumulatedParts.push({\n name: `attachment.${payload.id}.${name}`,\n payload: new Blob([content], {\n type: `${contentType}; length=${content.byteLength}`,\n }),\n });\n }\n }\n }\n // compute context\n accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`);\n }\n }\n await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join(\"; \"), options);\n }\n async _createNodeFetchBody(parts, boundary) {\n // Create multipart form data manually using Blobs\n const chunks = [];\n for (const part of parts) {\n // Add field boundary\n chunks.push(new Blob([`--${boundary}\\r\\n`]));\n chunks.push(new Blob([\n `Content-Disposition: form-data; name=\"${part.name}\"\\r\\n`,\n `Content-Type: ${part.payload.type}\\r\\n\\r\\n`,\n ]));\n chunks.push(part.payload);\n chunks.push(new Blob([\"\\r\\n\"]));\n }\n // Add final boundary\n chunks.push(new Blob([`--${boundary}--\\r\\n`]));\n // Combine all chunks into a single Blob\n const body = new Blob(chunks);\n // Convert Blob to ArrayBuffer for compatibility\n const arrayBuffer = await body.arrayBuffer();\n return arrayBuffer;\n }\n async _createMultipartStream(parts, boundary) {\n const encoder = new TextEncoder();\n // Create a ReadableStream for streaming the multipart data\n // Only do special handling if we're using node-fetch\n const stream = new ReadableStream({\n async start(controller) {\n // Helper function to write a chunk to the stream\n const writeChunk = async (chunk) => {\n if (typeof chunk === \"string\") {\n controller.enqueue(encoder.encode(chunk));\n }\n else {\n controller.enqueue(chunk);\n }\n };\n // Write each part to the stream\n for (const part of parts) {\n // Write boundary and headers\n await writeChunk(`--${boundary}\\r\\n`);\n await writeChunk(`Content-Disposition: form-data; name=\"${part.name}\"\\r\\n`);\n await writeChunk(`Content-Type: ${part.payload.type}\\r\\n\\r\\n`);\n // Write the payload\n const payloadStream = part.payload.stream();\n const reader = payloadStream.getReader();\n try {\n let result;\n while (!(result = await reader.read()).done) {\n controller.enqueue(result.value);\n }\n }\n finally {\n reader.releaseLock();\n }\n await writeChunk(\"\\r\\n\");\n }\n // Write final boundary\n await writeChunk(`--${boundary}--\\r\\n`);\n controller.close();\n },\n });\n return stream;\n }\n async _sendMultipartRequest(parts, context, options) {\n // Create multipart form data boundary\n const boundary = \"----LangSmithFormBoundary\" + Math.random().toString(36).slice(2);\n const isNodeFetch = _globalFetchImplementationIsNodeFetch();\n const buildBuffered = () => this._createNodeFetchBody(parts, boundary);\n const buildStream = () => this._createMultipartStream(parts, boundary);\n const sendWithRetry = async (bodyFactory) => {\n return this.batchIngestCaller.call(async () => {\n const body = await bodyFactory();\n const headers = {\n ...this.headers,\n \"Content-Type\": `multipart/form-data; boundary=${boundary}`,\n };\n if (options?.apiKey !== undefined) {\n headers[\"x-api-key\"] = options.apiKey;\n }\n let transformedBody = body;\n if (options?.useGzip &&\n typeof body === \"object\" &&\n \"pipeThrough\" in body) {\n transformedBody = body.pipeThrough(new CompressionStream(\"gzip\"));\n headers[\"Content-Encoding\"] = \"gzip\";\n }\n const response = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/multipart`, {\n method: \"POST\",\n headers,\n body: transformedBody,\n duplex: \"half\",\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, `Failed to send multipart request`, true);\n return response;\n });\n };\n try {\n let res;\n let streamedAttempt = false;\n // attempt stream only if not disabled and not using node-fetch or Bun\n if (!isNodeFetch &&\n !this.multipartStreamingDisabled &&\n getEnv() !== \"bun\") {\n streamedAttempt = true;\n res = await sendWithRetry(buildStream);\n }\n else {\n res = await sendWithRetry(buildBuffered);\n }\n // if stream fails, fallback to buffered body\n if ((!this.multipartStreamingDisabled || streamedAttempt) &&\n res.status === 422 &&\n (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) {\n console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. ` +\n `This usually means the host does not support chunked uploads. ` +\n `Retrying with a buffered upload for operation \"${context}\".`);\n // Disable streaming for future requests\n this.multipartStreamingDisabled = true;\n // retry with fully-buffered body\n res = await sendWithRetry(buildBuffered);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n catch (e) {\n console.warn(`${e.message.trim()}\\n\\nContext: ${context}`);\n }\n }\n async updateRun(runId, run, options) {\n assertUuid(runId);\n if (run.inputs) {\n run.inputs = await this.processInputs(run.inputs);\n }\n if (run.outputs) {\n run.outputs = await this.processOutputs(run.outputs);\n }\n // TODO: Untangle types\n const data = { ...run, id: runId };\n if (!this._filterForSampling([data], true).length) {\n return;\n }\n if (this.autoBatchTracing &&\n data.trace_id !== undefined &&\n data.dotted_order !== undefined) {\n const otelContext = this._cloneCurrentOTELContext();\n if (run.end_time !== undefined &&\n data.parent_run_id === undefined &&\n this.blockOnRootRunFinalization &&\n !this.manualFlushMode) {\n // Trigger batches as soon as a root trace ends and wait to ensure trace finishes\n // in serverless environments.\n await this.processRunOperation({\n action: \"update\",\n item: data,\n otelContext,\n apiKey: options?.apiKey,\n apiUrl: options?.apiUrl,\n }).catch(console.error);\n return;\n }\n else {\n void this.processRunOperation({\n action: \"update\",\n item: data,\n otelContext,\n apiKey: options?.apiKey,\n apiUrl: options?.apiUrl,\n }).catch(console.error);\n }\n return;\n }\n const headers = {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n };\n if (options?.apiKey !== undefined) {\n headers[\"x-api-key\"] = options.apiKey;\n }\n if (options?.workspaceId !== undefined) {\n headers[\"x-tenant-id\"] = options.workspaceId;\n }\n const body = serializePayloadForTracing(run, `Serializing payload to update run with id: ${runId}`);\n await this.caller.call(async () => {\n const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, {\n method: \"PATCH\",\n headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update run\", true);\n return res;\n });\n }\n async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) {\n assertUuid(runId);\n let run = await this._get(`/runs/${runId}`);\n if (loadChildRuns) {\n run = await this._loadChildRuns(run);\n }\n return run;\n }\n async getRunUrl({ runId, run, projectOpts, }) {\n if (run !== undefined) {\n let sessionId;\n if (run.session_id) {\n sessionId = run.session_id;\n }\n else if (projectOpts?.projectName) {\n sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id;\n }\n else if (projectOpts?.projectId) {\n sessionId = projectOpts?.projectId;\n }\n else {\n const project = await this.readProject({\n projectName: getLangSmithEnvironmentVariable(\"PROJECT\") || \"default\",\n });\n sessionId = project.id;\n }\n const tenantId = await this._getTenantId();\n return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`;\n }\n else if (runId !== undefined) {\n const run_ = await this.readRun(runId);\n if (!run_.app_path) {\n throw new Error(`Run ${runId} has no app_path`);\n }\n const baseUrl = this.getHostUrl();\n return `${baseUrl}${run_.app_path}`;\n }\n else {\n throw new Error(\"Must provide either runId or run\");\n }\n }\n async _loadChildRuns(run) {\n const childRuns = await toArray(this.listRuns({\n isRoot: false,\n projectId: run.session_id,\n traceId: run.trace_id,\n }));\n const treemap = {};\n const runs = {};\n // TODO: make dotted order required when the migration finishes\n childRuns.sort((a, b) => (a?.dotted_order ?? \"\").localeCompare(b?.dotted_order ?? \"\"));\n for (const childRun of childRuns) {\n if (childRun.parent_run_id === null ||\n childRun.parent_run_id === undefined) {\n throw new Error(`Child run ${childRun.id} has no parent`);\n }\n if (childRun.dotted_order?.startsWith(run.dotted_order ?? \"\") &&\n childRun.id !== run.id) {\n if (!(childRun.parent_run_id in treemap)) {\n treemap[childRun.parent_run_id] = [];\n }\n treemap[childRun.parent_run_id].push(childRun);\n runs[childRun.id] = childRun;\n }\n }\n run.child_runs = treemap[run.id] || [];\n for (const runId in treemap) {\n if (runId !== run.id) {\n runs[runId].child_runs = treemap[runId];\n }\n }\n return run;\n }\n /**\n * List runs from the LangSmith server.\n * @param projectId - The ID of the project to filter by.\n * @param projectName - The name of the project to filter by.\n * @param parentRunId - The ID of the parent run to filter by.\n * @param traceId - The ID of the trace to filter by.\n * @param referenceExampleId - The ID of the reference example to filter by.\n * @param startTime - The start time to filter by.\n * @param isRoot - Indicates whether to only return root runs.\n * @param runType - The run type to filter by.\n * @param error - Indicates whether to filter by error runs.\n * @param id - The ID of the run to filter by.\n * @param query - The query string to filter by.\n * @param filter - The filter string to apply to the run spans.\n * @param traceFilter - The filter string to apply on the root run of the trace.\n * @param treeFilter - The filter string to apply on other runs in the trace.\n * @param limit - The maximum number of runs to retrieve.\n * @returns {AsyncIterable} - The runs.\n *\n * @example\n * // List all runs in a project\n * const projectRuns = client.listRuns({ projectName: \"\" });\n *\n * @example\n * // List LLM and Chat runs in the last 24 hours\n * const todaysLLMRuns = client.listRuns({\n * projectName: \"\",\n * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),\n * run_type: \"llm\",\n * });\n *\n * @example\n * // List traces in a project\n * const rootRuns = client.listRuns({\n * projectName: \"\",\n * execution_order: 1,\n * });\n *\n * @example\n * // List runs without errors\n * const correctRuns = client.listRuns({\n * projectName: \"\",\n * error: false,\n * });\n *\n * @example\n * // List runs by run ID\n * const runIds = [\n * \"a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836\",\n * \"9398e6be-964f-4aa4-8ae9-ad78cd4b7074\",\n * ];\n * const selectedRuns = client.listRuns({ run_ids: runIds });\n *\n * @example\n * // List all \"chain\" type runs that took more than 10 seconds and had `total_tokens` greater than 5000\n * const chainRuns = client.listRuns({\n * projectName: \"\",\n * filter: 'and(eq(run_type, \"chain\"), gt(latency, 10), gt(total_tokens, 5000))',\n * });\n *\n * @example\n * // List all runs called \"extractor\" whose root of the trace was assigned feedback \"user_score\" score of 1\n * const goodExtractorRuns = client.listRuns({\n * projectName: \"\",\n * filter: 'eq(name, \"extractor\")',\n * traceFilter: 'and(eq(feedback_key, \"user_score\"), eq(feedback_score, 1))',\n * });\n *\n * @example\n * // List all runs that started after a specific timestamp and either have \"error\" not equal to null or a \"Correctness\" feedback score equal to 0\n * const complexRuns = client.listRuns({\n * projectName: \"\",\n * filter: 'and(gt(start_time, \"2023-07-15T12:34:56Z\"), or(neq(error, null), and(eq(feedback_key, \"Correctness\"), eq(feedback_score, 0.0))))',\n * });\n *\n * @example\n * // List all runs where `tags` include \"experimental\" or \"beta\" and `latency` is greater than 2 seconds\n * const taggedRuns = client.listRuns({\n * projectName: \"\",\n * filter: 'and(or(has(tags, \"experimental\"), has(tags, \"beta\")), gt(latency, 2))',\n * });\n */\n async *listRuns(props) {\n const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props;\n let projectIds = [];\n if (projectId) {\n projectIds = Array.isArray(projectId) ? projectId : [projectId];\n }\n if (projectName) {\n const projectNames = Array.isArray(projectName)\n ? projectName\n : [projectName];\n const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));\n projectIds.push(...projectIds_);\n }\n const default_select = [\n \"app_path\",\n \"completion_cost\",\n \"completion_tokens\",\n \"dotted_order\",\n \"end_time\",\n \"error\",\n \"events\",\n \"extra\",\n \"feedback_stats\",\n \"first_token_time\",\n \"id\",\n \"inputs\",\n \"name\",\n \"outputs\",\n \"parent_run_id\",\n \"parent_run_ids\",\n \"prompt_cost\",\n \"prompt_tokens\",\n \"reference_example_id\",\n \"run_type\",\n \"session_id\",\n \"start_time\",\n \"status\",\n \"tags\",\n \"total_cost\",\n \"total_tokens\",\n \"trace_id\",\n ];\n const body = {\n session: projectIds.length ? projectIds : null,\n run_type: runType,\n reference_example: referenceExampleId,\n query,\n filter,\n trace_filter: traceFilter,\n tree_filter: treeFilter,\n execution_order: executionOrder,\n parent_run: parentRunId,\n start_time: startTime ? startTime.toISOString() : null,\n error,\n id,\n limit,\n trace: traceId,\n select: select ? select : default_select,\n is_root: isRoot,\n order,\n };\n if (body.select.includes(\"child_run_ids\")) {\n warnOnce(\"Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.\");\n }\n let runsYielded = 0;\n for await (const runs of this._getCursorPaginatedList(\"/runs/query\", body)) {\n if (limit) {\n if (runsYielded >= limit) {\n break;\n }\n if (runs.length + runsYielded > limit) {\n const newRuns = runs.slice(0, limit - runsYielded);\n yield* newRuns;\n break;\n }\n runsYielded += runs.length;\n yield* runs;\n }\n else {\n yield* runs;\n }\n }\n }\n async *listGroupRuns(props) {\n const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props;\n const sessionId = projectId || (await this.readProject({ projectName })).id;\n const baseBody = {\n session_id: sessionId,\n group_by: groupBy,\n filter,\n start_time: startTime ? startTime.toISOString() : null,\n end_time: endTime ? endTime.toISOString() : null,\n limit: Number(limit) || 100,\n };\n let currentOffset = Number(offset) || 0;\n const path = \"/runs/group\";\n const url = `${this.apiUrl}${path}`;\n while (true) {\n const currentBody = {\n ...baseBody,\n offset: currentOffset,\n };\n // Remove undefined values from the payload\n const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined));\n const body = JSON.stringify(filteredPayload);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(url, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, `Failed to fetch ${path}`);\n return res;\n });\n const items = await response.json();\n const { groups, total } = items;\n if (groups.length === 0) {\n break;\n }\n for (const thread of groups) {\n yield thread;\n }\n currentOffset += groups.length;\n if (currentOffset >= total) {\n break;\n }\n }\n }\n async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) {\n let projectIds_ = projectIds || [];\n if (projectNames) {\n projectIds_ = [\n ...(projectIds || []),\n ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))),\n ];\n }\n const payload = {\n id,\n trace,\n parent_run: parentRun,\n run_type: runType,\n session: projectIds_,\n reference_example: referenceExampleIds,\n start_time: startTime,\n end_time: endTime,\n error,\n query,\n filter,\n trace_filter: traceFilter,\n tree_filter: treeFilter,\n is_root: isRoot,\n data_source_type: dataSourceType,\n };\n // Remove undefined values from the payload\n const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined));\n const body = JSON.stringify(filteredPayload);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/runs/stats`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"get run stats\");\n return res;\n });\n const result = await response.json();\n return result;\n }\n async shareRun(runId, { shareId } = {}) {\n const data = {\n run_id: runId,\n share_token: shareId || uuid.v4(),\n };\n assertUuid(runId);\n const body = JSON.stringify(data);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, {\n method: \"PUT\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"share run\");\n return res;\n });\n const result = await response.json();\n if (result === null || !(\"share_token\" in result)) {\n throw new Error(\"Invalid response from server\");\n }\n return `${this.getHostUrl()}/public/${result[\"share_token\"]}/r`;\n }\n async unshareRun(runId) {\n assertUuid(runId);\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"unshare run\", true);\n return res;\n });\n }\n async readRunSharedLink(runId) {\n assertUuid(runId);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"read run shared link\");\n return res;\n });\n const result = await response.json();\n if (result === null || !(\"share_token\" in result)) {\n return undefined;\n }\n return `${this.getHostUrl()}/public/${result[\"share_token\"]}/r`;\n }\n async listSharedRuns(shareToken, { runIds, } = {}) {\n const queryParams = new URLSearchParams({\n share_token: shareToken,\n });\n if (runIds !== undefined) {\n for (const runId of runIds) {\n queryParams.append(\"id\", runId);\n }\n }\n assertUuid(shareToken);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/runs${queryParams}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"list shared runs\");\n return res;\n });\n const runs = await response.json();\n return runs;\n }\n async readDatasetSharedSchema(datasetId, datasetName) {\n if (!datasetId && !datasetName) {\n throw new Error(\"Either datasetId or datasetName must be given\");\n }\n if (!datasetId) {\n const dataset = await this.readDataset({ datasetName });\n datasetId = dataset.id;\n }\n assertUuid(datasetId);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"read dataset shared schema\");\n return res;\n });\n const shareSchema = await response.json();\n shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;\n return shareSchema;\n }\n async shareDataset(datasetId, datasetName) {\n if (!datasetId && !datasetName) {\n throw new Error(\"Either datasetId or datasetName must be given\");\n }\n if (!datasetId) {\n const dataset = await this.readDataset({ datasetName });\n datasetId = dataset.id;\n }\n const data = {\n dataset_id: datasetId,\n };\n assertUuid(datasetId);\n const body = JSON.stringify(data);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, {\n method: \"PUT\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"share dataset\");\n return res;\n });\n const shareSchema = await response.json();\n shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;\n return shareSchema;\n }\n async unshareDataset(datasetId) {\n assertUuid(datasetId);\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"unshare dataset\", true);\n return res;\n });\n }\n async readSharedDataset(shareToken) {\n assertUuid(shareToken);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/datasets`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"read shared dataset\");\n return res;\n });\n const dataset = await response.json();\n return dataset;\n }\n /**\n * Get shared examples.\n *\n * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public.\n * @param {Object} [options] Additional options for listing the examples.\n * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by.\n * @returns {Promise} The shared examples.\n */\n async listSharedExamples(shareToken, options) {\n const params = {};\n if (options?.exampleIds) {\n params.id = options.exampleIds;\n }\n const urlParams = new URLSearchParams();\n Object.entries(params).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => urlParams.append(key, v));\n }\n else {\n urlParams.append(key, value);\n }\n });\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"list shared examples\");\n return res;\n });\n const result = await response.json();\n if (!response.ok) {\n if (\"detail\" in result) {\n throw new Error(`Failed to list shared examples.\\nStatus: ${response.status}\\nMessage: ${Array.isArray(result.detail)\n ? result.detail.join(\"\\n\")\n : \"Unspecified error\"}`);\n }\n throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`);\n }\n return result.map((example) => ({\n ...example,\n _hostUrl: this.getHostUrl(),\n }));\n }\n async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) {\n const upsert_ = upsert ? `?upsert=true` : \"\";\n const endpoint = `${this.apiUrl}/sessions${upsert_}`;\n const extra = projectExtra || {};\n if (metadata) {\n extra[\"metadata\"] = metadata;\n }\n const body = {\n name: projectName,\n extra,\n description,\n };\n if (referenceDatasetId !== null) {\n body[\"reference_dataset_id\"] = referenceDatasetId;\n }\n const serializedBody = JSON.stringify(body);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(endpoint, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: serializedBody,\n });\n await raiseForStatus(res, \"create project\");\n return res;\n });\n const result = await response.json();\n return result;\n }\n async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) {\n const endpoint = `${this.apiUrl}/sessions/${projectId}`;\n let extra = projectExtra;\n if (metadata) {\n extra = { ...(extra || {}), metadata };\n }\n const body = JSON.stringify({\n name,\n extra,\n description,\n end_time: endTime ? new Date(endTime).toISOString() : null,\n });\n const response = await this.caller.call(async () => {\n const res = await this._fetch(endpoint, {\n method: \"PATCH\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update project\");\n return res;\n });\n const result = await response.json();\n return result;\n }\n async hasProject({ projectId, projectName, }) {\n // TODO: Add a head request\n let path = \"/sessions\";\n const params = new URLSearchParams();\n if (projectId !== undefined && projectName !== undefined) {\n throw new Error(\"Must provide either projectName or projectId, not both\");\n }\n else if (projectId !== undefined) {\n assertUuid(projectId);\n path += `/${projectId}`;\n }\n else if (projectName !== undefined) {\n params.append(\"name\", projectName);\n }\n else {\n throw new Error(\"Must provide projectName or projectId\");\n }\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}${path}?${params}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"has project\");\n return res;\n });\n // consume the response body to release the connection\n // https://undici.nodejs.org/#/?id=garbage-collection\n try {\n const result = await response.json();\n if (!response.ok) {\n return false;\n }\n // If it's OK and we're querying by name, need to check the list is not empty\n if (Array.isArray(result)) {\n return result.length > 0;\n }\n // projectId querying\n return true;\n }\n catch (e) {\n return false;\n }\n }\n async readProject({ projectId, projectName, includeStats, }) {\n let path = \"/sessions\";\n const params = new URLSearchParams();\n if (projectId !== undefined && projectName !== undefined) {\n throw new Error(\"Must provide either projectName or projectId, not both\");\n }\n else if (projectId !== undefined) {\n assertUuid(projectId);\n path += `/${projectId}`;\n }\n else if (projectName !== undefined) {\n params.append(\"name\", projectName);\n }\n else {\n throw new Error(\"Must provide projectName or projectId\");\n }\n if (includeStats !== undefined) {\n params.append(\"include_stats\", includeStats.toString());\n }\n const response = await this._get(path, params);\n let result;\n if (Array.isArray(response)) {\n if (response.length === 0) {\n throw new Error(`Project[id=${projectId}, name=${projectName}] not found`);\n }\n result = response[0];\n }\n else {\n result = response;\n }\n return result;\n }\n async getProjectUrl({ projectId, projectName, }) {\n if (projectId === undefined && projectName === undefined) {\n throw new Error(\"Must provide either projectName or projectId\");\n }\n const project = await this.readProject({ projectId, projectName });\n const tenantId = await this._getTenantId();\n return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`;\n }\n async getDatasetUrl({ datasetId, datasetName, }) {\n if (datasetId === undefined && datasetName === undefined) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n const dataset = await this.readDataset({ datasetId, datasetName });\n const tenantId = await this._getTenantId();\n return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`;\n }\n async _getTenantId() {\n if (this._tenantId !== null) {\n return this._tenantId;\n }\n const queryParams = new URLSearchParams({ limit: \"1\" });\n for await (const projects of this._getPaginated(\"/sessions\", queryParams)) {\n this._tenantId = projects[0].tenant_id;\n return projects[0].tenant_id;\n }\n throw new Error(\"No projects found to resolve tenant.\");\n }\n async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, includeStats, datasetVersion, referenceFree, metadata, } = {}) {\n const params = new URLSearchParams();\n if (projectIds !== undefined) {\n for (const projectId of projectIds) {\n params.append(\"id\", projectId);\n }\n }\n if (name !== undefined) {\n params.append(\"name\", name);\n }\n if (nameContains !== undefined) {\n params.append(\"name_contains\", nameContains);\n }\n if (referenceDatasetId !== undefined) {\n params.append(\"reference_dataset\", referenceDatasetId);\n }\n else if (referenceDatasetName !== undefined) {\n const dataset = await this.readDataset({\n datasetName: referenceDatasetName,\n });\n params.append(\"reference_dataset\", dataset.id);\n }\n if (includeStats !== undefined) {\n params.append(\"include_stats\", includeStats.toString());\n }\n if (datasetVersion !== undefined) {\n params.append(\"dataset_version\", datasetVersion);\n }\n if (referenceFree !== undefined) {\n params.append(\"reference_free\", referenceFree.toString());\n }\n if (metadata !== undefined) {\n params.append(\"metadata\", JSON.stringify(metadata));\n }\n for await (const projects of this._getPaginated(\"/sessions\", params)) {\n yield* projects;\n }\n }\n async deleteProject({ projectId, projectName, }) {\n let projectId_;\n if (projectId === undefined && projectName === undefined) {\n throw new Error(\"Must provide projectName or projectId\");\n }\n else if (projectId !== undefined && projectName !== undefined) {\n throw new Error(\"Must provide either projectName or projectId, not both\");\n }\n else if (projectId === undefined) {\n projectId_ = (await this.readProject({ projectName })).id;\n }\n else {\n projectId_ = projectId;\n }\n assertUuid(projectId_);\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/sessions/${projectId_}`, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, `delete session ${projectId_} (${projectName})`, true);\n return res;\n });\n }\n async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) {\n const url = `${this.apiUrl}/datasets/upload`;\n const formData = new FormData();\n formData.append(\"file\", csvFile, fileName);\n inputKeys.forEach((key) => {\n formData.append(\"input_keys\", key);\n });\n outputKeys.forEach((key) => {\n formData.append(\"output_keys\", key);\n });\n if (description) {\n formData.append(\"description\", description);\n }\n if (dataType) {\n formData.append(\"data_type\", dataType);\n }\n if (name) {\n formData.append(\"name\", name);\n }\n const response = await this.caller.call(async () => {\n const res = await this._fetch(url, {\n method: \"POST\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: formData,\n });\n await raiseForStatus(res, \"upload CSV\");\n return res;\n });\n const result = await response.json();\n return result;\n }\n async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) {\n const body = {\n name,\n description,\n extra: metadata ? { metadata } : undefined,\n };\n if (dataType) {\n body.data_type = dataType;\n }\n if (inputsSchema) {\n body.inputs_schema_definition = inputsSchema;\n }\n if (outputsSchema) {\n body.outputs_schema_definition = outputsSchema;\n }\n const serializedBody = JSON.stringify(body);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: serializedBody,\n });\n await raiseForStatus(res, \"create dataset\");\n return res;\n });\n const result = await response.json();\n return result;\n }\n async readDataset({ datasetId, datasetName, }) {\n let path = \"/datasets\";\n // limit to 1 result\n const params = new URLSearchParams({ limit: \"1\" });\n if (datasetId && datasetName) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId) {\n assertUuid(datasetId);\n path += `/${datasetId}`;\n }\n else if (datasetName) {\n params.append(\"name\", datasetName);\n }\n else {\n throw new Error(\"Must provide datasetName or datasetId\");\n }\n const response = await this._get(path, params);\n let result;\n if (Array.isArray(response)) {\n if (response.length === 0) {\n throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`);\n }\n result = response[0];\n }\n else {\n result = response;\n }\n return result;\n }\n async hasDataset({ datasetId, datasetName, }) {\n try {\n await this.readDataset({ datasetId, datasetName });\n return true;\n }\n catch (e) {\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n e instanceof Error &&\n e.message.toLocaleLowerCase().includes(\"not found\")) {\n return false;\n }\n throw e;\n }\n }\n async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) {\n let datasetId_ = datasetId;\n if (datasetId_ === undefined && datasetName === undefined) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n else if (datasetId_ !== undefined && datasetName !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n const urlParams = new URLSearchParams({\n from_version: typeof fromVersion === \"string\"\n ? fromVersion\n : fromVersion.toISOString(),\n to_version: typeof toVersion === \"string\" ? toVersion : toVersion.toISOString(),\n });\n const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams);\n return response;\n }\n async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) {\n const path = \"/datasets\";\n if (datasetId !== undefined) {\n // do nothing\n }\n else if (datasetName !== undefined) {\n datasetId = (await this.readDataset({ datasetName })).id;\n }\n else {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n const response = await this._getResponse(`${path}/${datasetId}/openai_ft`);\n const datasetText = await response.text();\n const dataset = datasetText\n .trim()\n .split(\"\\n\")\n .map((line) => JSON.parse(line));\n return dataset;\n }\n async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) {\n const path = \"/datasets\";\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n if (datasetIds !== undefined) {\n for (const id_ of datasetIds) {\n params.append(\"id\", id_);\n }\n }\n if (datasetName !== undefined) {\n params.append(\"name\", datasetName);\n }\n if (datasetNameContains !== undefined) {\n params.append(\"name_contains\", datasetNameContains);\n }\n if (metadata !== undefined) {\n params.append(\"metadata\", JSON.stringify(metadata));\n }\n for await (const datasets of this._getPaginated(path, params)) {\n yield* datasets;\n }\n }\n /**\n * Update a dataset\n * @param props The dataset details to update\n * @returns The updated dataset\n */\n async updateDataset(props) {\n const { datasetId, datasetName, ...update } = props;\n if (!datasetId && !datasetName) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id;\n assertUuid(_datasetId);\n const body = JSON.stringify(update);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}`, {\n method: \"PATCH\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update dataset\");\n return res;\n });\n return (await response.json());\n }\n /**\n * Updates a tag on a dataset.\n *\n * If the tag is already assigned to a different version of this dataset,\n * the tag will be moved to the new version. The as_of parameter is used to\n * determine which version of the dataset to apply the new tags to.\n *\n * It must be an exact version of the dataset to succeed. You can\n * use the \"readDatasetVersion\" method to find the exact version\n * to apply the tags to.\n * @param params.datasetId The ID of the dataset to update. Must be provided if \"datasetName\" is not provided.\n * @param params.datasetName The name of the dataset to update. Must be provided if \"datasetId\" is not provided.\n * @param params.asOf The timestamp of the dataset to apply the new tags to.\n * @param params.tag The new tag to apply to the dataset.\n */\n async updateDatasetTag(props) {\n const { datasetId, datasetName, asOf, tag } = props;\n if (!datasetId && !datasetName) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id;\n assertUuid(_datasetId);\n const body = JSON.stringify({\n as_of: typeof asOf === \"string\" ? asOf : asOf.toISOString(),\n tag,\n });\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}/tags`, {\n method: \"PUT\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update dataset tags\", true);\n return res;\n });\n }\n async deleteDataset({ datasetId, datasetName, }) {\n let path = \"/datasets\";\n let datasetId_ = datasetId;\n if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetName !== undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n if (datasetId_ !== undefined) {\n assertUuid(datasetId_);\n path += `/${datasetId_}`;\n }\n else {\n throw new Error(\"Must provide datasetName or datasetId\");\n }\n await this.caller.call(async () => {\n const res = await this._fetch(this.apiUrl + path, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, `delete ${path}`, true);\n return res;\n });\n }\n async indexDataset({ datasetId, datasetName, tag, }) {\n let datasetId_ = datasetId;\n if (!datasetId_ && !datasetName) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n else if (datasetId_ && datasetName) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (!datasetId_) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n assertUuid(datasetId_);\n const data = {\n tag: tag,\n };\n const body = JSON.stringify(data);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/index`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"index dataset\");\n return res;\n });\n await response.json();\n }\n /**\n * Lets you run a similarity search query on a dataset.\n *\n * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing.\n *\n * @param inputs The input on which to run the similarity search. Must have the\n * same schema as the dataset.\n *\n * @param datasetId The dataset to search for similar examples.\n *\n * @param limit The maximum number of examples to return. Will return the top `limit` most\n * similar examples in order of most similar to least similar. If no similar\n * examples are found, random examples will be returned.\n *\n * @param filter A filter string to apply to the search. Only examples will be returned that\n * match the filter string. Some examples of filters\n *\n * - eq(metadata.mykey, \"value\")\n * - and(neq(metadata.my.nested.key, \"value\"), neq(metadata.mykey, \"value\"))\n * - or(eq(metadata.mykey, \"value\"), eq(metadata.mykey, \"othervalue\"))\n *\n * @returns A list of similar examples.\n *\n *\n * @example\n * dataset_id = \"123e4567-e89b-12d3-a456-426614174000\"\n * inputs = {\"text\": \"How many people live in Berlin?\"}\n * limit = 5\n * examples = await client.similarExamples(inputs, dataset_id, limit)\n */\n async similarExamples(inputs, datasetId, limit, { filter, } = {}) {\n const data = {\n limit: limit,\n inputs: inputs,\n };\n if (filter !== undefined) {\n data[\"filter\"] = filter;\n }\n assertUuid(datasetId);\n const body = JSON.stringify(data);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/search`, {\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n method: \"POST\",\n body,\n });\n await raiseForStatus(res, \"fetch similar examples\");\n return res;\n });\n const result = await response.json();\n return result[\"examples\"];\n }\n async createExample(inputsOrUpdate, outputs, options) {\n if (isExampleCreate(inputsOrUpdate)) {\n if (outputs !== undefined || options !== undefined) {\n throw new Error(\"Cannot provide outputs or options when using ExampleCreate object\");\n }\n }\n let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id;\n const datasetName_ = outputs\n ? options?.datasetName\n : inputsOrUpdate.dataset_name;\n if (datasetId_ === undefined && datasetName_ === undefined) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n else if (datasetId_ !== undefined && datasetName_ !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName: datasetName_ });\n datasetId_ = dataset.id;\n }\n const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date();\n let data;\n if (!isExampleCreate(inputsOrUpdate)) {\n data = {\n inputs: inputsOrUpdate,\n outputs,\n created_at: createdAt_?.toISOString(),\n id: options?.exampleId,\n metadata: options?.metadata,\n split: options?.split,\n source_run_id: options?.sourceRunId,\n use_source_run_io: options?.useSourceRunIO,\n use_source_run_attachments: options?.useSourceRunAttachments,\n attachments: options?.attachments,\n };\n }\n else {\n data = inputsOrUpdate;\n }\n const response = await this._uploadExamplesMultipart(datasetId_, [data]);\n const example = await this.readExample(response.example_ids?.[0] ?? uuid.v4());\n return example;\n }\n async createExamples(propsOrUploads) {\n if (Array.isArray(propsOrUploads)) {\n if (propsOrUploads.length === 0) {\n return [];\n }\n const uploads = propsOrUploads;\n let datasetId_ = uploads[0].dataset_id;\n const datasetName_ = uploads[0].dataset_name;\n if (datasetId_ === undefined && datasetName_ === undefined) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n else if (datasetId_ !== undefined && datasetName_ !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName: datasetName_ });\n datasetId_ = dataset.id;\n }\n const response = await this._uploadExamplesMultipart(datasetId_, uploads);\n const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id)));\n return examples;\n }\n const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads;\n if (inputs === undefined) {\n throw new Error(\"Must provide inputs when using legacy parameters\");\n }\n let datasetId_ = datasetId;\n const datasetName_ = datasetName;\n if (datasetId_ === undefined && datasetName_ === undefined) {\n throw new Error(\"Must provide either datasetName or datasetId\");\n }\n else if (datasetId_ !== undefined && datasetName_ !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName: datasetName_ });\n datasetId_ = dataset.id;\n }\n const formattedExamples = inputs.map((input, idx) => {\n return {\n dataset_id: datasetId_,\n inputs: input,\n outputs: outputs?.[idx],\n metadata: metadata?.[idx],\n split: splits?.[idx],\n id: exampleIds?.[idx],\n attachments: attachments?.[idx],\n source_run_id: sourceRunIds?.[idx],\n use_source_run_io: useSourceRunIOs?.[idx],\n use_source_run_attachments: useSourceRunAttachments?.[idx],\n };\n });\n const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples);\n const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id)));\n return examples;\n }\n async createLLMExample(input, generation, options) {\n return this.createExample({ input }, { output: generation }, options);\n }\n async createChatExample(input, generations, options) {\n const finalInput = input.map((message) => {\n if (isLangChainMessage(message)) {\n return convertLangChainMessageToExample(message);\n }\n return message;\n });\n const finalOutput = isLangChainMessage(generations)\n ? convertLangChainMessageToExample(generations)\n : generations;\n return this.createExample({ input: finalInput }, { output: finalOutput }, options);\n }\n async readExample(exampleId) {\n assertUuid(exampleId);\n const path = `/examples/${exampleId}`;\n const rawExample = await this._get(path);\n const { attachment_urls, ...rest } = rawExample;\n const example = rest;\n if (attachment_urls) {\n example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => {\n acc[key.slice(\"attachment.\".length)] = {\n presigned_url: value.presigned_url,\n mime_type: value.mime_type,\n };\n return acc;\n }, {});\n }\n return example;\n }\n async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) {\n let datasetId_;\n if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId !== undefined) {\n datasetId_ = datasetId;\n }\n else if (datasetName !== undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n else {\n throw new Error(\"Must provide a datasetName or datasetId\");\n }\n const params = new URLSearchParams({ dataset: datasetId_ });\n const dataset_version = asOf\n ? typeof asOf === \"string\"\n ? asOf\n : asOf?.toISOString()\n : undefined;\n if (dataset_version) {\n params.append(\"as_of\", dataset_version);\n }\n const inlineS3Urls_ = inlineS3Urls ?? true;\n params.append(\"inline_s3_urls\", inlineS3Urls_.toString());\n if (exampleIds !== undefined) {\n for (const id_ of exampleIds) {\n params.append(\"id\", id_);\n }\n }\n if (splits !== undefined) {\n for (const split of splits) {\n params.append(\"splits\", split);\n }\n }\n if (metadata !== undefined) {\n const serializedMetadata = JSON.stringify(metadata);\n params.append(\"metadata\", serializedMetadata);\n }\n if (limit !== undefined) {\n params.append(\"limit\", limit.toString());\n }\n if (offset !== undefined) {\n params.append(\"offset\", offset.toString());\n }\n if (filter !== undefined) {\n params.append(\"filter\", filter);\n }\n if (includeAttachments === true) {\n [\"attachment_urls\", \"outputs\", \"metadata\"].forEach((field) => params.append(\"select\", field));\n }\n let i = 0;\n for await (const rawExamples of this._getPaginated(\"/examples\", params)) {\n for (const rawExample of rawExamples) {\n const { attachment_urls, ...rest } = rawExample;\n const example = rest;\n if (attachment_urls) {\n example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => {\n acc[key.slice(\"attachment.\".length)] = {\n presigned_url: value.presigned_url,\n mime_type: value.mime_type || undefined,\n };\n return acc;\n }, {});\n }\n yield example;\n i++;\n }\n if (limit !== undefined && i >= limit) {\n break;\n }\n }\n }\n async deleteExample(exampleId) {\n assertUuid(exampleId);\n const path = `/examples/${exampleId}`;\n await this.caller.call(async () => {\n const res = await this._fetch(this.apiUrl + path, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, `delete ${path}`, true);\n return res;\n });\n }\n async updateExample(exampleIdOrUpdate, update) {\n let exampleId;\n if (update) {\n exampleId = exampleIdOrUpdate;\n }\n else {\n exampleId = exampleIdOrUpdate.id;\n }\n assertUuid(exampleId);\n let updateToUse;\n if (update) {\n updateToUse = { id: exampleId, ...update };\n }\n else {\n updateToUse = exampleIdOrUpdate;\n }\n let datasetId;\n if (updateToUse.dataset_id !== undefined) {\n datasetId = updateToUse.dataset_id;\n }\n else {\n const example = await this.readExample(exampleId);\n datasetId = example.dataset_id;\n }\n return this._updateExamplesMultipart(datasetId, [updateToUse]);\n }\n async updateExamples(update) {\n // We will naively get dataset id from first example and assume it works for all\n let datasetId;\n if (update[0].dataset_id === undefined) {\n const example = await this.readExample(update[0].id);\n datasetId = example.dataset_id;\n }\n else {\n datasetId = update[0].dataset_id;\n }\n return this._updateExamplesMultipart(datasetId, update);\n }\n /**\n * Get dataset version by closest date or exact tag.\n *\n * Use this to resolve the nearest version to a given timestamp or for a given tag.\n *\n * @param options The options for getting the dataset version\n * @param options.datasetId The ID of the dataset\n * @param options.datasetName The name of the dataset\n * @param options.asOf The timestamp of the dataset to retrieve\n * @param options.tag The tag of the dataset to retrieve\n * @returns The dataset version\n */\n async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) {\n let resolvedDatasetId;\n if (!datasetId) {\n const dataset = await this.readDataset({ datasetName });\n resolvedDatasetId = dataset.id;\n }\n else {\n resolvedDatasetId = datasetId;\n }\n assertUuid(resolvedDatasetId);\n if ((asOf && tag) || (!asOf && !tag)) {\n throw new Error(\"Exactly one of asOf and tag must be specified.\");\n }\n const params = new URLSearchParams();\n if (asOf !== undefined) {\n params.append(\"as_of\", typeof asOf === \"string\" ? asOf : asOf.toISOString());\n }\n if (tag !== undefined) {\n params.append(\"tag\", tag);\n }\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, {\n method: \"GET\",\n headers: { ...this.headers },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"read dataset version\");\n return res;\n });\n return await response.json();\n }\n async listDatasetSplits({ datasetId, datasetName, asOf, }) {\n let datasetId_;\n if (datasetId === undefined && datasetName === undefined) {\n throw new Error(\"Must provide dataset name or ID\");\n }\n else if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId === undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n else {\n datasetId_ = datasetId;\n }\n assertUuid(datasetId_);\n const params = new URLSearchParams();\n const dataset_version = asOf\n ? typeof asOf === \"string\"\n ? asOf\n : asOf?.toISOString()\n : undefined;\n if (dataset_version) {\n params.append(\"as_of\", dataset_version);\n }\n const response = await this._get(`/datasets/${datasetId_}/splits`, params);\n return response;\n }\n async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) {\n let datasetId_;\n if (datasetId === undefined && datasetName === undefined) {\n throw new Error(\"Must provide dataset name or ID\");\n }\n else if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error(\"Must provide either datasetName or datasetId, not both\");\n }\n else if (datasetId === undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n else {\n datasetId_ = datasetId;\n }\n assertUuid(datasetId_);\n const data = {\n split_name: splitName,\n examples: exampleIds.map((id) => {\n assertUuid(id);\n return id;\n }),\n remove,\n };\n const body = JSON.stringify(data);\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/splits`, {\n method: \"PUT\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update dataset splits\", true);\n return res;\n });\n }\n /**\n * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.\n */\n async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) {\n warnOnce(\"This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.\");\n let run_;\n if (typeof run === \"string\") {\n run_ = await this.readRun(run, { loadChildRuns });\n }\n else if (typeof run === \"object\" && \"id\" in run) {\n run_ = run;\n }\n else {\n throw new Error(`Invalid run type: ${typeof run}`);\n }\n if (run_.reference_example_id !== null &&\n run_.reference_example_id !== undefined) {\n referenceExample = await this.readExample(run_.reference_example_id);\n }\n const feedbackResult = await evaluator.evaluateRun(run_, referenceExample);\n const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo);\n return feedbacks[0];\n }\n async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = \"api\", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) {\n if (!runId && !projectId) {\n throw new Error(\"One of runId or projectId must be provided\");\n }\n if (runId && projectId) {\n throw new Error(\"Only one of runId or projectId can be provided\");\n }\n const feedback_source = {\n type: feedbackSourceType ?? \"api\",\n metadata: sourceInfo ?? {},\n };\n if (sourceRunId !== undefined &&\n feedback_source?.metadata !== undefined &&\n !feedback_source.metadata[\"__run\"]) {\n feedback_source.metadata[\"__run\"] = { run_id: sourceRunId };\n }\n if (feedback_source?.metadata !== undefined &&\n feedback_source.metadata[\"__run\"]?.run_id !== undefined) {\n assertUuid(feedback_source.metadata[\"__run\"].run_id);\n }\n const feedback = {\n id: feedbackId ?? uuid.v4(),\n run_id: runId,\n key,\n score: _formatFeedbackScore(score),\n value,\n correction,\n comment,\n feedback_source: feedback_source,\n comparative_experiment_id: comparativeExperimentId,\n feedbackConfig,\n session_id: projectId,\n };\n const body = JSON.stringify(feedback);\n const url = `${this.apiUrl}/feedback`;\n await this.caller.call(async () => {\n const res = await this._fetch(url, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"create feedback\", true);\n return res;\n });\n return feedback;\n }\n async updateFeedback(feedbackId, { score, value, correction, comment, }) {\n const feedbackUpdate = {};\n if (score !== undefined && score !== null) {\n feedbackUpdate[\"score\"] = _formatFeedbackScore(score);\n }\n if (value !== undefined && value !== null) {\n feedbackUpdate[\"value\"] = value;\n }\n if (correction !== undefined && correction !== null) {\n feedbackUpdate[\"correction\"] = correction;\n }\n if (comment !== undefined && comment !== null) {\n feedbackUpdate[\"comment\"] = comment;\n }\n assertUuid(feedbackId);\n const body = JSON.stringify(feedbackUpdate);\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/feedback/${feedbackId}`, {\n method: \"PATCH\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update feedback\", true);\n return res;\n });\n }\n async readFeedback(feedbackId) {\n assertUuid(feedbackId);\n const path = `/feedback/${feedbackId}`;\n const response = await this._get(path);\n return response;\n }\n async deleteFeedback(feedbackId) {\n assertUuid(feedbackId);\n const path = `/feedback/${feedbackId}`;\n await this.caller.call(async () => {\n const res = await this._fetch(this.apiUrl + path, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, `delete ${path}`, true);\n return res;\n });\n }\n async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) {\n const queryParams = new URLSearchParams();\n if (runIds) {\n for (const runId of runIds) {\n assertUuid(runId);\n queryParams.append(\"run\", runId);\n }\n }\n if (feedbackKeys) {\n for (const key of feedbackKeys) {\n queryParams.append(\"key\", key);\n }\n }\n if (feedbackSourceTypes) {\n for (const type of feedbackSourceTypes) {\n queryParams.append(\"source\", type);\n }\n }\n for await (const feedbacks of this._getPaginated(\"/feedback\", queryParams)) {\n yield* feedbacks;\n }\n }\n /**\n * Creates a presigned feedback token and URL.\n *\n * The token can be used to authorize feedback metrics without\n * needing an API key. This is useful for giving browser-based\n * applications the ability to submit feedback without needing\n * to expose an API key.\n *\n * @param runId The ID of the run.\n * @param feedbackKey The feedback key.\n * @param options Additional options for the token.\n * @param options.expiration The expiration time for the token.\n *\n * @returns A promise that resolves to a FeedbackIngestToken.\n */\n async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) {\n const body = {\n run_id: runId,\n feedback_key: feedbackKey,\n feedback_config: feedbackConfig,\n };\n if (expiration) {\n if (typeof expiration === \"string\") {\n body[\"expires_at\"] = expiration;\n }\n else if (expiration?.hours || expiration?.minutes || expiration?.days) {\n body[\"expires_in\"] = expiration;\n }\n }\n else {\n body[\"expires_in\"] = {\n hours: 3,\n };\n }\n const serializedBody = JSON.stringify(body);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/feedback/tokens`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: serializedBody,\n });\n await raiseForStatus(res, \"create presigned feedback token\");\n return res;\n });\n return await response.json();\n }\n async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) {\n if (experimentIds.length === 0) {\n throw new Error(\"At least one experiment is required\");\n }\n if (!referenceDatasetId) {\n referenceDatasetId = (await this.readProject({\n projectId: experimentIds[0],\n })).reference_dataset_id;\n }\n if (!referenceDatasetId == null) {\n throw new Error(\"A reference dataset is required\");\n }\n const body = {\n id,\n name,\n experiment_ids: experimentIds,\n reference_dataset_id: referenceDatasetId,\n description,\n created_at: (createdAt ?? new Date())?.toISOString(),\n extra: {},\n };\n if (metadata)\n body.extra[\"metadata\"] = metadata;\n const serializedBody = JSON.stringify(body);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/datasets/comparative`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: serializedBody,\n });\n await raiseForStatus(res, \"create comparative experiment\");\n return res;\n });\n return response.json();\n }\n /**\n * Retrieves a list of presigned feedback tokens for a given run ID.\n * @param runId The ID of the run.\n * @returns An async iterable of FeedbackIngestToken objects.\n */\n async *listPresignedFeedbackTokens(runId) {\n assertUuid(runId);\n const params = new URLSearchParams({ run_id: runId });\n for await (const tokens of this._getPaginated(\"/feedback/tokens\", params)) {\n yield* tokens;\n }\n }\n _selectEvalResults(results) {\n let results_;\n if (\"results\" in results) {\n results_ = results.results;\n }\n else if (Array.isArray(results)) {\n results_ = results;\n }\n else {\n results_ = [results];\n }\n return results_;\n }\n async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {\n const evalResults = this._selectEvalResults(evaluatorResponse);\n const feedbacks = [];\n for (const res of evalResults) {\n let sourceInfo_ = sourceInfo || {};\n if (res.evaluatorInfo) {\n sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ };\n }\n let runId_ = null;\n if (res.targetRunId) {\n runId_ = res.targetRunId;\n }\n else if (run) {\n runId_ = run.id;\n }\n feedbacks.push(await this.createFeedback(runId_, res.key, {\n score: res.score,\n value: res.value,\n comment: res.comment,\n correction: res.correction,\n sourceInfo: sourceInfo_,\n sourceRunId: res.sourceRunId,\n feedbackConfig: res.feedbackConfig,\n feedbackSourceType: \"model\",\n }));\n }\n return [evalResults, feedbacks];\n }\n async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {\n const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo);\n return results;\n }\n /**\n * API for managing annotation queues\n */\n /**\n * List the annotation queues on the LangSmith API.\n * @param options - The options for listing annotation queues\n * @param options.queueIds - The IDs of the queues to filter by\n * @param options.name - The name of the queue to filter by\n * @param options.nameContains - The substring that the queue name should contain\n * @param options.limit - The maximum number of queues to return\n * @returns An iterator of AnnotationQueue objects\n */\n async *listAnnotationQueues(options = {}) {\n const { queueIds, name, nameContains, limit } = options;\n const params = new URLSearchParams();\n if (queueIds) {\n queueIds.forEach((id, i) => {\n assertUuid(id, `queueIds[${i}]`);\n params.append(\"ids\", id);\n });\n }\n if (name)\n params.append(\"name\", name);\n if (nameContains)\n params.append(\"name_contains\", nameContains);\n params.append(\"limit\", (limit !== undefined ? Math.min(limit, 100) : 100).toString());\n let count = 0;\n for await (const queues of this._getPaginated(\"/annotation-queues\", params)) {\n yield* queues;\n count++;\n if (limit !== undefined && count >= limit)\n break;\n }\n }\n /**\n * Create an annotation queue on the LangSmith API.\n * @param options - The options for creating an annotation queue\n * @param options.name - The name of the annotation queue\n * @param options.description - The description of the annotation queue\n * @param options.queueId - The ID of the annotation queue\n * @returns The created AnnotationQueue object\n */\n async createAnnotationQueue(options) {\n const { name, description, queueId, rubricInstructions } = options;\n const body = {\n name,\n description,\n id: queueId || uuid.v4(),\n rubric_instructions: rubricInstructions,\n };\n const serializedBody = JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined)));\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: serializedBody,\n });\n await raiseForStatus(res, \"create annotation queue\");\n return res;\n });\n return response.json();\n }\n /**\n * Read an annotation queue with the specified queue ID.\n * @param queueId - The ID of the annotation queue to read\n * @returns The AnnotationQueueWithDetails object\n */\n async readAnnotationQueue(queueId) {\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, \"queueId\")}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"read annotation queue\");\n return res;\n });\n return response.json();\n }\n /**\n * Update an annotation queue with the specified queue ID.\n * @param queueId - The ID of the annotation queue to update\n * @param options - The options for updating the annotation queue\n * @param options.name - The new name for the annotation queue\n * @param options.description - The new description for the annotation queue\n */\n async updateAnnotationQueue(queueId, options) {\n const { name, description, rubricInstructions } = options;\n const body = JSON.stringify({\n name,\n description,\n rubric_instructions: rubricInstructions,\n });\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, \"queueId\")}`, {\n method: \"PATCH\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update annotation queue\", true);\n return res;\n });\n }\n /**\n * Delete an annotation queue with the specified queue ID.\n * @param queueId - The ID of the annotation queue to delete\n */\n async deleteAnnotationQueue(queueId) {\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, \"queueId\")}`, {\n method: \"DELETE\",\n headers: { ...this.headers, Accept: \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"delete annotation queue\", true);\n return res;\n });\n }\n /**\n * Add runs to an annotation queue with the specified queue ID.\n * @param queueId - The ID of the annotation queue\n * @param runIds - The IDs of the runs to be added to the annotation queue\n */\n async addRunsToAnnotationQueue(queueId, runIds) {\n const body = JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString()));\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, \"queueId\")}/runs`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"add runs to annotation queue\", true);\n return res;\n });\n }\n /**\n * Get a run from an annotation queue at the specified index.\n * @param queueId - The ID of the annotation queue\n * @param index - The index of the run to retrieve\n * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object\n * @throws {Error} If the run is not found at the given index or for other API-related errors\n */\n async getRunFromAnnotationQueue(queueId, index) {\n const baseUrl = `/annotation-queues/${assertUuid(queueId, \"queueId\")}/run`;\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}${baseUrl}/${index}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"get run from annotation queue\");\n return res;\n });\n return response.json();\n }\n /**\n * Delete a run from an an annotation queue.\n * @param queueId - The ID of the annotation queue to delete the run from\n * @param queueRunId - The ID of the run to delete from the annotation queue\n */\n async deleteRunFromAnnotationQueue(queueId, queueRunId) {\n await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, \"queueId\")}/runs/${assertUuid(queueRunId, \"queueRunId\")}`, {\n method: \"DELETE\",\n headers: { ...this.headers, Accept: \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"delete run from annotation queue\", true);\n return res;\n });\n }\n /**\n * Get the size of an annotation queue.\n * @param queueId - The ID of the annotation queue\n */\n async getSizeFromAnnotationQueue(queueId) {\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, \"queueId\")}/size`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"get size from annotation queue\");\n return res;\n });\n return response.json();\n }\n async _currentTenantIsOwner(owner) {\n const settings = await this._getSettings();\n return owner == \"-\" || settings.tenant_handle === owner;\n }\n async _ownerConflictError(action, owner) {\n const settings = await this._getSettings();\n return new Error(`Cannot ${action} for another tenant.\\n\n Current tenant: ${settings.tenant_handle}\\n\n Requested tenant: ${owner}`);\n }\n async _getLatestCommitHash(promptOwnerAndName) {\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"get latest commit hash\");\n return res;\n });\n const json = await response.json();\n if (json.commits.length === 0) {\n return undefined;\n }\n return json.commits[0].commit_hash;\n }\n async _likeOrUnlikePrompt(promptIdentifier, like) {\n const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);\n const body = JSON.stringify({ like: like });\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/likes/${owner}/${promptName}`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, `${like ? \"like\" : \"unlike\"} prompt`);\n return res;\n });\n return response.json();\n }\n async _getPromptUrl(promptIdentifier) {\n const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier);\n if (!(await this._currentTenantIsOwner(owner))) {\n if (commitHash !== \"latest\") {\n return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`;\n }\n else {\n return `${this.getHostUrl()}/hub/${owner}/${promptName}`;\n }\n }\n else {\n const settings = await this._getSettings();\n if (commitHash !== \"latest\") {\n return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`;\n }\n else {\n return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`;\n }\n }\n }\n async promptExists(promptIdentifier) {\n const prompt = await this.getPrompt(promptIdentifier);\n return !!prompt;\n }\n async likePrompt(promptIdentifier) {\n return this._likeOrUnlikePrompt(promptIdentifier, true);\n }\n async unlikePrompt(promptIdentifier) {\n return this._likeOrUnlikePrompt(promptIdentifier, false);\n }\n async *listCommits(promptOwnerAndName) {\n for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) {\n yield* commits;\n }\n }\n async *listPrompts(options) {\n const params = new URLSearchParams();\n params.append(\"sort_field\", options?.sortField ?? \"updated_at\");\n params.append(\"sort_direction\", \"desc\");\n params.append(\"is_archived\", (!!options?.isArchived).toString());\n if (options?.isPublic !== undefined) {\n params.append(\"is_public\", options.isPublic.toString());\n }\n if (options?.query) {\n params.append(\"query\", options.query);\n }\n for await (const prompts of this._getPaginated(\"/repos\", params, (res) => res.repos)) {\n yield* prompts;\n }\n }\n async getPrompt(promptIdentifier) {\n const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (res?.status === 404) {\n return null;\n }\n await raiseForStatus(res, \"get prompt\");\n return res;\n });\n const result = await response?.json();\n if (result?.repo) {\n return result.repo;\n }\n else {\n return null;\n }\n }\n async createPrompt(promptIdentifier, options) {\n const settings = await this._getSettings();\n if (options?.isPublic && !settings.tenant_handle) {\n throw new Error(`Cannot create a public prompt without first\\n\n creating a LangChain Hub handle.\n You can add a handle by creating a public prompt at:\\n\n https://smith.langchain.com/prompts`);\n }\n const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);\n if (!(await this._currentTenantIsOwner(owner))) {\n throw await this._ownerConflictError(\"create a prompt\", owner);\n }\n const data = {\n repo_handle: promptName,\n ...(options?.description && { description: options.description }),\n ...(options?.readme && { readme: options.readme }),\n ...(options?.tags && { tags: options.tags }),\n is_public: !!options?.isPublic,\n };\n const body = JSON.stringify(data);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/repos/`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"create prompt\");\n return res;\n });\n const { repo } = await response.json();\n return repo;\n }\n async createCommit(promptIdentifier, object, options) {\n if (!(await this.promptExists(promptIdentifier))) {\n throw new Error(\"Prompt does not exist, you must create it first.\");\n }\n const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);\n const resolvedParentCommitHash = options?.parentCommitHash === \"latest\" || !options?.parentCommitHash\n ? await this._getLatestCommitHash(`${owner}/${promptName}`)\n : options?.parentCommitHash;\n const payload = {\n manifest: JSON.parse(JSON.stringify(object)),\n parent_commit: resolvedParentCommitHash,\n };\n const body = JSON.stringify(payload);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}`, {\n method: \"POST\",\n headers: { ...this.headers, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"create commit\");\n return res;\n });\n const result = await response.json();\n return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : \"\"}`);\n }\n /**\n * Update examples with attachments using multipart form data.\n * @param updates List of ExampleUpdateWithAttachments objects to upsert\n * @returns Promise with the update response\n */\n async updateExamplesMultipart(datasetId, updates = []) {\n return this._updateExamplesMultipart(datasetId, updates);\n }\n async _updateExamplesMultipart(datasetId, updates = []) {\n if (!(await this._getDatasetExamplesMultiPartSupport())) {\n throw new Error(\"Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.\");\n }\n const formData = new FormData();\n for (const example of updates) {\n const exampleId = example.id;\n // Prepare the main example body\n const exampleBody = {\n ...(example.metadata && { metadata: example.metadata }),\n ...(example.split && { split: example.split }),\n };\n // Add main example data\n const stringifiedExample = serializePayloadForTracing(exampleBody, `Serializing body for example with id: ${exampleId}`);\n const exampleBlob = new Blob([stringifiedExample], {\n type: \"application/json\",\n });\n formData.append(exampleId, exampleBlob);\n // Add inputs if present\n if (example.inputs) {\n const stringifiedInputs = serializePayloadForTracing(example.inputs, `Serializing inputs for example with id: ${exampleId}`);\n const inputsBlob = new Blob([stringifiedInputs], {\n type: \"application/json\",\n });\n formData.append(`${exampleId}.inputs`, inputsBlob);\n }\n // Add outputs if present\n if (example.outputs) {\n const stringifiedOutputs = serializePayloadForTracing(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`);\n const outputsBlob = new Blob([stringifiedOutputs], {\n type: \"application/json\",\n });\n formData.append(`${exampleId}.outputs`, outputsBlob);\n }\n // Add attachments if present\n if (example.attachments) {\n for (const [name, attachment] of Object.entries(example.attachments)) {\n let mimeType;\n let data;\n if (Array.isArray(attachment)) {\n [mimeType, data] = attachment;\n }\n else {\n mimeType = attachment.mimeType;\n data = attachment.data;\n }\n const attachmentBlob = new Blob([data], {\n type: `${mimeType}; length=${data.byteLength}`,\n });\n formData.append(`${exampleId}.attachment.${name}`, attachmentBlob);\n }\n }\n if (example.attachments_operations) {\n const stringifiedAttachmentsOperations = serializePayloadForTracing(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`);\n const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], {\n type: \"application/json\",\n });\n formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob);\n }\n }\n const datasetIdToUse = datasetId ?? updates[0]?.dataset_id;\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, {\n method: \"PATCH\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: formData,\n });\n await raiseForStatus(res, \"update examples\");\n return res;\n });\n return response.json();\n }\n /**\n * Upload examples with attachments using multipart form data.\n * @param uploads List of ExampleUploadWithAttachments objects to upload\n * @returns Promise with the upload response\n * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead\n */\n async uploadExamplesMultipart(datasetId, uploads = []) {\n return this._uploadExamplesMultipart(datasetId, uploads);\n }\n async _uploadExamplesMultipart(datasetId, uploads = []) {\n if (!(await this._getDatasetExamplesMultiPartSupport())) {\n throw new Error(\"Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.\");\n }\n const formData = new FormData();\n for (const example of uploads) {\n const exampleId = (example.id ?? uuid.v4()).toString();\n // Prepare the main example body\n const exampleBody = {\n created_at: example.created_at,\n ...(example.metadata && { metadata: example.metadata }),\n ...(example.split && { split: example.split }),\n ...(example.source_run_id && { source_run_id: example.source_run_id }),\n ...(example.use_source_run_io && {\n use_source_run_io: example.use_source_run_io,\n }),\n ...(example.use_source_run_attachments && {\n use_source_run_attachments: example.use_source_run_attachments,\n }),\n };\n // Add main example data\n const stringifiedExample = serializePayloadForTracing(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`);\n const exampleBlob = new Blob([stringifiedExample], {\n type: \"application/json\",\n });\n formData.append(exampleId, exampleBlob);\n // Add inputs if present\n if (example.inputs) {\n const stringifiedInputs = serializePayloadForTracing(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`);\n const inputsBlob = new Blob([stringifiedInputs], {\n type: \"application/json\",\n });\n formData.append(`${exampleId}.inputs`, inputsBlob);\n }\n // Add outputs if present\n if (example.outputs) {\n const stringifiedOutputs = serializePayloadForTracing(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`);\n const outputsBlob = new Blob([stringifiedOutputs], {\n type: \"application/json\",\n });\n formData.append(`${exampleId}.outputs`, outputsBlob);\n }\n // Add attachments if present\n if (example.attachments) {\n for (const [name, attachment] of Object.entries(example.attachments)) {\n let mimeType;\n let data;\n if (Array.isArray(attachment)) {\n [mimeType, data] = attachment;\n }\n else {\n mimeType = attachment.mimeType;\n data = attachment.data;\n }\n const attachmentBlob = new Blob([data], {\n type: `${mimeType}; length=${data.byteLength}`,\n });\n formData.append(`${exampleId}.attachment.${name}`, attachmentBlob);\n }\n }\n }\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, {\n method: \"POST\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: formData,\n });\n await raiseForStatus(res, \"upload examples\");\n return res;\n });\n return response.json();\n }\n async updatePrompt(promptIdentifier, options) {\n if (!(await this.promptExists(promptIdentifier))) {\n throw new Error(\"Prompt does not exist, you must create it first.\");\n }\n const [owner, promptName] = parsePromptIdentifier(promptIdentifier);\n if (!(await this._currentTenantIsOwner(owner))) {\n throw await this._ownerConflictError(\"update a prompt\", owner);\n }\n const payload = {};\n if (options?.description !== undefined)\n payload.description = options.description;\n if (options?.readme !== undefined)\n payload.readme = options.readme;\n if (options?.tags !== undefined)\n payload.tags = options.tags;\n if (options?.isPublic !== undefined)\n payload.is_public = options.isPublic;\n if (options?.isArchived !== undefined)\n payload.is_archived = options.isArchived;\n // Check if payload is empty\n if (Object.keys(payload).length === 0) {\n throw new Error(\"No valid update options provided\");\n }\n const body = JSON.stringify(payload);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, {\n method: \"PATCH\",\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body,\n });\n await raiseForStatus(res, \"update prompt\");\n return res;\n });\n return response.json();\n }\n async deletePrompt(promptIdentifier) {\n if (!(await this.promptExists(promptIdentifier))) {\n throw new Error(\"Prompt does not exist, you must create it first.\");\n }\n const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);\n if (!(await this._currentTenantIsOwner(owner))) {\n throw await this._ownerConflictError(\"delete a prompt\", owner);\n }\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, {\n method: \"DELETE\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"delete prompt\");\n return res;\n });\n return response.json();\n }\n async pullPromptCommit(promptIdentifier, options) {\n const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier);\n const response = await this.caller.call(async () => {\n const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? \"?include_model=true\" : \"\"}`, {\n method: \"GET\",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(res, \"pull prompt commit\");\n return res;\n });\n const result = await response.json();\n return {\n owner,\n repo: promptName,\n commit_hash: result.commit_hash,\n manifest: result.manifest,\n examples: result.examples,\n };\n }\n /**\n * This method should not be used directly, use `import { pull } from \"langchain/hub\"` instead.\n * Using this method directly returns the JSON string of the prompt rather than a LangChain object.\n * @private\n */\n async _pullPrompt(promptIdentifier, options) {\n const promptObject = await this.pullPromptCommit(promptIdentifier, {\n includeModel: options?.includeModel,\n });\n const prompt = JSON.stringify(promptObject.manifest);\n return prompt;\n }\n async pushPrompt(promptIdentifier, options) {\n // Create or update prompt metadata\n if (await this.promptExists(promptIdentifier)) {\n if (options && Object.keys(options).some((key) => key !== \"object\")) {\n await this.updatePrompt(promptIdentifier, {\n description: options?.description,\n readme: options?.readme,\n tags: options?.tags,\n isPublic: options?.isPublic,\n });\n }\n }\n else {\n await this.createPrompt(promptIdentifier, {\n description: options?.description,\n readme: options?.readme,\n tags: options?.tags,\n isPublic: options?.isPublic,\n });\n }\n if (!options?.object) {\n return await this._getPromptUrl(promptIdentifier);\n }\n // Create a commit with the new manifest\n const url = await this.createCommit(promptIdentifier, options?.object, {\n parentCommitHash: options?.parentCommitHash,\n });\n return url;\n }\n /**\n * Clone a public dataset to your own langsmith tenant.\n * This operation is idempotent. If you already have a dataset with the given name,\n * this function will do nothing.\n \n * @param {string} tokenOrUrl The token of the public dataset to clone.\n * @param {Object} [options] Additional options for cloning the dataset.\n * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client.\n * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset.\n * @returns {Promise}\n */\n async clonePublicDataset(tokenOrUrl, options = {}) {\n const { sourceApiUrl = this.apiUrl, datasetName } = options;\n const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl);\n const sourceClient = new Client({\n apiUrl: parsedApiUrl,\n // Placeholder API key not needed anymore in most cases, but\n // some private deployments may have API key-based rate limiting\n // that would cause this to fail if we provide no value.\n apiKey: \"placeholder\",\n });\n const ds = await sourceClient.readSharedDataset(tokenUuid);\n const finalDatasetName = datasetName || ds.name;\n try {\n if (await this.hasDataset({ datasetId: finalDatasetName })) {\n console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`);\n return;\n }\n }\n catch (_) {\n // `.hasDataset` will throw an error if the dataset does not exist.\n // no-op in that case\n }\n // Fetch examples first, then create the dataset\n const examples = await sourceClient.listSharedExamples(tokenUuid);\n const dataset = await this.createDataset(finalDatasetName, {\n description: ds.description,\n dataType: ds.data_type || \"kv\",\n inputsSchema: ds.inputs_schema_definition ?? undefined,\n outputsSchema: ds.outputs_schema_definition ?? undefined,\n });\n try {\n await this.createExamples({\n inputs: examples.map((e) => e.inputs),\n outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])),\n datasetId: dataset.id,\n });\n }\n catch (e) {\n console.error(`An error occurred while creating dataset ${finalDatasetName}. ` +\n \"You should delete it manually.\");\n throw e;\n }\n }\n parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = \"dataset\") {\n // Try parsing as UUID\n try {\n assertUuid(urlOrToken); // Will throw if it's not a UUID.\n return [apiUrl, urlOrToken];\n }\n catch (_) {\n // no-op if it's not a uuid\n }\n // Parse as URL\n try {\n const parsedUrl = new URL(urlOrToken);\n const pathParts = parsedUrl.pathname\n .split(\"/\")\n .filter((part) => part !== \"\");\n if (pathParts.length >= numParts) {\n const tokenUuid = pathParts[pathParts.length - numParts];\n return [apiUrl, tokenUuid];\n }\n else {\n throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`);\n }\n }\n catch (error) {\n throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`);\n }\n }\n /**\n * Awaits all pending trace batches. Useful for environments where\n * you need to be sure that all tracing requests finish before execution ends,\n * such as serverless environments.\n *\n * @example\n * ```\n * import { Client } from \"langsmith\";\n *\n * const client = new Client();\n *\n * try {\n * // Tracing happens here\n * ...\n * } finally {\n * await client.awaitPendingTraceBatches();\n * }\n * ```\n *\n * @returns A promise that resolves once all currently pending traces have sent.\n */\n async awaitPendingTraceBatches() {\n if (this.manualFlushMode) {\n console.warn(\"[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches.\");\n return Promise.resolve();\n }\n await Promise.all([\n ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise),\n this.batchIngestCaller.queue.onIdle(),\n ]);\n if (this.langSmithToOTELTranslator !== undefined) {\n await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush();\n }\n }\n}\nfunction isExampleCreate(input) {\n return \"dataset_id\" in input || \"dataset_name\" in input;\n}\n","import { getLangSmithEnvironmentVariable } from \"./utils/env.js\";\nexport const isTracingEnabled = (tracingEnabled) => {\n if (tracingEnabled !== undefined) {\n return tracingEnabled;\n }\n const envVars = [\"TRACING_V2\", \"TRACING\"];\n return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === \"true\");\n};\n","export const _LC_CONTEXT_VARIABLES_KEY = Symbol.for(\"lc:context_variables\");\n","import * as uuid from \"uuid\";\nimport { Client } from \"./client.js\";\nimport { isTracingEnabled } from \"./env.js\";\nimport { isConflictingEndpointsError, ConflictingEndpointsError, } from \"./utils/error.js\";\nimport { _LC_CONTEXT_VARIABLES_KEY } from \"./singletons/constants.js\";\nimport { getEnvironmentVariable, getRuntimeEnvironment, } from \"./utils/env.js\";\nimport { getDefaultProjectName } from \"./utils/project.js\";\nimport { getLangSmithEnvironmentVariable } from \"./utils/env.js\";\nimport { warnOnce } from \"./utils/warn.js\";\nfunction stripNonAlphanumeric(input) {\n return input.replace(/[-:.]/g, \"\");\n}\nexport function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) {\n // Date only has millisecond precision, so we use the microseconds to break\n // possible ties, avoiding incorrect run order\n const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, \"0\");\n const microsecondPrecisionDatestring = `${new Date(epoch)\n .toISOString()\n .slice(0, -1)}${paddedOrder}Z`;\n return {\n dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId,\n microsecondPrecisionDatestring,\n };\n}\n/**\n * Baggage header information\n */\nclass Baggage {\n constructor(metadata, tags, project_name, replicas) {\n Object.defineProperty(this, \"metadata\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"tags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"project_name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"replicas\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.metadata = metadata;\n this.tags = tags;\n this.project_name = project_name;\n this.replicas = replicas;\n }\n static fromHeader(value) {\n const items = value.split(\",\");\n let metadata = {};\n let tags = [];\n let project_name;\n let replicas;\n for (const item of items) {\n const [key, uriValue] = item.split(\"=\");\n const value = decodeURIComponent(uriValue);\n if (key === \"langsmith-metadata\") {\n metadata = JSON.parse(value);\n }\n else if (key === \"langsmith-tags\") {\n tags = value.split(\",\");\n }\n else if (key === \"langsmith-project\") {\n project_name = value;\n }\n else if (key === \"langsmith-replicas\") {\n replicas = JSON.parse(value);\n }\n }\n return new Baggage(metadata, tags, project_name, replicas);\n }\n toHeader() {\n const items = [];\n if (this.metadata && Object.keys(this.metadata).length > 0) {\n items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);\n }\n if (this.tags && this.tags.length > 0) {\n items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(\",\"))}`);\n }\n if (this.project_name) {\n items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`);\n }\n return items.join(\",\");\n }\n}\nexport class RunTree {\n constructor(originalConfig) {\n Object.defineProperty(this, \"id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"run_type\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"project_name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"parent_run\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"parent_run_id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"child_runs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"start_time\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"end_time\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"extra\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"tags\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"error\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"serialized\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"inputs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"reference_example_id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"client\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"events\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"trace_id\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"dotted_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"tracingEnabled\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"execution_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"child_execution_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /**\n * Attachments associated with the run.\n * Each entry is a tuple of [mime_type, bytes]\n */\n Object.defineProperty(this, \"attachments\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /**\n * Projects to replicate this run to with optional updates.\n */\n Object.defineProperty(this, \"replicas\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_serialized_start_time\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // If you pass in a run tree directly, return a shallow clone\n if (isRunTree(originalConfig)) {\n Object.assign(this, { ...originalConfig });\n return;\n }\n const defaultConfig = RunTree.getDefaultConfig();\n const { metadata, ...config } = originalConfig;\n const client = config.client ?? RunTree.getSharedClient();\n const dedupedMetadata = {\n ...metadata,\n ...config?.extra?.metadata,\n };\n config.extra = { ...config.extra, metadata: dedupedMetadata };\n if (\"id\" in config && config.id == null) {\n delete config.id;\n }\n Object.assign(this, { ...defaultConfig, ...config, client });\n if (!this.trace_id) {\n if (this.parent_run) {\n this.trace_id = this.parent_run.trace_id ?? this.id;\n }\n else {\n this.trace_id = this.id;\n }\n }\n this.replicas = _ensureWriteReplicas(this.replicas);\n this.execution_order ??= 1;\n this.child_execution_order ??= 1;\n if (!this.dotted_order) {\n const { dottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order);\n if (this.parent_run) {\n this.dotted_order = this.parent_run.dotted_order + \".\" + dottedOrder;\n }\n else {\n this.dotted_order = dottedOrder;\n }\n this._serialized_start_time = microsecondPrecisionDatestring;\n }\n }\n set metadata(metadata) {\n this.extra = {\n ...this.extra,\n metadata: {\n ...this.extra?.metadata,\n ...metadata,\n },\n };\n }\n get metadata() {\n return this.extra?.metadata;\n }\n static getDefaultConfig() {\n return {\n id: uuid.v4(),\n run_type: \"chain\",\n project_name: getDefaultProjectName(),\n child_runs: [],\n api_url: getEnvironmentVariable(\"LANGCHAIN_ENDPOINT\") ?? \"http://localhost:1984\",\n api_key: getEnvironmentVariable(\"LANGCHAIN_API_KEY\"),\n caller_options: {},\n start_time: Date.now(),\n serialized: {},\n inputs: {},\n extra: {},\n };\n }\n static getSharedClient() {\n if (!RunTree.sharedClient) {\n RunTree.sharedClient = new Client();\n }\n return RunTree.sharedClient;\n }\n createChild(config) {\n const child_execution_order = this.child_execution_order + 1;\n const child = new RunTree({\n ...config,\n parent_run: this,\n project_name: this.project_name,\n replicas: this.replicas,\n client: this.client,\n tracingEnabled: this.tracingEnabled,\n execution_order: child_execution_order,\n child_execution_order: child_execution_order,\n });\n // Copy context vars over into the new run tree.\n if (_LC_CONTEXT_VARIABLES_KEY in this) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n child[_LC_CONTEXT_VARIABLES_KEY] =\n this[_LC_CONTEXT_VARIABLES_KEY];\n }\n const LC_CHILD = Symbol.for(\"lc:child_config\");\n const presentConfig = config.extra?.[LC_CHILD] ??\n this.extra[LC_CHILD];\n // tracing for LangChain is defined by the _parentRunId and runMap of the tracer\n if (isRunnableConfigLike(presentConfig)) {\n const newConfig = { ...presentConfig };\n const callbacks = isCallbackManagerLike(newConfig.callbacks)\n ? newConfig.callbacks.copy?.()\n : undefined;\n if (callbacks) {\n // update the parent run id\n Object.assign(callbacks, { _parentRunId: child.id });\n // only populate if we're in a newer LC.JS version\n callbacks.handlers\n ?.find(isLangChainTracerLike)\n ?.updateFromRunTree?.(child);\n newConfig.callbacks = callbacks;\n }\n child.extra[LC_CHILD] = newConfig;\n }\n // propagate child_execution_order upwards\n const visited = new Set();\n let current = this;\n while (current != null && !visited.has(current.id)) {\n visited.add(current.id);\n current.child_execution_order = Math.max(current.child_execution_order, child_execution_order);\n current = current.parent_run;\n }\n this.child_runs.push(child);\n return child;\n }\n async end(outputs, error, endTime = Date.now(), metadata) {\n this.outputs = this.outputs ?? outputs;\n this.error = this.error ?? error;\n this.end_time = this.end_time ?? endTime;\n if (metadata && Object.keys(metadata).length > 0) {\n this.extra = this.extra\n ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } }\n : { metadata };\n }\n }\n _convertToCreate(run, runtimeEnv, excludeChildRuns = true) {\n const runExtra = run.extra ?? {};\n // Avoid overwriting the runtime environment if it's already set\n if (runExtra?.runtime?.library === undefined) {\n if (!runExtra.runtime) {\n runExtra.runtime = {};\n }\n if (runtimeEnv) {\n for (const [k, v] of Object.entries(runtimeEnv)) {\n if (!runExtra.runtime[k]) {\n runExtra.runtime[k] = v;\n }\n }\n }\n }\n let child_runs;\n let parent_run_id;\n if (!excludeChildRuns) {\n child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns));\n parent_run_id = undefined;\n }\n else {\n parent_run_id = run.parent_run?.id ?? run.parent_run_id;\n child_runs = [];\n }\n return {\n id: run.id,\n name: run.name,\n start_time: run._serialized_start_time ?? run.start_time,\n end_time: run.end_time,\n run_type: run.run_type,\n reference_example_id: run.reference_example_id,\n extra: runExtra,\n serialized: run.serialized,\n error: run.error,\n inputs: run.inputs,\n outputs: run.outputs,\n session_name: run.project_name,\n child_runs: child_runs,\n parent_run_id: parent_run_id,\n trace_id: run.trace_id,\n dotted_order: run.dotted_order,\n tags: run.tags,\n attachments: run.attachments,\n events: run.events,\n };\n }\n _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) {\n const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns);\n if (projectName === this.project_name) {\n return baseRun;\n }\n // Create a deterministic UUID mapping for this project\n const createRemappedId = (originalId) => {\n return uuid.v5(`${originalId}:${projectName}`, uuid.v5.DNS);\n };\n // Remap the current run's ID\n const newId = createRemappedId(baseRun.id);\n const newTraceId = baseRun.trace_id\n ? createRemappedId(baseRun.trace_id)\n : undefined;\n const newParentRunId = baseRun.parent_run_id\n ? createRemappedId(baseRun.parent_run_id)\n : undefined;\n let newDottedOrder;\n if (baseRun.dotted_order) {\n const segments = _parseDottedOrder(baseRun.dotted_order);\n const rebuilt = [];\n // Process all segments except the last one\n for (let i = 0; i < segments.length - 1; i++) {\n const [timestamp, segmentId] = segments[i];\n const remappedId = createRemappedId(segmentId);\n rebuilt.push(timestamp.toISOString().replace(/[-:]/g, \"\").replace(\".\", \"\") +\n remappedId);\n }\n // Process the last segment with the new run ID\n const [lastTimestamp] = segments[segments.length - 1];\n rebuilt.push(lastTimestamp.toISOString().replace(/[-:]/g, \"\").replace(\".\", \"\") +\n newId);\n newDottedOrder = rebuilt.join(\".\");\n }\n else {\n newDottedOrder = undefined;\n }\n const remappedRun = {\n ...baseRun,\n id: newId,\n trace_id: newTraceId,\n parent_run_id: newParentRunId,\n dotted_order: newDottedOrder,\n session_name: projectName,\n };\n return remappedRun;\n }\n async postRun(excludeChildRuns = true) {\n try {\n const runtimeEnv = getRuntimeEnvironment();\n if (this.replicas && this.replicas.length > 0) {\n for (const { projectName, apiKey, apiUrl, workspaceId } of this\n .replicas) {\n const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true);\n await this.client.createRun(runCreate, {\n apiKey,\n apiUrl,\n workspaceId,\n });\n }\n }\n else {\n const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns);\n await this.client.createRun(runCreate);\n }\n if (!excludeChildRuns) {\n warnOnce(\"Posting with excludeChildRuns=false is deprecated and will be removed in a future version.\");\n for (const childRun of this.child_runs) {\n await childRun.postRun(false);\n }\n }\n }\n catch (error) {\n console.error(`Error in postRun for run ${this.id}:`, error);\n }\n }\n async patchRun(options) {\n if (this.replicas && this.replicas.length > 0) {\n for (const { projectName, apiKey, apiUrl, workspaceId, updates } of this\n .replicas) {\n const runData = this._remapForProject(projectName ?? this.project_name);\n const updatePayload = {\n id: runData.id,\n outputs: runData.outputs,\n error: runData.error,\n parent_run_id: runData.parent_run_id,\n session_name: runData.session_name,\n reference_example_id: runData.reference_example_id,\n end_time: runData.end_time,\n dotted_order: runData.dotted_order,\n trace_id: runData.trace_id,\n events: runData.events,\n tags: runData.tags,\n extra: runData.extra,\n attachments: this.attachments,\n ...updates,\n };\n // Important that inputs is not a key in the run update\n // if excluded because it will overwrite the run create if the\n // two operations are merged during batching\n if (!options?.excludeInputs) {\n updatePayload.inputs = runData.inputs;\n }\n await this.client.updateRun(runData.id, updatePayload, {\n apiKey,\n apiUrl,\n workspaceId,\n });\n }\n }\n else {\n try {\n const runUpdate = {\n end_time: this.end_time,\n error: this.error,\n outputs: this.outputs,\n parent_run_id: this.parent_run?.id ?? this.parent_run_id,\n reference_example_id: this.reference_example_id,\n extra: this.extra,\n events: this.events,\n dotted_order: this.dotted_order,\n trace_id: this.trace_id,\n tags: this.tags,\n attachments: this.attachments,\n session_name: this.project_name,\n };\n // Important that inputs is not a key in the run update\n // if excluded because it will overwrite the run create if the\n // two operations are merged during batching\n if (!options?.excludeInputs) {\n runUpdate.inputs = this.inputs;\n }\n await this.client.updateRun(this.id, runUpdate);\n }\n catch (error) {\n console.error(`Error in patchRun for run ${this.id}`, error);\n }\n }\n }\n toJSON() {\n return this._convertToCreate(this, undefined, false);\n }\n /**\n * Add an event to the run tree.\n * @param event - A single event or string to add\n */\n addEvent(event) {\n if (!this.events) {\n this.events = [];\n }\n if (typeof event === \"string\") {\n this.events.push({\n name: \"event\",\n time: new Date().toISOString(),\n message: event,\n });\n }\n else {\n this.events.push({\n ...event,\n time: event.time ?? new Date().toISOString(),\n });\n }\n }\n static fromRunnableConfig(parentConfig, props) {\n // We only handle the callback manager case for now\n const callbackManager = parentConfig?.callbacks;\n let parentRun;\n let projectName;\n let client;\n let tracingEnabled = isTracingEnabled();\n if (callbackManager) {\n const parentRunId = callbackManager?.getParentRunId?.() ?? \"\";\n const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == \"langchain_tracer\");\n parentRun = langChainTracer?.getRun?.(parentRunId);\n projectName = langChainTracer?.projectName;\n client = langChainTracer?.client;\n tracingEnabled = tracingEnabled || !!langChainTracer;\n }\n if (!parentRun) {\n return new RunTree({\n ...props,\n client,\n tracingEnabled,\n project_name: projectName,\n });\n }\n const parentRunTree = new RunTree({\n name: parentRun.name,\n id: parentRun.id,\n trace_id: parentRun.trace_id,\n dotted_order: parentRun.dotted_order,\n client,\n tracingEnabled,\n project_name: projectName,\n tags: [\n ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])),\n ],\n extra: {\n metadata: {\n ...parentRun?.extra?.metadata,\n ...parentConfig?.metadata,\n },\n },\n });\n return parentRunTree.createChild(props);\n }\n static fromDottedOrder(dottedOrder) {\n return this.fromHeaders({ \"langsmith-trace\": dottedOrder });\n }\n static fromHeaders(headers, inheritArgs) {\n const rawHeaders = \"get\" in headers && typeof headers.get === \"function\"\n ? {\n \"langsmith-trace\": headers.get(\"langsmith-trace\"),\n baggage: headers.get(\"baggage\"),\n }\n : headers;\n const headerTrace = rawHeaders[\"langsmith-trace\"];\n if (!headerTrace || typeof headerTrace !== \"string\")\n return undefined;\n const parentDottedOrder = headerTrace.trim();\n const parsedDottedOrder = parentDottedOrder.split(\".\").map((part) => {\n const [strTime, uuid] = part.split(\"Z\");\n return { strTime, time: Date.parse(strTime + \"Z\"), uuid };\n });\n const traceId = parsedDottedOrder[0].uuid;\n const config = {\n ...inheritArgs,\n name: inheritArgs?.[\"name\"] ?? \"parent\",\n run_type: inheritArgs?.[\"run_type\"] ?? \"chain\",\n start_time: inheritArgs?.[\"start_time\"] ?? Date.now(),\n id: parsedDottedOrder.at(-1)?.uuid,\n trace_id: traceId,\n dotted_order: parentDottedOrder,\n };\n if (rawHeaders[\"baggage\"] && typeof rawHeaders[\"baggage\"] === \"string\") {\n const baggage = Baggage.fromHeader(rawHeaders[\"baggage\"]);\n config.metadata = baggage.metadata;\n config.tags = baggage.tags;\n config.project_name = baggage.project_name;\n config.replicas = baggage.replicas;\n }\n return new RunTree(config);\n }\n toHeaders(headers) {\n const result = {\n \"langsmith-trace\": this.dotted_order,\n baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader(),\n };\n if (headers) {\n for (const [key, value] of Object.entries(result)) {\n headers.set(key, value);\n }\n }\n return result;\n }\n}\nObject.defineProperty(RunTree, \"sharedClient\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: null\n});\nexport function isRunTree(x) {\n return (x != null &&\n typeof x.createChild === \"function\" &&\n typeof x.postRun === \"function\");\n}\nfunction isLangChainTracerLike(x) {\n return (typeof x === \"object\" &&\n x != null &&\n typeof x.name === \"string\" &&\n x.name === \"langchain_tracer\");\n}\nfunction containsLangChainTracerLike(x) {\n return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback)));\n}\nfunction isCallbackManagerLike(x) {\n return (typeof x === \"object\" &&\n x != null &&\n Array.isArray(x.handlers));\n}\nexport function isRunnableConfigLike(x) {\n // Check that it's an object with a callbacks arg\n // that has either a CallbackManagerLike object with a langchain tracer within it\n // or an array with a LangChainTracerLike object within it\n return (x != null &&\n typeof x.callbacks === \"object\" &&\n // Callback manager with a langchain tracer\n (containsLangChainTracerLike(x.callbacks?.handlers) ||\n // Or it's an array with a LangChainTracerLike object within it\n containsLangChainTracerLike(x.callbacks)));\n}\nfunction _parseDottedOrder(dottedOrder) {\n const parts = dottedOrder.split(\".\");\n return parts.map((part) => {\n const timestampStr = part.slice(0, -36);\n const uuidStr = part.slice(-36);\n // Parse timestamp: \"%Y%m%dT%H%M%S%fZ\" format\n // Example: \"20231215T143045123456Z\"\n const year = parseInt(timestampStr.slice(0, 4));\n const month = parseInt(timestampStr.slice(4, 6)) - 1; // JS months are 0-indexed\n const day = parseInt(timestampStr.slice(6, 8));\n const hour = parseInt(timestampStr.slice(9, 11));\n const minute = parseInt(timestampStr.slice(11, 13));\n const second = parseInt(timestampStr.slice(13, 15));\n const microsecond = parseInt(timestampStr.slice(15, 21));\n const timestamp = new Date(year, month, day, hour, minute, second, microsecond / 1000);\n return [timestamp, uuidStr];\n });\n}\nfunction _getWriteReplicasFromEnv() {\n const envVar = getEnvironmentVariable(\"LANGSMITH_RUNS_ENDPOINTS\");\n if (!envVar)\n return [];\n try {\n const parsed = JSON.parse(envVar);\n if (Array.isArray(parsed)) {\n const replicas = [];\n for (const item of parsed) {\n if (typeof item !== \"object\" || item === null) {\n console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: ` +\n `expected object, got ${typeof item}`);\n continue;\n }\n if (typeof item.api_url !== \"string\") {\n console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: ` +\n `expected string, got ${typeof item.api_url}`);\n continue;\n }\n if (typeof item.api_key !== \"string\") {\n console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: ` +\n `expected string, got ${typeof item.api_key}`);\n continue;\n }\n replicas.push({\n apiUrl: item.api_url.replace(/\\/$/, \"\"),\n apiKey: item.api_key,\n });\n }\n return replicas;\n }\n else if (typeof parsed === \"object\" && parsed !== null) {\n _checkEndpointEnvUnset(parsed);\n const replicas = [];\n for (const [url, key] of Object.entries(parsed)) {\n const cleanUrl = url.replace(/\\/$/, \"\");\n if (typeof key === \"string\") {\n replicas.push({\n apiUrl: cleanUrl,\n apiKey: key,\n });\n }\n else {\n console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: ` +\n `expected string, got ${typeof key}`);\n continue;\n }\n }\n return replicas;\n }\n else {\n console.warn(\"Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of \" +\n `objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`);\n return [];\n }\n }\n catch (e) {\n if (isConflictingEndpointsError(e)) {\n throw e;\n }\n console.warn(\"Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of \" +\n \"objects with api_url and api_key properties, or object mapping url->apiKey\");\n return [];\n }\n}\nfunction _ensureWriteReplicas(replicas) {\n // If null -> fetch from env\n if (replicas) {\n return replicas.map((replica) => {\n if (Array.isArray(replica)) {\n return {\n projectName: replica[0],\n updates: replica[1],\n };\n }\n return replica;\n });\n }\n return _getWriteReplicasFromEnv();\n}\nfunction _checkEndpointEnvUnset(parsed) {\n if (Object.keys(parsed).length > 0 &&\n getLangSmithEnvironmentVariable(\"ENDPOINT\")) {\n throw new ConflictingEndpointsError();\n }\n}\n","export * from './dist/run_trees.js'","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { getRuntimeEnvironment } from \"../utils/env.js\";\nimport { BaseCallbackHandler } from \"../callbacks/base.js\";\nimport { RunTree, convertToDottedOrderFormat } from \"langsmith/run_trees\";\n\n//#region src/tracers/base.ts\nvar base_exports = {};\n__export(base_exports, {\n\tBaseTracer: () => BaseTracer,\n\tisBaseTracer: () => isBaseTracer\n});\nconst convertRunTreeToRun = (runTree) => {\n\tif (!runTree) return void 0;\n\trunTree.events = runTree.events ?? [];\n\trunTree.child_runs = runTree.child_runs ?? [];\n\treturn runTree;\n};\nfunction convertRunToRunTree(run, parentRun) {\n\tif (!run) return void 0;\n\treturn new RunTree({\n\t\t...run,\n\t\tstart_time: run._serialized_start_time ?? run.start_time,\n\t\tparent_run: convertRunToRunTree(parentRun),\n\t\tchild_runs: run.child_runs.map((r) => convertRunToRunTree(r)).filter((r) => r !== void 0),\n\t\textra: {\n\t\t\t...run.extra,\n\t\t\truntime: getRuntimeEnvironment()\n\t\t},\n\t\ttracingEnabled: false\n\t});\n}\nfunction _coerceToDict(value, defaultKey) {\n\treturn value && !Array.isArray(value) && typeof value === \"object\" ? value : { [defaultKey]: value };\n}\nfunction isBaseTracer(x) {\n\treturn typeof x._addRunToRunMap === \"function\";\n}\nvar BaseTracer = class extends BaseCallbackHandler {\n\t/** @deprecated Use `runTreeMap` instead. */\n\trunMap = /* @__PURE__ */ new Map();\n\trunTreeMap = /* @__PURE__ */ new Map();\n\tusesRunTreeMap = false;\n\tconstructor(_fields) {\n\t\tsuper(...arguments);\n\t}\n\tcopy() {\n\t\treturn this;\n\t}\n\tgetRunById(runId) {\n\t\tif (runId === void 0) return void 0;\n\t\treturn this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId);\n\t}\n\tstringifyError(error) {\n\t\tif (error instanceof Error) return error.message + (error?.stack ? `\\n\\n${error.stack}` : \"\");\n\t\tif (typeof error === \"string\") return error;\n\t\treturn `${error}`;\n\t}\n\t_addChildRun(parentRun, childRun) {\n\t\tparentRun.child_runs.push(childRun);\n\t}\n\t_addRunToRunMap(run) {\n\t\tconst { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order);\n\t\tconst storedRun = { ...run };\n\t\tconst parentRun = this.getRunById(storedRun.parent_run_id);\n\t\tif (storedRun.parent_run_id !== void 0) {\n\t\t\tif (parentRun) {\n\t\t\t\tthis._addChildRun(parentRun, storedRun);\n\t\t\t\tparentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);\n\t\t\t\tstoredRun.trace_id = parentRun.trace_id;\n\t\t\t\tif (parentRun.dotted_order !== void 0) {\n\t\t\t\t\tstoredRun.dotted_order = [parentRun.dotted_order, currentDottedOrder].join(\".\");\n\t\t\t\t\tstoredRun._serialized_start_time = microsecondPrecisionDatestring;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tstoredRun.trace_id = storedRun.id;\n\t\t\tstoredRun.dotted_order = currentDottedOrder;\n\t\t\tstoredRun._serialized_start_time = microsecondPrecisionDatestring;\n\t\t}\n\t\tif (this.usesRunTreeMap) {\n\t\t\tconst runTree = convertRunToRunTree(storedRun, parentRun);\n\t\t\tif (runTree !== void 0) this.runTreeMap.set(storedRun.id, runTree);\n\t\t} else this.runMap.set(storedRun.id, storedRun);\n\t\treturn storedRun;\n\t}\n\tasync _endTrace(run) {\n\t\tconst parentRun = run.parent_run_id !== void 0 && this.getRunById(run.parent_run_id);\n\t\tif (parentRun) parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order);\n\t\telse await this.persistRun(run);\n\t\tawait this.onRunUpdate?.(run);\n\t\tif (this.usesRunTreeMap) this.runTreeMap.delete(run.id);\n\t\telse this.runMap.delete(run.id);\n\t}\n\t_getExecutionOrder(parentRunId) {\n\t\tconst parentRun = parentRunId !== void 0 && this.getRunById(parentRunId);\n\t\tif (!parentRun) return 1;\n\t\treturn parentRun.child_execution_order + 1;\n\t}\n\t/**\n\t* Create and add a run to the run map for LLM start events.\n\t* This must sometimes be done synchronously to avoid race conditions\n\t* when callbacks are backgrounded, so we expose it as a separate method here.\n\t*/\n\t_createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {\n\t\tconst execution_order = this._getExecutionOrder(parentRunId);\n\t\tconst start_time = Date.now();\n\t\tconst finalExtraParams = metadata ? {\n\t\t\t...extraParams,\n\t\t\tmetadata\n\t\t} : extraParams;\n\t\tconst run = {\n\t\t\tid: runId,\n\t\t\tname: name ?? llm.id[llm.id.length - 1],\n\t\t\tparent_run_id: parentRunId,\n\t\t\tstart_time,\n\t\t\tserialized: llm,\n\t\t\tevents: [{\n\t\t\t\tname: \"start\",\n\t\t\t\ttime: new Date(start_time).toISOString()\n\t\t\t}],\n\t\t\tinputs: { prompts },\n\t\t\texecution_order,\n\t\t\tchild_runs: [],\n\t\t\tchild_execution_order: execution_order,\n\t\t\trun_type: \"llm\",\n\t\t\textra: finalExtraParams ?? {},\n\t\t\ttags: tags || []\n\t\t};\n\t\treturn this._addRunToRunMap(run);\n\t}\n\tasync handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {\n\t\tconst run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name);\n\t\tawait this.onRunCreate?.(run);\n\t\tawait this.onLLMStart?.(run);\n\t\treturn run;\n\t}\n\t/**\n\t* Create and add a run to the run map for chat model start events.\n\t* This must sometimes be done synchronously to avoid race conditions\n\t* when callbacks are backgrounded, so we expose it as a separate method here.\n\t*/\n\t_createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {\n\t\tconst execution_order = this._getExecutionOrder(parentRunId);\n\t\tconst start_time = Date.now();\n\t\tconst finalExtraParams = metadata ? {\n\t\t\t...extraParams,\n\t\t\tmetadata\n\t\t} : extraParams;\n\t\tconst run = {\n\t\t\tid: runId,\n\t\t\tname: name ?? llm.id[llm.id.length - 1],\n\t\t\tparent_run_id: parentRunId,\n\t\t\tstart_time,\n\t\t\tserialized: llm,\n\t\t\tevents: [{\n\t\t\t\tname: \"start\",\n\t\t\t\ttime: new Date(start_time).toISOString()\n\t\t\t}],\n\t\t\tinputs: { messages },\n\t\t\texecution_order,\n\t\t\tchild_runs: [],\n\t\t\tchild_execution_order: execution_order,\n\t\t\trun_type: \"llm\",\n\t\t\textra: finalExtraParams ?? {},\n\t\t\ttags: tags || []\n\t\t};\n\t\treturn this._addRunToRunMap(run);\n\t}\n\tasync handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {\n\t\tconst run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name);\n\t\tawait this.onRunCreate?.(run);\n\t\tawait this.onLLMStart?.(run);\n\t\treturn run;\n\t}\n\tasync handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"llm\") throw new Error(\"No LLM run to end.\");\n\t\trun.end_time = Date.now();\n\t\trun.outputs = output;\n\t\trun.events.push({\n\t\t\tname: \"end\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\trun.extra = {\n\t\t\t...run.extra,\n\t\t\t...extraParams\n\t\t};\n\t\tawait this.onLLMEnd?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\tasync handleLLMError(error, runId, _parentRunId, _tags, extraParams) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"llm\") throw new Error(\"No LLM run to end.\");\n\t\trun.end_time = Date.now();\n\t\trun.error = this.stringifyError(error);\n\t\trun.events.push({\n\t\t\tname: \"error\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\trun.extra = {\n\t\t\t...run.extra,\n\t\t\t...extraParams\n\t\t};\n\t\tawait this.onLLMError?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\t/**\n\t* Create and add a run to the run map for chain start events.\n\t* This must sometimes be done synchronously to avoid race conditions\n\t* when callbacks are backgrounded, so we expose it as a separate method here.\n\t*/\n\t_createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {\n\t\tconst execution_order = this._getExecutionOrder(parentRunId);\n\t\tconst start_time = Date.now();\n\t\tconst run = {\n\t\t\tid: runId,\n\t\t\tname: name ?? chain.id[chain.id.length - 1],\n\t\t\tparent_run_id: parentRunId,\n\t\t\tstart_time,\n\t\t\tserialized: chain,\n\t\t\tevents: [{\n\t\t\t\tname: \"start\",\n\t\t\t\ttime: new Date(start_time).toISOString()\n\t\t\t}],\n\t\t\tinputs,\n\t\t\texecution_order,\n\t\t\tchild_execution_order: execution_order,\n\t\t\trun_type: runType ?? \"chain\",\n\t\t\tchild_runs: [],\n\t\t\textra: metadata ? { metadata } : {},\n\t\t\ttags: tags || []\n\t\t};\n\t\treturn this._addRunToRunMap(run);\n\t}\n\tasync handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {\n\t\tconst run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name);\n\t\tawait this.onRunCreate?.(run);\n\t\tawait this.onChainStart?.(run);\n\t\treturn run;\n\t}\n\tasync handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run) throw new Error(\"No chain run to end.\");\n\t\trun.end_time = Date.now();\n\t\trun.outputs = _coerceToDict(outputs, \"output\");\n\t\trun.events.push({\n\t\t\tname: \"end\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\tif (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, \"input\");\n\t\tawait this.onChainEnd?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\tasync handleChainError(error, runId, _parentRunId, _tags, kwargs) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run) throw new Error(\"No chain run to end.\");\n\t\trun.end_time = Date.now();\n\t\trun.error = this.stringifyError(error);\n\t\trun.events.push({\n\t\t\tname: \"error\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\tif (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, \"input\");\n\t\tawait this.onChainError?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\t/**\n\t* Create and add a run to the run map for tool start events.\n\t* This must sometimes be done synchronously to avoid race conditions\n\t* when callbacks are backgrounded, so we expose it as a separate method here.\n\t*/\n\t_createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) {\n\t\tconst execution_order = this._getExecutionOrder(parentRunId);\n\t\tconst start_time = Date.now();\n\t\tconst run = {\n\t\t\tid: runId,\n\t\t\tname: name ?? tool.id[tool.id.length - 1],\n\t\t\tparent_run_id: parentRunId,\n\t\t\tstart_time,\n\t\t\tserialized: tool,\n\t\t\tevents: [{\n\t\t\t\tname: \"start\",\n\t\t\t\ttime: new Date(start_time).toISOString()\n\t\t\t}],\n\t\t\tinputs: { input },\n\t\t\texecution_order,\n\t\t\tchild_execution_order: execution_order,\n\t\t\trun_type: \"tool\",\n\t\t\tchild_runs: [],\n\t\t\textra: metadata ? { metadata } : {},\n\t\t\ttags: tags || []\n\t\t};\n\t\treturn this._addRunToRunMap(run);\n\t}\n\tasync handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) {\n\t\tconst run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name);\n\t\tawait this.onRunCreate?.(run);\n\t\tawait this.onToolStart?.(run);\n\t\treturn run;\n\t}\n\tasync handleToolEnd(output, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"tool\") throw new Error(\"No tool run to end\");\n\t\trun.end_time = Date.now();\n\t\trun.outputs = { output };\n\t\trun.events.push({\n\t\t\tname: \"end\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\tawait this.onToolEnd?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\tasync handleToolError(error, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"tool\") throw new Error(\"No tool run to end\");\n\t\trun.end_time = Date.now();\n\t\trun.error = this.stringifyError(error);\n\t\trun.events.push({\n\t\t\tname: \"error\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\tawait this.onToolError?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\tasync handleAgentAction(action, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"chain\") return;\n\t\tconst agentRun = run;\n\t\tagentRun.actions = agentRun.actions || [];\n\t\tagentRun.actions.push(action);\n\t\tagentRun.events.push({\n\t\t\tname: \"agent_action\",\n\t\t\ttime: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tkwargs: { action }\n\t\t});\n\t\tawait this.onAgentAction?.(run);\n\t}\n\tasync handleAgentEnd(action, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"chain\") return;\n\t\trun.events.push({\n\t\t\tname: \"agent_end\",\n\t\t\ttime: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tkwargs: { action }\n\t\t});\n\t\tawait this.onAgentEnd?.(run);\n\t}\n\t/**\n\t* Create and add a run to the run map for retriever start events.\n\t* This must sometimes be done synchronously to avoid race conditions\n\t* when callbacks are backgrounded, so we expose it as a separate method here.\n\t*/\n\t_createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {\n\t\tconst execution_order = this._getExecutionOrder(parentRunId);\n\t\tconst start_time = Date.now();\n\t\tconst run = {\n\t\t\tid: runId,\n\t\t\tname: name ?? retriever.id[retriever.id.length - 1],\n\t\t\tparent_run_id: parentRunId,\n\t\t\tstart_time,\n\t\t\tserialized: retriever,\n\t\t\tevents: [{\n\t\t\t\tname: \"start\",\n\t\t\t\ttime: new Date(start_time).toISOString()\n\t\t\t}],\n\t\t\tinputs: { query },\n\t\t\texecution_order,\n\t\t\tchild_execution_order: execution_order,\n\t\t\trun_type: \"retriever\",\n\t\t\tchild_runs: [],\n\t\t\textra: metadata ? { metadata } : {},\n\t\t\ttags: tags || []\n\t\t};\n\t\treturn this._addRunToRunMap(run);\n\t}\n\tasync handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {\n\t\tconst run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name);\n\t\tawait this.onRunCreate?.(run);\n\t\tawait this.onRetrieverStart?.(run);\n\t\treturn run;\n\t}\n\tasync handleRetrieverEnd(documents, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"retriever\") throw new Error(\"No retriever run to end\");\n\t\trun.end_time = Date.now();\n\t\trun.outputs = { documents };\n\t\trun.events.push({\n\t\t\tname: \"end\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\tawait this.onRetrieverEnd?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\tasync handleRetrieverError(error, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"retriever\") throw new Error(\"No retriever run to end\");\n\t\trun.end_time = Date.now();\n\t\trun.error = this.stringifyError(error);\n\t\trun.events.push({\n\t\t\tname: \"error\",\n\t\t\ttime: new Date(run.end_time).toISOString()\n\t\t});\n\t\tawait this.onRetrieverError?.(run);\n\t\tawait this._endTrace(run);\n\t\treturn run;\n\t}\n\tasync handleText(text, runId) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"chain\") return;\n\t\trun.events.push({\n\t\t\tname: \"text\",\n\t\t\ttime: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tkwargs: { text }\n\t\t});\n\t\tawait this.onText?.(run);\n\t}\n\tasync handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) {\n\t\tconst run = this.getRunById(runId);\n\t\tif (!run || run?.run_type !== \"llm\") throw new Error(`Invalid \"runId\" provided to \"handleLLMNewToken\" callback.`);\n\t\trun.events.push({\n\t\t\tname: \"new_token\",\n\t\t\ttime: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tkwargs: {\n\t\t\t\ttoken,\n\t\t\t\tidx,\n\t\t\t\tchunk: fields?.chunk\n\t\t\t}\n\t\t});\n\t\tawait this.onLLMNewToken?.(run, token, { chunk: fields?.chunk });\n\t\treturn run;\n\t}\n};\n\n//#endregion\nexport { BaseTracer, base_exports, isBaseTracer };\n//# sourceMappingURL=base.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BaseTracer } from \"./base.js\";\nimport styles from \"ansi-styles\";\n\n//#region src/tracers/console.ts\nvar console_exports = {};\n__export(console_exports, { ConsoleCallbackHandler: () => ConsoleCallbackHandler });\nfunction wrap(style, text) {\n\treturn `${style.open}${text}${style.close}`;\n}\nfunction tryJsonStringify(obj, fallback) {\n\ttry {\n\t\treturn JSON.stringify(obj, null, 2);\n\t} catch {\n\t\treturn fallback;\n\t}\n}\nfunction formatKVMapItem(value) {\n\tif (typeof value === \"string\") return value.trim();\n\tif (value === null || value === void 0) return value;\n\treturn tryJsonStringify(value, value.toString());\n}\nfunction elapsed(run) {\n\tif (!run.end_time) return \"\";\n\tconst elapsed$1 = run.end_time - run.start_time;\n\tif (elapsed$1 < 1e3) return `${elapsed$1}ms`;\n\treturn `${(elapsed$1 / 1e3).toFixed(2)}s`;\n}\nconst { color } = styles;\n/**\n* A tracer that logs all events to the console. It extends from the\n* `BaseTracer` class and overrides its methods to provide custom logging\n* functionality.\n* @example\n* ```typescript\n*\n* const llm = new ChatAnthropic({\n* temperature: 0,\n* tags: [\"example\", \"callbacks\", \"constructor\"],\n* callbacks: [new ConsoleCallbackHandler()],\n* });\n*\n* ```\n*/\nvar ConsoleCallbackHandler = class extends BaseTracer {\n\tname = \"console_callback_handler\";\n\t/**\n\t* Method used to persist the run. In this case, it simply returns a\n\t* resolved promise as there's no persistence logic.\n\t* @param _run The run to persist.\n\t* @returns A resolved promise.\n\t*/\n\tpersistRun(_run) {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Method used to get all the parent runs of a given run.\n\t* @param run The run whose parents are to be retrieved.\n\t* @returns An array of parent runs.\n\t*/\n\tgetParents(run) {\n\t\tconst parents = [];\n\t\tlet currentRun = run;\n\t\twhile (currentRun.parent_run_id) {\n\t\t\tconst parent = this.runMap.get(currentRun.parent_run_id);\n\t\t\tif (parent) {\n\t\t\t\tparents.push(parent);\n\t\t\t\tcurrentRun = parent;\n\t\t\t} else break;\n\t\t}\n\t\treturn parents;\n\t}\n\t/**\n\t* Method used to get a string representation of the run's lineage, which\n\t* is used in logging.\n\t* @param run The run whose lineage is to be retrieved.\n\t* @returns A string representation of the run's lineage.\n\t*/\n\tgetBreadcrumbs(run) {\n\t\tconst parents = this.getParents(run).reverse();\n\t\tconst string = [...parents, run].map((parent, i, arr) => {\n\t\t\tconst name = `${parent.execution_order}:${parent.run_type}:${parent.name}`;\n\t\t\treturn i === arr.length - 1 ? wrap(styles.bold, name) : name;\n\t\t}).join(\" > \");\n\t\treturn wrap(color.grey, string);\n\t}\n\t/**\n\t* Method used to log the start of a chain run.\n\t* @param run The chain run that has started.\n\t* @returns void\n\t*/\n\tonChainStart(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.green, \"[chain/start]\")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, \"[inputs]\")}`);\n\t}\n\t/**\n\t* Method used to log the end of a chain run.\n\t* @param run The chain run that has ended.\n\t* @returns void\n\t*/\n\tonChainEnd(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.cyan, \"[chain/end]\")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, \"[outputs]\")}`);\n\t}\n\t/**\n\t* Method used to log any errors of a chain run.\n\t* @param run The chain run that has errored.\n\t* @returns void\n\t*/\n\tonChainError(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.red, \"[chain/error]\")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, \"[error]\")}`);\n\t}\n\t/**\n\t* Method used to log the start of an LLM run.\n\t* @param run The LLM run that has started.\n\t* @returns void\n\t*/\n\tonLLMStart(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconst inputs = \"prompts\" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs;\n\t\tconsole.log(`${wrap(color.green, \"[llm/start]\")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, \"[inputs]\")}`);\n\t}\n\t/**\n\t* Method used to log the end of an LLM run.\n\t* @param run The LLM run that has ended.\n\t* @returns void\n\t*/\n\tonLLMEnd(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.cyan, \"[llm/end]\")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, \"[response]\")}`);\n\t}\n\t/**\n\t* Method used to log any errors of an LLM run.\n\t* @param run The LLM run that has errored.\n\t* @returns void\n\t*/\n\tonLLMError(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.red, \"[llm/error]\")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, \"[error]\")}`);\n\t}\n\t/**\n\t* Method used to log the start of a tool run.\n\t* @param run The tool run that has started.\n\t* @returns void\n\t*/\n\tonToolStart(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.green, \"[tool/start]\")} [${crumbs}] Entering Tool run with input: \"${formatKVMapItem(run.inputs.input)}\"`);\n\t}\n\t/**\n\t* Method used to log the end of a tool run.\n\t* @param run The tool run that has ended.\n\t* @returns void\n\t*/\n\tonToolEnd(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.cyan, \"[tool/end]\")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: \"${formatKVMapItem(run.outputs?.output)}\"`);\n\t}\n\t/**\n\t* Method used to log any errors of a tool run.\n\t* @param run The tool run that has errored.\n\t* @returns void\n\t*/\n\tonToolError(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.red, \"[tool/error]\")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, \"[error]\")}`);\n\t}\n\t/**\n\t* Method used to log the start of a retriever run.\n\t* @param run The retriever run that has started.\n\t* @returns void\n\t*/\n\tonRetrieverStart(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.green, \"[retriever/start]\")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, \"[inputs]\")}`);\n\t}\n\t/**\n\t* Method used to log the end of a retriever run.\n\t* @param run The retriever run that has ended.\n\t* @returns void\n\t*/\n\tonRetrieverEnd(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.cyan, \"[retriever/end]\")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, \"[outputs]\")}`);\n\t}\n\t/**\n\t* Method used to log any errors of a retriever run.\n\t* @param run The retriever run that has errored.\n\t* @returns void\n\t*/\n\tonRetrieverError(run) {\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.red, \"[retriever/error]\")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, \"[error]\")}`);\n\t}\n\t/**\n\t* Method used to log the action selected by the agent.\n\t* @param run The run in which the agent action occurred.\n\t* @returns void\n\t*/\n\tonAgentAction(run) {\n\t\tconst agentRun = run;\n\t\tconst crumbs = this.getBreadcrumbs(run);\n\t\tconsole.log(`${wrap(color.blue, \"[agent/action]\")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], \"[action]\")}`);\n\t}\n};\n\n//#endregion\nexport { ConsoleCallbackHandler, console_exports };\n//# sourceMappingURL=console.js.map","export * from './dist/index.js'","import { getEnvironmentVariable } from \"../utils/env.js\";\nimport { Client } from \"langsmith\";\n\n//#region src/singletons/tracer.ts\nlet client;\nconst getDefaultLangChainClientSingleton = () => {\n\tif (client === void 0) {\n\t\tconst clientParams = getEnvironmentVariable(\"LANGCHAIN_CALLBACKS_BACKGROUND\") === \"false\" ? { blockOnRootRunFinalization: true } : {};\n\t\tclient = new Client(clientParams);\n\t}\n\treturn client;\n};\n\n//#endregion\nexport { getDefaultLangChainClientSingleton };\n//# sourceMappingURL=tracer.js.map","class MockAsyncLocalStorage {\n getStore() {\n return undefined;\n }\n run(_, callback) {\n return callback();\n }\n}\nconst TRACING_ALS_KEY = Symbol.for(\"ls:tracing_async_local_storage\");\nconst mockAsyncLocalStorage = new MockAsyncLocalStorage();\nclass AsyncLocalStorageProvider {\n getInstance() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage;\n }\n initializeGlobalInstance(instance) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (globalThis[TRACING_ALS_KEY] === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n globalThis[TRACING_ALS_KEY] = instance;\n }\n }\n}\nexport const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();\nexport function getCurrentRunTree(permitAbsentRunTree = false) {\n const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore();\n if (!permitAbsentRunTree && runTree === undefined) {\n throw new Error(\"Could not get the current run tree.\\n\\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.\");\n }\n return runTree;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withRunTree(runTree, fn) {\n const storage = AsyncLocalStorageProviderSingleton.getInstance();\n return new Promise((resolve, reject) => {\n storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject));\n });\n}\nexport const ROOT = Symbol.for(\"langsmith:traceable:root\");\nexport function isTraceableFunction(x\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n return typeof x === \"function\" && \"langsmith:traceable\" in x;\n}\n","export * from '../dist/singletons/traceable.js'","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BaseTracer } from \"./base.js\";\nimport { getDefaultLangChainClientSingleton } from \"../singletons/tracer.js\";\nimport { getCurrentRunTree } from \"langsmith/singletons/traceable\";\nimport { RunTree } from \"langsmith/run_trees\";\nimport { getDefaultProjectName } from \"langsmith\";\n\n//#region src/tracers/tracer_langchain.ts\nvar tracer_langchain_exports = {};\n__export(tracer_langchain_exports, { LangChainTracer: () => LangChainTracer });\nvar LangChainTracer = class LangChainTracer extends BaseTracer {\n\tname = \"langchain_tracer\";\n\tprojectName;\n\texampleId;\n\tclient;\n\treplicas;\n\tusesRunTreeMap = true;\n\tconstructor(fields = {}) {\n\t\tsuper(fields);\n\t\tconst { exampleId, projectName, client, replicas } = fields;\n\t\tthis.projectName = projectName ?? getDefaultProjectName();\n\t\tthis.replicas = replicas;\n\t\tthis.exampleId = exampleId;\n\t\tthis.client = client ?? getDefaultLangChainClientSingleton();\n\t\tconst traceableTree = LangChainTracer.getTraceableRunTree();\n\t\tif (traceableTree) this.updateFromRunTree(traceableTree);\n\t}\n\tasync persistRun(_run) {}\n\tasync onRunCreate(run) {\n\t\tconst runTree = this.getRunTreeWithTracingConfig(run.id);\n\t\tawait runTree?.postRun();\n\t}\n\tasync onRunUpdate(run) {\n\t\tconst runTree = this.getRunTreeWithTracingConfig(run.id);\n\t\tawait runTree?.patchRun();\n\t}\n\tgetRun(id) {\n\t\treturn this.runTreeMap.get(id);\n\t}\n\tupdateFromRunTree(runTree) {\n\t\tthis.runTreeMap.set(runTree.id, runTree);\n\t\tlet rootRun = runTree;\n\t\tconst visited = /* @__PURE__ */ new Set();\n\t\twhile (rootRun.parent_run) {\n\t\t\tif (visited.has(rootRun.id)) break;\n\t\t\tvisited.add(rootRun.id);\n\t\t\tif (!rootRun.parent_run) break;\n\t\t\trootRun = rootRun.parent_run;\n\t\t}\n\t\tvisited.clear();\n\t\tconst queue = [rootRun];\n\t\twhile (queue.length > 0) {\n\t\t\tconst current = queue.shift();\n\t\t\tif (!current || visited.has(current.id)) continue;\n\t\t\tvisited.add(current.id);\n\t\t\tthis.runTreeMap.set(current.id, current);\n\t\t\tif (current.child_runs) queue.push(...current.child_runs);\n\t\t}\n\t\tthis.client = runTree.client ?? this.client;\n\t\tthis.replicas = runTree.replicas ?? this.replicas;\n\t\tthis.projectName = runTree.project_name ?? this.projectName;\n\t\tthis.exampleId = runTree.reference_example_id ?? this.exampleId;\n\t}\n\tgetRunTreeWithTracingConfig(id) {\n\t\tconst runTree = this.runTreeMap.get(id);\n\t\tif (!runTree) return void 0;\n\t\treturn new RunTree({\n\t\t\t...runTree,\n\t\t\tclient: this.client,\n\t\t\tproject_name: this.projectName,\n\t\t\treplicas: this.replicas,\n\t\t\treference_example_id: this.exampleId,\n\t\t\ttracingEnabled: true\n\t\t});\n\t}\n\tstatic getTraceableRunTree() {\n\t\ttry {\n\t\t\treturn getCurrentRunTree(true);\n\t\t} catch {\n\t\t\treturn void 0;\n\t\t}\n\t}\n};\n\n//#endregion\nexport { LangChainTracer, tracer_langchain_exports };\n//# sourceMappingURL=tracer_langchain.js.map","import { getDefaultLangChainClientSingleton } from \"./tracer.js\";\nimport { getGlobalAsyncLocalStorageInstance } from \"./async_local_storage/globals.js\";\nimport PQueueMod from \"p-queue\";\n\n//#region src/singletons/callbacks.ts\nlet queue;\n/**\n* Creates a queue using the p-queue library. The queue is configured to\n* auto-start and has a concurrency of 1, meaning it will process tasks\n* one at a time.\n*/\nfunction createQueue() {\n\tconst PQueue = \"default\" in PQueueMod ? PQueueMod.default : PQueueMod;\n\treturn new PQueue({\n\t\tautoStart: true,\n\t\tconcurrency: 1\n\t});\n}\nfunction getQueue() {\n\tif (typeof queue === \"undefined\") queue = createQueue();\n\treturn queue;\n}\n/**\n* Consume a promise, either adding it to the queue or waiting for it to resolve\n* @param promiseFn Promise to consume\n* @param wait Whether to wait for the promise to resolve or resolve immediately\n*/\nasync function consumeCallback(promiseFn, wait) {\n\tif (wait === true) {\n\t\tconst asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n\t\tif (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn());\n\t\telse await promiseFn();\n\t} else {\n\t\tqueue = getQueue();\n\t\tqueue.add(async () => {\n\t\t\tconst asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n\t\t\tif (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn());\n\t\t\telse await promiseFn();\n\t\t});\n\t}\n}\n/**\n* Waits for all promises in the queue to resolve. If the queue is\n* undefined, it immediately resolves a promise.\n*/\nasync function awaitAllCallbacks() {\n\tconst defaultClient = getDefaultLangChainClientSingleton();\n\tawait Promise.allSettled([typeof queue !== \"undefined\" ? queue.onIdle() : Promise.resolve(), defaultClient.awaitPendingTraceBatches()]);\n}\n\n//#endregion\nexport { awaitAllCallbacks, consumeCallback };\n//# sourceMappingURL=callbacks.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { awaitAllCallbacks, consumeCallback } from \"../singletons/callbacks.js\";\n\n//#region src/callbacks/promises.ts\nvar promises_exports = {};\n__export(promises_exports, {\n\tawaitAllCallbacks: () => awaitAllCallbacks,\n\tconsumeCallback: () => consumeCallback\n});\n\n//#endregion\nexport { awaitAllCallbacks, consumeCallback, promises_exports };\n//# sourceMappingURL=promises.js.map","import { getEnvironmentVariable } from \"./env.js\";\n\n//#region src/utils/callbacks.ts\nconst isTracingEnabled = (tracingEnabled) => {\n\tif (tracingEnabled !== void 0) return tracingEnabled;\n\tconst envVars = [\n\t\t\"LANGSMITH_TRACING_V2\",\n\t\t\"LANGCHAIN_TRACING_V2\",\n\t\t\"LANGSMITH_TRACING\",\n\t\t\"LANGCHAIN_TRACING\"\n\t];\n\treturn !!envVars.find((envVar) => getEnvironmentVariable(envVar) === \"true\");\n};\n\n//#endregion\nexport { isTracingEnabled };\n//# sourceMappingURL=callbacks.js.map","import { _CONTEXT_VARIABLES_KEY, getGlobalAsyncLocalStorageInstance } from \"./globals.js\";\nimport { RunTree, isRunTree } from \"langsmith/run_trees\";\n\n//#region src/singletons/async_local_storage/context.ts\n/**\n* Set a context variable. Context variables are scoped to any\n* child runnables called by the current runnable, or globally if set outside\n* of any runnable.\n*\n* @remarks\n* This function is only supported in environments that support AsyncLocalStorage,\n* including Node.js, Deno, and Cloudflare Workers.\n*\n* @example\n* ```ts\n* import { RunnableLambda } from \"@langchain/core/runnables\";\n* import {\n* getContextVariable,\n* setContextVariable\n* } from \"@langchain/core/context\";\n*\n* const nested = RunnableLambda.from(() => {\n* // \"bar\" because it was set by a parent\n* console.log(getContextVariable(\"foo\"));\n*\n* // Override to \"baz\", but only for child runnables\n* setContextVariable(\"foo\", \"baz\");\n*\n* // Now \"baz\", but only for child runnables\n* return getContextVariable(\"foo\");\n* });\n*\n* const runnable = RunnableLambda.from(async () => {\n* // Set a context variable named \"foo\"\n* setContextVariable(\"foo\", \"bar\");\n*\n* const res = await nested.invoke({});\n*\n* // Still \"bar\" since child changes do not affect parents\n* console.log(getContextVariable(\"foo\"));\n*\n* return res;\n* });\n*\n* // undefined, because context variable has not been set yet\n* console.log(getContextVariable(\"foo\"));\n*\n* // Final return value is \"baz\"\n* const result = await runnable.invoke({});\n* ```\n*\n* @param name The name of the context variable.\n* @param value The value to set.\n*/\nfunction setContextVariable(name, value) {\n\tconst asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n\tif (asyncLocalStorageInstance === void 0) throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`);\n\tconst runTree = asyncLocalStorageInstance.getStore();\n\tconst contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] };\n\tcontextVars[name] = value;\n\tlet newValue = {};\n\tif (isRunTree(runTree)) newValue = new RunTree(runTree);\n\tnewValue[_CONTEXT_VARIABLES_KEY] = contextVars;\n\tasyncLocalStorageInstance.enterWith(newValue);\n}\n/**\n* Get the value of a previously set context variable. Context variables\n* are scoped to any child runnables called by the current runnable,\n* or globally if set outside of any runnable.\n*\n* @remarks\n* This function is only supported in environments that support AsyncLocalStorage,\n* including Node.js, Deno, and Cloudflare Workers.\n*\n* @example\n* ```ts\n* import { RunnableLambda } from \"@langchain/core/runnables\";\n* import {\n* getContextVariable,\n* setContextVariable\n* } from \"@langchain/core/context\";\n*\n* const nested = RunnableLambda.from(() => {\n* // \"bar\" because it was set by a parent\n* console.log(getContextVariable(\"foo\"));\n*\n* // Override to \"baz\", but only for child runnables\n* setContextVariable(\"foo\", \"baz\");\n*\n* // Now \"baz\", but only for child runnables\n* return getContextVariable(\"foo\");\n* });\n*\n* const runnable = RunnableLambda.from(async () => {\n* // Set a context variable named \"foo\"\n* setContextVariable(\"foo\", \"bar\");\n*\n* const res = await nested.invoke({});\n*\n* // Still \"bar\" since child changes do not affect parents\n* console.log(getContextVariable(\"foo\"));\n*\n* return res;\n* });\n*\n* // undefined, because context variable has not been set yet\n* console.log(getContextVariable(\"foo\"));\n*\n* // Final return value is \"baz\"\n* const result = await runnable.invoke({});\n* ```\n*\n* @param name The name of the context variable.\n*/\nfunction getContextVariable(name) {\n\tconst asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n\tif (asyncLocalStorageInstance === void 0) return void 0;\n\tconst runTree = asyncLocalStorageInstance.getStore();\n\treturn runTree?.[_CONTEXT_VARIABLES_KEY]?.[name];\n}\nconst LC_CONFIGURE_HOOKS_KEY = Symbol(\"lc:configure_hooks\");\nconst _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || [];\n/**\n* Register a callback configure hook to automatically add callback handlers to all runs.\n*\n* There are two ways to use this:\n*\n* 1. Using a context variable:\n* - Set `contextVar` to specify the variable name\n* - Use `setContextVariable()` to store your handler instance\n*\n* 2. Using an environment variable:\n* - Set both `envVar` and `handlerClass`\n* - The handler will be instantiated when the env var is set to \"true\".\n*\n* @example\n* ```typescript\n* // Method 1: Using context variable\n* import {\n* registerConfigureHook,\n* setContextVariable\n* } from \"@langchain/core/context\";\n*\n* const tracer = new MyCallbackHandler();\n* registerConfigureHook({\n* contextVar: \"my_tracer\",\n* });\n* setContextVariable(\"my_tracer\", tracer);\n*\n* // ...run code here\n*\n* // Method 2: Using environment variable\n* registerConfigureHook({\n* handlerClass: MyCallbackHandler,\n* envVar: \"MY_TRACER_ENABLED\",\n* });\n* process.env.MY_TRACER_ENABLED = \"true\";\n*\n* // ...run code here\n* ```\n*\n* @param config Configuration object for the hook\n* @param config.contextVar Name of the context variable containing the handler instance\n* @param config.inheritable Whether child runs should inherit this handler\n* @param config.handlerClass Optional callback handler class (required if using envVar)\n* @param config.envVar Optional environment variable name to control handler activation\n*/\nconst registerConfigureHook = (config) => {\n\tif (config.envVar && !config.handlerClass) throw new Error(\"If envVar is set, handlerClass must also be set to a non-None value.\");\n\tsetContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]);\n};\n\n//#endregion\nexport { _getConfigureHooks, getContextVariable, registerConfigureHook, setContextVariable };\n//# sourceMappingURL=context.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { getBufferString } from \"../messages/utils.js\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\nimport { BaseCallbackHandler, isBaseCallbackHandler } from \"./base.js\";\nimport { isBaseTracer } from \"../tracers/base.js\";\nimport { ConsoleCallbackHandler } from \"../tracers/console.js\";\nimport { LangChainTracer } from \"../tracers/tracer_langchain.js\";\nimport { consumeCallback } from \"../singletons/callbacks.js\";\nimport \"./promises.js\";\nimport { isTracingEnabled } from \"../utils/callbacks.js\";\nimport { _getConfigureHooks, getContextVariable } from \"../singletons/async_local_storage/context.js\";\nimport { v4 } from \"uuid\";\n\n//#region src/callbacks/manager.ts\nvar manager_exports = {};\n__export(manager_exports, {\n\tBaseCallbackManager: () => BaseCallbackManager,\n\tBaseRunManager: () => BaseRunManager,\n\tCallbackManager: () => CallbackManager,\n\tCallbackManagerForChainRun: () => CallbackManagerForChainRun,\n\tCallbackManagerForLLMRun: () => CallbackManagerForLLMRun,\n\tCallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun,\n\tCallbackManagerForToolRun: () => CallbackManagerForToolRun,\n\tensureHandler: () => ensureHandler,\n\tparseCallbackConfigArg: () => parseCallbackConfigArg\n});\nfunction parseCallbackConfigArg(arg) {\n\tif (!arg) return {};\n\telse if (Array.isArray(arg) || \"name\" in arg) return { callbacks: arg };\n\telse return arg;\n}\n/**\n* Manage callbacks from different components of LangChain.\n*/\nvar BaseCallbackManager = class {\n\tsetHandler(handler) {\n\t\treturn this.setHandlers([handler]);\n\t}\n};\n/**\n* Base class for run manager in LangChain.\n*/\nvar BaseRunManager = class {\n\tconstructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) {\n\t\tthis.runId = runId;\n\t\tthis.handlers = handlers;\n\t\tthis.inheritableHandlers = inheritableHandlers;\n\t\tthis.tags = tags;\n\t\tthis.inheritableTags = inheritableTags;\n\t\tthis.metadata = metadata;\n\t\tthis.inheritableMetadata = inheritableMetadata;\n\t\tthis._parentRunId = _parentRunId;\n\t}\n\tget parentRunId() {\n\t\treturn this._parentRunId;\n\t}\n\tasync handleText(text) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\ttry {\n\t\t\t\tawait handler.handleText?.(text, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleCustomEvent(eventName, data, _runId, _tags, _metadata) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\ttry {\n\t\t\t\tawait handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n};\n/**\n* Manages callbacks for retriever runs.\n*/\nvar CallbackManagerForRetrieverRun = class extends BaseRunManager {\n\tgetChild(tag) {\n\t\tconst manager = new CallbackManager(this.runId);\n\t\tmanager.setHandlers(this.inheritableHandlers);\n\t\tmanager.addTags(this.inheritableTags);\n\t\tmanager.addMetadata(this.inheritableMetadata);\n\t\tif (tag) manager.addTags([tag], false);\n\t\treturn manager;\n\t}\n\tasync handleRetrieverEnd(documents) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreRetriever) try {\n\t\t\t\tawait handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleRetriever`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleRetrieverError(err) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreRetriever) try {\n\t\t\t\tawait handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (error) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n};\nvar CallbackManagerForLLMRun = class extends BaseRunManager {\n\tasync handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreLLM) try {\n\t\t\t\tawait handler.handleLLMNewToken?.(token, idx ?? {\n\t\t\t\t\tprompt: 0,\n\t\t\t\t\tcompletion: 0\n\t\t\t\t}, this.runId, this._parentRunId, this.tags, fields);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleLLMError(err, _runId, _parentRunId, _tags, extraParams) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreLLM) try {\n\t\t\t\tawait handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams);\n\t\t\t} catch (err$1) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err$1}`);\n\t\t\t\tif (handler.raiseError) throw err$1;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreLLM) try {\n\t\t\t\tawait handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n};\nvar CallbackManagerForChainRun = class extends BaseRunManager {\n\tgetChild(tag) {\n\t\tconst manager = new CallbackManager(this.runId);\n\t\tmanager.setHandlers(this.inheritableHandlers);\n\t\tmanager.addTags(this.inheritableTags);\n\t\tmanager.addMetadata(this.inheritableMetadata);\n\t\tif (tag) manager.addTags([tag], false);\n\t\treturn manager;\n\t}\n\tasync handleChainError(err, _runId, _parentRunId, _tags, kwargs) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreChain) try {\n\t\t\t\tawait handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs);\n\t\t\t} catch (err$1) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err$1}`);\n\t\t\t\tif (handler.raiseError) throw err$1;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreChain) try {\n\t\t\t\tawait handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleAgentAction(action) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreAgent) try {\n\t\t\t\tawait handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleAgentEnd(action) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreAgent) try {\n\t\t\t\tawait handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n};\nvar CallbackManagerForToolRun = class extends BaseRunManager {\n\tgetChild(tag) {\n\t\tconst manager = new CallbackManager(this.runId);\n\t\tmanager.setHandlers(this.inheritableHandlers);\n\t\tmanager.addTags(this.inheritableTags);\n\t\tmanager.addMetadata(this.inheritableMetadata);\n\t\tif (tag) manager.addTags([tag], false);\n\t\treturn manager;\n\t}\n\tasync handleToolError(err) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreAgent) try {\n\t\t\t\tawait handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (err$1) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err$1}`);\n\t\t\t\tif (handler.raiseError) throw err$1;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\tasync handleToolEnd(output) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreAgent) try {\n\t\t\t\tawait handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n};\n/**\n* @example\n* ```typescript\n* const prompt = PromptTemplate.fromTemplate(\"What is the answer to {question}?\");\n*\n* // Example of using LLMChain with OpenAI and a simple prompt\n* const chain = new LLMChain({\n* llm: new ChatOpenAI({ model: \"gpt-4o-mini\", temperature: 0.9 }),\n* prompt,\n* });\n*\n* // Running the chain with a single question\n* const result = await chain.call({\n* question: \"What is the airspeed velocity of an unladen swallow?\",\n* });\n* console.log(\"The answer is:\", result);\n* ```\n*/\nvar CallbackManager = class CallbackManager extends BaseCallbackManager {\n\thandlers = [];\n\tinheritableHandlers = [];\n\ttags = [];\n\tinheritableTags = [];\n\tmetadata = {};\n\tinheritableMetadata = {};\n\tname = \"callback_manager\";\n\t_parentRunId;\n\tconstructor(parentRunId, options) {\n\t\tsuper();\n\t\tthis.handlers = options?.handlers ?? this.handlers;\n\t\tthis.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers;\n\t\tthis.tags = options?.tags ?? this.tags;\n\t\tthis.inheritableTags = options?.inheritableTags ?? this.inheritableTags;\n\t\tthis.metadata = options?.metadata ?? this.metadata;\n\t\tthis.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata;\n\t\tthis._parentRunId = parentRunId;\n\t}\n\t/**\n\t* Gets the parent run ID, if any.\n\t*\n\t* @returns The parent run ID.\n\t*/\n\tgetParentRunId() {\n\t\treturn this._parentRunId;\n\t}\n\tasync handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {\n\t\treturn Promise.all(prompts.map(async (prompt, idx) => {\n\t\t\tconst runId_ = idx === 0 && runId ? runId : v4();\n\t\t\tawait Promise.all(this.handlers.map((handler) => {\n\t\t\t\tif (handler.ignoreLLM) return;\n\t\t\t\tif (isBaseTracer(handler)) handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n\t\t\t\treturn consumeCallback(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`);\n\t\t\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t\t\t}\n\t\t\t\t}, handler.awaitHandlers);\n\t\t\t}));\n\t\t\treturn new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n\t\t}));\n\t}\n\tasync handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {\n\t\treturn Promise.all(messages.map(async (messageGroup, idx) => {\n\t\t\tconst runId_ = idx === 0 && runId ? runId : v4();\n\t\t\tawait Promise.all(this.handlers.map((handler) => {\n\t\t\t\tif (handler.ignoreLLM) return;\n\t\t\t\tif (isBaseTracer(handler)) handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n\t\t\t\treturn consumeCallback(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (handler.handleChatModelStart) await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n\t\t\t\t\t\telse if (handler.handleLLMStart) {\n\t\t\t\t\t\t\tconst messageString = getBufferString(messageGroup);\n\t\t\t\t\t\t\tawait handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`);\n\t\t\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t\t\t}\n\t\t\t\t}, handler.awaitHandlers);\n\t\t\t}));\n\t\t\treturn new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n\t\t}));\n\t}\n\tasync handleChainStart(chain, inputs, runId = v4(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {\n\t\tawait Promise.all(this.handlers.map((handler) => {\n\t\t\tif (handler.ignoreChain) return;\n\t\t\tif (isBaseTracer(handler)) handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);\n\t\t\treturn consumeCallback(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`);\n\t\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t\t}\n\t\t\t}, handler.awaitHandlers);\n\t\t}));\n\t\treturn new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n\t}\n\tasync handleToolStart(tool, input, runId = v4(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {\n\t\tawait Promise.all(this.handlers.map((handler) => {\n\t\t\tif (handler.ignoreAgent) return;\n\t\t\tif (isBaseTracer(handler)) handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);\n\t\t\treturn consumeCallback(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`);\n\t\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t\t}\n\t\t\t}, handler.awaitHandlers);\n\t\t}));\n\t\treturn new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n\t}\n\tasync handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {\n\t\tawait Promise.all(this.handlers.map((handler) => {\n\t\t\tif (handler.ignoreRetriever) return;\n\t\t\tif (isBaseTracer(handler)) handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);\n\t\t\treturn consumeCallback(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`);\n\t\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t\t}\n\t\t\t}, handler.awaitHandlers);\n\t\t}));\n\t\treturn new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n\t}\n\tasync handleCustomEvent(eventName, data, runId, _tags, _metadata) {\n\t\tawait Promise.all(this.handlers.map((handler) => consumeCallback(async () => {\n\t\t\tif (!handler.ignoreCustomEvent) try {\n\t\t\t\tawait handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata);\n\t\t\t} catch (err) {\n\t\t\t\tconst logFunction = handler.raiseError ? console.error : console.warn;\n\t\t\t\tlogFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`);\n\t\t\t\tif (handler.raiseError) throw err;\n\t\t\t}\n\t\t}, handler.awaitHandlers)));\n\t}\n\taddHandler(handler, inherit = true) {\n\t\tthis.handlers.push(handler);\n\t\tif (inherit) this.inheritableHandlers.push(handler);\n\t}\n\tremoveHandler(handler) {\n\t\tthis.handlers = this.handlers.filter((_handler) => _handler !== handler);\n\t\tthis.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler);\n\t}\n\tsetHandlers(handlers, inherit = true) {\n\t\tthis.handlers = [];\n\t\tthis.inheritableHandlers = [];\n\t\tfor (const handler of handlers) this.addHandler(handler, inherit);\n\t}\n\taddTags(tags, inherit = true) {\n\t\tthis.removeTags(tags);\n\t\tthis.tags.push(...tags);\n\t\tif (inherit) this.inheritableTags.push(...tags);\n\t}\n\tremoveTags(tags) {\n\t\tthis.tags = this.tags.filter((tag) => !tags.includes(tag));\n\t\tthis.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag));\n\t}\n\taddMetadata(metadata, inherit = true) {\n\t\tthis.metadata = {\n\t\t\t...this.metadata,\n\t\t\t...metadata\n\t\t};\n\t\tif (inherit) this.inheritableMetadata = {\n\t\t\t...this.inheritableMetadata,\n\t\t\t...metadata\n\t\t};\n\t}\n\tremoveMetadata(metadata) {\n\t\tfor (const key of Object.keys(metadata)) {\n\t\t\tdelete this.metadata[key];\n\t\t\tdelete this.inheritableMetadata[key];\n\t\t}\n\t}\n\tcopy(additionalHandlers = [], inherit = true) {\n\t\tconst manager = new CallbackManager(this._parentRunId);\n\t\tfor (const handler of this.handlers) {\n\t\t\tconst inheritable = this.inheritableHandlers.includes(handler);\n\t\t\tmanager.addHandler(handler, inheritable);\n\t\t}\n\t\tfor (const tag of this.tags) {\n\t\t\tconst inheritable = this.inheritableTags.includes(tag);\n\t\t\tmanager.addTags([tag], inheritable);\n\t\t}\n\t\tfor (const key of Object.keys(this.metadata)) {\n\t\t\tconst inheritable = Object.keys(this.inheritableMetadata).includes(key);\n\t\t\tmanager.addMetadata({ [key]: this.metadata[key] }, inheritable);\n\t\t}\n\t\tfor (const handler of additionalHandlers) {\n\t\t\tif (manager.handlers.filter((h) => h.name === \"console_callback_handler\").some((h) => h.name === handler.name)) continue;\n\t\t\tmanager.addHandler(handler, inherit);\n\t\t}\n\t\treturn manager;\n\t}\n\tstatic fromHandlers(handlers) {\n\t\tclass Handler extends BaseCallbackHandler {\n\t\t\tname = v4();\n\t\t\tconstructor() {\n\t\t\t\tsuper();\n\t\t\t\tObject.assign(this, handlers);\n\t\t\t}\n\t\t}\n\t\tconst manager = new this();\n\t\tmanager.addHandler(new Handler());\n\t\treturn manager;\n\t}\n\tstatic configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) {\n\t\treturn this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options);\n\t}\n\tstatic _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) {\n\t\tlet callbackManager;\n\t\tif (inheritableHandlers || localHandlers) {\n\t\t\tif (Array.isArray(inheritableHandlers) || !inheritableHandlers) {\n\t\t\t\tcallbackManager = new CallbackManager();\n\t\t\t\tcallbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true);\n\t\t\t} else callbackManager = inheritableHandlers;\n\t\t\tcallbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false);\n\t\t}\n\t\tconst verboseEnabled = getEnvironmentVariable(\"LANGCHAIN_VERBOSE\") === \"true\" || options?.verbose;\n\t\tconst tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || isTracingEnabled();\n\t\tconst tracingEnabled = tracingV2Enabled || (getEnvironmentVariable(\"LANGCHAIN_TRACING\") ?? false);\n\t\tif (verboseEnabled || tracingEnabled) {\n\t\t\tif (!callbackManager) callbackManager = new CallbackManager();\n\t\t\tif (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) {\n\t\t\t\tconst consoleHandler = new ConsoleCallbackHandler();\n\t\t\t\tcallbackManager.addHandler(consoleHandler, true);\n\t\t\t}\n\t\t\tif (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === \"langchain_tracer\")) {\n\t\t\t\tif (tracingV2Enabled) {\n\t\t\t\t\tconst tracerV2 = new LangChainTracer();\n\t\t\t\t\tcallbackManager.addHandler(tracerV2, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (tracingV2Enabled) {\n\t\t\t\tconst implicitRunTree = LangChainTracer.getTraceableRunTree();\n\t\t\t\tif (implicitRunTree && callbackManager._parentRunId === void 0) {\n\t\t\t\t\tcallbackManager._parentRunId = implicitRunTree.id;\n\t\t\t\t\tconst tracerV2 = callbackManager.handlers.find((handler) => handler.name === \"langchain_tracer\");\n\t\t\t\t\ttracerV2?.updateFromRunTree(implicitRunTree);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) {\n\t\t\tconst createIfNotInContext = envVar && getEnvironmentVariable(envVar) === \"true\" && handlerClass;\n\t\t\tlet handler;\n\t\t\tconst contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0;\n\t\t\tif (contextVarValue && isBaseCallbackHandler(contextVarValue)) handler = contextVarValue;\n\t\t\telse if (createIfNotInContext) handler = new handlerClass({});\n\t\t\tif (handler !== void 0) {\n\t\t\t\tif (!callbackManager) callbackManager = new CallbackManager();\n\t\t\t\tif (!callbackManager.handlers.some((h) => h.name === handler.name)) callbackManager.addHandler(handler, inheritable);\n\t\t\t}\n\t\t}\n\t\tif (inheritableTags || localTags) {\n\t\t\tif (callbackManager) {\n\t\t\t\tcallbackManager.addTags(inheritableTags ?? []);\n\t\t\t\tcallbackManager.addTags(localTags ?? [], false);\n\t\t\t}\n\t\t}\n\t\tif (inheritableMetadata || localMetadata) {\n\t\t\tif (callbackManager) {\n\t\t\t\tcallbackManager.addMetadata(inheritableMetadata ?? {});\n\t\t\t\tcallbackManager.addMetadata(localMetadata ?? {}, false);\n\t\t\t}\n\t\t}\n\t\treturn callbackManager;\n\t}\n};\nfunction ensureHandler(handler) {\n\tif (\"name\" in handler) return handler;\n\treturn BaseCallbackHandler.fromMethods(handler);\n}\n\n//#endregion\nexport { BaseCallbackManager, BaseRunManager, CallbackManager, CallbackManagerForChainRun, CallbackManagerForLLMRun, CallbackManagerForRetrieverRun, CallbackManagerForToolRun, ensureHandler, manager_exports, parseCallbackConfigArg };\n//# sourceMappingURL=manager.js.map","import { _CONTEXT_VARIABLES_KEY, getGlobalAsyncLocalStorageInstance, setGlobalAsyncLocalStorageInstance } from \"./globals.js\";\nimport { CallbackManager } from \"../../callbacks/manager.js\";\nimport { RunTree } from \"langsmith\";\n\n//#region src/singletons/async_local_storage/index.ts\nvar MockAsyncLocalStorage = class {\n\tgetStore() {\n\t\treturn void 0;\n\t}\n\trun(_store, callback) {\n\t\treturn callback();\n\t}\n\tenterWith(_store) {\n\t\treturn void 0;\n\t}\n};\nconst mockAsyncLocalStorage = new MockAsyncLocalStorage();\nconst LC_CHILD_KEY = Symbol.for(\"lc:child_config\");\nvar AsyncLocalStorageProvider = class {\n\tgetInstance() {\n\t\treturn getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage;\n\t}\n\tgetRunnableConfig() {\n\t\tconst storage = this.getInstance();\n\t\treturn storage.getStore()?.extra?.[LC_CHILD_KEY];\n\t}\n\trunWithConfig(config, callback, avoidCreatingRootRunTree) {\n\t\tconst callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata);\n\t\tconst storage = this.getInstance();\n\t\tconst previousValue = storage.getStore();\n\t\tconst parentRunId = callbackManager?.getParentRunId();\n\t\tconst langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === \"langchain_tracer\");\n\t\tlet runTree;\n\t\tif (langChainTracer && parentRunId) runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId);\n\t\telse if (!avoidCreatingRootRunTree) runTree = new RunTree({\n\t\t\tname: \"\",\n\t\t\ttracingEnabled: false\n\t\t});\n\t\tif (runTree) runTree.extra = {\n\t\t\t...runTree.extra,\n\t\t\t[LC_CHILD_KEY]: config\n\t\t};\n\t\tif (previousValue !== void 0 && previousValue[_CONTEXT_VARIABLES_KEY] !== void 0) {\n\t\t\tif (runTree === void 0) runTree = {};\n\t\t\trunTree[_CONTEXT_VARIABLES_KEY] = previousValue[_CONTEXT_VARIABLES_KEY];\n\t\t}\n\t\treturn storage.run(runTree, callback);\n\t}\n\tinitializeGlobalInstance(instance) {\n\t\tif (getGlobalAsyncLocalStorageInstance() === void 0) setGlobalAsyncLocalStorageInstance(instance);\n\t}\n};\nconst AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();\n\n//#endregion\nexport { AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage };\n//# sourceMappingURL=index.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { _CONTEXT_VARIABLES_KEY } from \"./async_local_storage/globals.js\";\nimport { AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage } from \"./async_local_storage/index.js\";\n\n//#region src/singletons/index.ts\nvar singletons_exports = {};\n__export(singletons_exports, {\n\tAsyncLocalStorageProviderSingleton: () => AsyncLocalStorageProviderSingleton,\n\tMockAsyncLocalStorage: () => MockAsyncLocalStorage,\n\t_CONTEXT_VARIABLES_KEY: () => _CONTEXT_VARIABLES_KEY\n});\n\n//#endregion\nexport { AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage, _CONTEXT_VARIABLES_KEY, singletons_exports };\n//# sourceMappingURL=index.js.map","const __WEBPACK_NAMESPACE_OBJECT__ = __WEBPACK_EXTERNAL_createRequire(import.meta.url)(\"node:async_hooks\");","import { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n//#region src/setup/async_local_storage.ts\nfunction initializeAsyncLocalStorageSingleton() {\n\tAsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorage());\n}\n\n//#endregion\nexport { initializeAsyncLocalStorageSingleton };\n//# sourceMappingURL=async_local_storage.js.map","//#region src/errors.ts\n/** @category Errors */\nvar BaseLangGraphError = class extends Error {\n\tlc_error_code;\n\tconstructor(message, fields) {\n\t\tlet finalMessage = message ?? \"\";\n\t\tif (fields?.lc_error_code) finalMessage = `${finalMessage}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\\n`;\n\t\tsuper(finalMessage);\n\t\tthis.lc_error_code = fields?.lc_error_code;\n\t}\n};\nvar GraphBubbleUp = class extends BaseLangGraphError {\n\tget is_bubble_up() {\n\t\treturn true;\n\t}\n};\nvar GraphRecursionError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"GraphRecursionError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"GraphRecursionError\";\n\t}\n};\nvar GraphValueError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"GraphValueError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"GraphValueError\";\n\t}\n};\nvar GraphInterrupt = class extends GraphBubbleUp {\n\tinterrupts;\n\tconstructor(interrupts, fields) {\n\t\tsuper(JSON.stringify(interrupts, null, 2), fields);\n\t\tthis.name = \"GraphInterrupt\";\n\t\tthis.interrupts = interrupts ?? [];\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"GraphInterrupt\";\n\t}\n};\n/** Raised by a node to interrupt execution. */\nvar NodeInterrupt = class extends GraphInterrupt {\n\tconstructor(message, fields) {\n\t\tsuper([{ value: message }], fields);\n\t\tthis.name = \"NodeInterrupt\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"NodeInterrupt\";\n\t}\n};\nvar ParentCommand = class extends GraphBubbleUp {\n\tcommand;\n\tconstructor(command) {\n\t\tsuper();\n\t\tthis.name = \"ParentCommand\";\n\t\tthis.command = command;\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"ParentCommand\";\n\t}\n};\nfunction isParentCommand(e) {\n\treturn e !== void 0 && e.name === ParentCommand.unminifiable_name;\n}\nfunction isGraphBubbleUp(e) {\n\treturn e !== void 0 && e.is_bubble_up === true;\n}\nfunction isGraphInterrupt(e) {\n\treturn e !== void 0 && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name);\n}\nvar EmptyInputError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"EmptyInputError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"EmptyInputError\";\n\t}\n};\nvar EmptyChannelError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"EmptyChannelError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"EmptyChannelError\";\n\t}\n};\nvar InvalidUpdateError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"InvalidUpdateError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"InvalidUpdateError\";\n\t}\n};\n/**\n* @deprecated This exception type is no longer thrown.\n*/\nvar MultipleSubgraphsError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"MultipleSubgraphError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"MultipleSubgraphError\";\n\t}\n};\nvar UnreachableNodeError = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"UnreachableNodeError\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"UnreachableNodeError\";\n\t}\n};\n/**\n* Exception raised when an error occurs in the remote graph.\n*/\nvar RemoteException = class extends BaseLangGraphError {\n\tconstructor(message, fields) {\n\t\tsuper(message, fields);\n\t\tthis.name = \"RemoteException\";\n\t}\n\tstatic get unminifiable_name() {\n\t\treturn \"RemoteException\";\n\t}\n};\n/**\n* Used for subgraph detection.\n*/\nconst getSubgraphsSeenSet = () => {\n\tif (globalThis[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")] === void 0) globalThis[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")] = /* @__PURE__ */ new Set();\n\treturn globalThis[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")];\n};\n\n//#endregion\nexport { BaseLangGraphError, EmptyChannelError, EmptyInputError, GraphBubbleUp, GraphInterrupt, GraphRecursionError, GraphValueError, InvalidUpdateError, MultipleSubgraphsError, NodeInterrupt, ParentCommand, RemoteException, UnreachableNodeError, getSubgraphsSeenSet, isGraphBubbleUp, isGraphInterrupt, isParentCommand };\n//# sourceMappingURL=errors.js.map","import uuid from './dist/index.js';\nexport const v1 = uuid.v1;\nexport const v1ToV6 = uuid.v1ToV6;\nexport const v3 = uuid.v3;\nexport const v4 = uuid.v4;\nexport const v5 = uuid.v5;\nexport const v6 = uuid.v6;\nexport const v6ToV1 = uuid.v6ToV1;\nexport const v7 = uuid.v7;\nexport const NIL = uuid.NIL;\nexport const MAX = uuid.MAX;\nexport const version = uuid.version;\nexport const validate = uuid.validate;\nexport const stringify = uuid.stringify;\nexport const parse = uuid.parse;\n","import { v5, v6 } from \"uuid\";\n\n//#region src/id.ts\nfunction uuid6(clockseq) {\n\treturn v6({ clockseq });\n}\nfunction uuid5(name, namespace) {\n\tconst namespaceBytes = namespace.replace(/-/g, \"\").match(/.{2}/g).map((byte) => parseInt(byte, 16));\n\treturn v5(name, new Uint8Array(namespaceBytes));\n}\n\n//#endregion\nexport { uuid5, uuid6 };\n//# sourceMappingURL=id.js.map","//#region src/serde/types.ts\nconst TASKS = \"__pregel_tasks\";\nconst ERROR = \"__error__\";\nconst SCHEDULED = \"__scheduled__\";\nconst INTERRUPT = \"__interrupt__\";\nconst RESUME = \"__resume__\";\n\n//#endregion\nexport { ERROR, INTERRUPT, RESUME, SCHEDULED, TASKS };\n//# sourceMappingURL=types.js.map","//#region src/serde/utils/fast-safe-stringify/index.ts\nvar LIMIT_REPLACE_NODE = \"[...]\";\nvar CIRCULAR_REPLACE_NODE = \"[Circular]\";\nvar arr = [];\nvar replacerStack = [];\nfunction defaultOptions() {\n\treturn {\n\t\tdepthLimit: Number.MAX_SAFE_INTEGER,\n\t\tedgesLimit: Number.MAX_SAFE_INTEGER\n\t};\n}\nfunction stringify(obj, replacer, spacer, options) {\n\tif (typeof options === \"undefined\") options = defaultOptions();\n\tdecirc(obj, \"\", 0, [], void 0, 0, options);\n\tvar res;\n\ttry {\n\t\tif (replacerStack.length === 0) res = JSON.stringify(obj, replacer, spacer);\n\t\telse res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);\n\t} catch (_) {\n\t\treturn JSON.stringify(\"[unable to serialize, circular reference is too complex to analyze]\");\n\t} finally {\n\t\twhile (arr.length !== 0) {\n\t\t\tvar part = arr.pop();\n\t\t\tif (part.length === 4) Object.defineProperty(part[0], part[1], part[3]);\n\t\t\telse part[0][part[1]] = part[2];\n\t\t}\n\t}\n\treturn res;\n}\nfunction setReplace(replace, val, k, parent) {\n\tvar propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);\n\tif (propertyDescriptor.get !== void 0) if (propertyDescriptor.configurable) {\n\t\tObject.defineProperty(parent, k, { value: replace });\n\t\tarr.push([\n\t\t\tparent,\n\t\t\tk,\n\t\t\tval,\n\t\t\tpropertyDescriptor\n\t\t]);\n\t} else replacerStack.push([\n\t\tval,\n\t\tk,\n\t\treplace\n\t]);\n\telse {\n\t\tparent[k] = replace;\n\t\tarr.push([\n\t\t\tparent,\n\t\t\tk,\n\t\t\tval\n\t\t]);\n\t}\n}\nfunction decirc(val, k, edgeIndex, stack, parent, depth, options) {\n\tdepth += 1;\n\tvar i;\n\tif (typeof val === \"object\" && val !== null) {\n\t\tfor (i = 0; i < stack.length; i++) if (stack[i] === val) {\n\t\t\tsetReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof options.depthLimit !== \"undefined\" && depth > options.depthLimit) {\n\t\t\tsetReplace(LIMIT_REPLACE_NODE, val, k, parent);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof options.edgesLimit !== \"undefined\" && edgeIndex + 1 > options.edgesLimit) {\n\t\t\tsetReplace(LIMIT_REPLACE_NODE, val, k, parent);\n\t\t\treturn;\n\t\t}\n\t\tstack.push(val);\n\t\tif (Array.isArray(val)) for (i = 0; i < val.length; i++) decirc(val[i], i, i, stack, val, depth, options);\n\t\telse {\n\t\t\tvar keys = Object.keys(val);\n\t\t\tfor (i = 0; i < keys.length; i++) {\n\t\t\t\tvar key = keys[i];\n\t\t\t\tdecirc(val[key], key, i, stack, val, depth, options);\n\t\t\t}\n\t\t}\n\t\tstack.pop();\n\t}\n}\nfunction replaceGetterValues(replacer) {\n\treplacer = typeof replacer !== \"undefined\" ? replacer : function(k, v) {\n\t\treturn v;\n\t};\n\treturn function(key, val) {\n\t\tif (replacerStack.length > 0) for (var i = 0; i < replacerStack.length; i++) {\n\t\t\tvar part = replacerStack[i];\n\t\t\tif (part[1] === key && part[0] === val) {\n\t\t\t\tval = part[2];\n\t\t\t\treplacerStack.splice(i, 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn replacer.call(this, key, val);\n\t};\n}\n\n//#endregion\nexport { stringify };\n//# sourceMappingURL=index.js.map","//#region src/load/import_constants.ts\nconst optionalImportEntrypoints = [];\n\n//#endregion\nexport { optionalImportEntrypoints };\n//# sourceMappingURL=import_constants.js.map","//#region src/agents.ts\nvar agents_exports = {};\n\n//#endregion\nexport { agents_exports };\n//# sourceMappingURL=agents.js.map","import { CallbackManager, ensureHandler } from \"../callbacks/manager.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/async_local_storage/index.js\";\nimport \"../singletons/index.js\";\n\n//#region src/runnables/config.ts\nconst DEFAULT_RECURSION_LIMIT = 25;\nasync function getCallbackManagerForConfig(config) {\n\treturn CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata);\n}\nfunction mergeConfigs(...configs) {\n\tconst copy = {};\n\tfor (const options of configs.filter((c) => !!c)) for (const key of Object.keys(options)) if (key === \"metadata\") copy[key] = {\n\t\t...copy[key],\n\t\t...options[key]\n\t};\n\telse if (key === \"tags\") {\n\t\tconst baseKeys = copy[key] ?? [];\n\t\tcopy[key] = [...new Set(baseKeys.concat(options[key] ?? []))];\n\t} else if (key === \"configurable\") copy[key] = {\n\t\t...copy[key],\n\t\t...options[key]\n\t};\n\telse if (key === \"timeout\") {\n\t\tif (copy.timeout === void 0) copy.timeout = options.timeout;\n\t\telse if (options.timeout !== void 0) copy.timeout = Math.min(copy.timeout, options.timeout);\n\t} else if (key === \"signal\") {\n\t\tif (copy.signal === void 0) copy.signal = options.signal;\n\t\telse if (options.signal !== void 0) if (\"any\" in AbortSignal) copy.signal = AbortSignal.any([copy.signal, options.signal]);\n\t\telse copy.signal = options.signal;\n\t} else if (key === \"callbacks\") {\n\t\tconst baseCallbacks = copy.callbacks;\n\t\tconst providedCallbacks = options.callbacks;\n\t\tif (Array.isArray(providedCallbacks)) if (!baseCallbacks) copy.callbacks = providedCallbacks;\n\t\telse if (Array.isArray(baseCallbacks)) copy.callbacks = baseCallbacks.concat(providedCallbacks);\n\t\telse {\n\t\t\tconst manager = baseCallbacks.copy();\n\t\t\tfor (const callback of providedCallbacks) manager.addHandler(ensureHandler(callback), true);\n\t\t\tcopy.callbacks = manager;\n\t\t}\n\t\telse if (providedCallbacks) if (!baseCallbacks) copy.callbacks = providedCallbacks;\n\t\telse if (Array.isArray(baseCallbacks)) {\n\t\t\tconst manager = providedCallbacks.copy();\n\t\t\tfor (const callback of baseCallbacks) manager.addHandler(ensureHandler(callback), true);\n\t\t\tcopy.callbacks = manager;\n\t\t} else copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, {\n\t\t\thandlers: baseCallbacks.handlers.concat(providedCallbacks.handlers),\n\t\t\tinheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers),\n\t\t\ttags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))),\n\t\t\tinheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))),\n\t\t\tmetadata: {\n\t\t\t\t...baseCallbacks.metadata,\n\t\t\t\t...providedCallbacks.metadata\n\t\t\t}\n\t\t});\n\t} else {\n\t\tconst typedKey = key;\n\t\tcopy[typedKey] = options[typedKey] ?? copy[typedKey];\n\t}\n\treturn copy;\n}\nconst PRIMITIVES = new Set([\n\t\"string\",\n\t\"number\",\n\t\"boolean\"\n]);\n/**\n* Ensure that a passed config is an object with all required keys present.\n*/\nfunction ensureConfig(config) {\n\tconst implicitConfig = AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tlet empty = {\n\t\ttags: [],\n\t\tmetadata: {},\n\t\trecursionLimit: 25,\n\t\trunId: void 0\n\t};\n\tif (implicitConfig) {\n\t\tconst { runId, runName,...rest } = implicitConfig;\n\t\tempty = Object.entries(rest).reduce((currentConfig, [key, value]) => {\n\t\t\tif (value !== void 0) currentConfig[key] = value;\n\t\t\treturn currentConfig;\n\t\t}, empty);\n\t}\n\tif (config) empty = Object.entries(config).reduce((currentConfig, [key, value]) => {\n\t\tif (value !== void 0) currentConfig[key] = value;\n\t\treturn currentConfig;\n\t}, empty);\n\tif (empty?.configurable) {\n\t\tfor (const key of Object.keys(empty.configurable)) if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) {\n\t\t\tif (!empty.metadata) empty.metadata = {};\n\t\t\tempty.metadata[key] = empty.configurable[key];\n\t\t}\n\t}\n\tif (empty.timeout !== void 0) {\n\t\tif (empty.timeout <= 0) throw new Error(\"Timeout must be a positive number\");\n\t\tconst timeoutSignal = AbortSignal.timeout(empty.timeout);\n\t\tif (empty.signal !== void 0) {\n\t\t\tif (\"any\" in AbortSignal) empty.signal = AbortSignal.any([empty.signal, timeoutSignal]);\n\t\t} else empty.signal = timeoutSignal;\n\t\tdelete empty.timeout;\n\t}\n\treturn empty;\n}\n/**\n* Helper function that patches runnable configs with updated properties.\n*/\nfunction patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) {\n\tconst newConfig = ensureConfig(config);\n\tif (callbacks !== void 0) {\n\t\t/**\n\t\t* If we're replacing callbacks we need to unset runName\n\t\t* since that should apply only to the same run as the original callbacks\n\t\t*/\n\t\tdelete newConfig.runName;\n\t\tnewConfig.callbacks = callbacks;\n\t}\n\tif (recursionLimit !== void 0) newConfig.recursionLimit = recursionLimit;\n\tif (maxConcurrency !== void 0) newConfig.maxConcurrency = maxConcurrency;\n\tif (runName !== void 0) newConfig.runName = runName;\n\tif (configurable !== void 0) newConfig.configurable = {\n\t\t...newConfig.configurable,\n\t\t...configurable\n\t};\n\tif (runId !== void 0) delete newConfig.runId;\n\treturn newConfig;\n}\nfunction pickRunnableConfigKeys(config) {\n\treturn config ? {\n\t\tconfigurable: config.configurable,\n\t\trecursionLimit: config.recursionLimit,\n\t\tcallbacks: config.callbacks,\n\t\ttags: config.tags,\n\t\tmetadata: config.metadata,\n\t\tmaxConcurrency: config.maxConcurrency,\n\t\ttimeout: config.timeout,\n\t\tsignal: config.signal\n\t} : void 0;\n}\n\n//#endregion\nexport { DEFAULT_RECURSION_LIMIT, ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys };\n//# sourceMappingURL=config.js.map","//#region src/utils/signal.ts\n/**\n* Race a promise with an abort signal. If the signal is aborted, the promise will\n* be rejected with the error from the signal. If the promise is rejected, the signal will be aborted.\n*\n* @param promise - The promise to race.\n* @param signal - The abort signal.\n* @returns The result of the promise.\n*/\nasync function raceWithSignal(promise, signal) {\n\tif (signal === void 0) return promise;\n\tlet listener;\n\treturn Promise.race([promise.catch((err) => {\n\t\tif (!signal?.aborted) throw err;\n\t\telse return void 0;\n\t}), new Promise((_, reject) => {\n\t\tlistener = () => {\n\t\t\treject(getAbortSignalError(signal));\n\t\t};\n\t\tsignal.addEventListener(\"abort\", listener);\n\t\tif (signal.aborted) reject(getAbortSignalError(signal));\n\t})]).finally(() => signal.removeEventListener(\"abort\", listener));\n}\n/**\n* Get the error from an abort signal. Since you can set the reason to anything,\n* we have to do some type gymnastics to get a proper error message.\n*\n* @param signal - The abort signal.\n* @returns The error from the abort signal.\n*/\nfunction getAbortSignalError(signal) {\n\tif (signal?.reason instanceof Error) return signal.reason;\n\tif (typeof signal?.reason === \"string\") return new Error(signal.reason);\n\treturn /* @__PURE__ */ new Error(\"Aborted\");\n}\n\n//#endregion\nexport { getAbortSignalError, raceWithSignal };\n//# sourceMappingURL=signal.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/async_local_storage/index.js\";\nimport \"../singletons/index.js\";\nimport { pickRunnableConfigKeys } from \"../runnables/config.js\";\nimport { raceWithSignal } from \"./signal.js\";\n\n//#region src/utils/stream.ts\nvar stream_exports = {};\n__export(stream_exports, {\n\tAsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup,\n\tIterableReadableStream: () => IterableReadableStream,\n\tatee: () => atee,\n\tconcat: () => concat,\n\tpipeGeneratorWithSetup: () => pipeGeneratorWithSetup\n});\nvar IterableReadableStream = class IterableReadableStream extends ReadableStream {\n\treader;\n\tensureReader() {\n\t\tif (!this.reader) this.reader = this.getReader();\n\t}\n\tasync next() {\n\t\tthis.ensureReader();\n\t\ttry {\n\t\t\tconst result = await this.reader.read();\n\t\t\tif (result.done) {\n\t\t\t\tthis.reader.releaseLock();\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t} else return {\n\t\t\t\tdone: false,\n\t\t\t\tvalue: result.value\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tthis.reader.releaseLock();\n\t\t\tthrow e;\n\t\t}\n\t}\n\tasync return() {\n\t\tthis.ensureReader();\n\t\tif (this.locked) {\n\t\t\tconst cancelPromise = this.reader.cancel();\n\t\t\tthis.reader.releaseLock();\n\t\t\tawait cancelPromise;\n\t\t}\n\t\treturn {\n\t\t\tdone: true,\n\t\t\tvalue: void 0\n\t\t};\n\t}\n\tasync throw(e) {\n\t\tthis.ensureReader();\n\t\tif (this.locked) {\n\t\t\tconst cancelPromise = this.reader.cancel();\n\t\t\tthis.reader.releaseLock();\n\t\t\tawait cancelPromise;\n\t\t}\n\t\tthrow e;\n\t}\n\t[Symbol.asyncIterator]() {\n\t\treturn this;\n\t}\n\tasync [Symbol.asyncDispose]() {\n\t\tawait this.return();\n\t}\n\tstatic fromReadableStream(stream) {\n\t\tconst reader = stream.getReader();\n\t\treturn new IterableReadableStream({\n\t\t\tstart(controller) {\n\t\t\t\treturn pump();\n\t\t\t\tfunction pump() {\n\t\t\t\t\treturn reader.read().then(({ done, value }) => {\n\t\t\t\t\t\tif (done) {\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\t\treturn pump();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel() {\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\t\t});\n\t}\n\tstatic fromAsyncGenerator(generator) {\n\t\treturn new IterableReadableStream({\n\t\t\tasync pull(controller) {\n\t\t\t\tconst { value, done } = await generator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\tcontroller.enqueue(value);\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\tawait generator.return(reason);\n\t\t\t}\n\t\t});\n\t}\n};\nfunction atee(iter, length = 2) {\n\tconst buffers = Array.from({ length }, () => []);\n\treturn buffers.map(async function* makeIter(buffer) {\n\t\twhile (true) if (buffer.length === 0) {\n\t\t\tconst result = await iter.next();\n\t\t\tfor (const buffer$1 of buffers) buffer$1.push(result);\n\t\t} else if (buffer[0].done) return;\n\t\telse yield buffer.shift().value;\n\t});\n}\nfunction concat(first, second) {\n\tif (Array.isArray(first) && Array.isArray(second)) return first.concat(second);\n\telse if (typeof first === \"string\" && typeof second === \"string\") return first + second;\n\telse if (typeof first === \"number\" && typeof second === \"number\") return first + second;\n\telse if (\"concat\" in first && typeof first.concat === \"function\") return first.concat(second);\n\telse if (typeof first === \"object\" && typeof second === \"object\") {\n\t\tconst chunk = { ...first };\n\t\tfor (const [key, value] of Object.entries(second)) if (key in chunk && !Array.isArray(chunk[key])) chunk[key] = concat(chunk[key], value);\n\t\telse chunk[key] = value;\n\t\treturn chunk;\n\t} else throw new Error(`Cannot concat ${typeof first} and ${typeof second}`);\n}\nvar AsyncGeneratorWithSetup = class {\n\tgenerator;\n\tsetup;\n\tconfig;\n\tsignal;\n\tfirstResult;\n\tfirstResultUsed = false;\n\tconstructor(params) {\n\t\tthis.generator = params.generator;\n\t\tthis.config = params.config;\n\t\tthis.signal = params.signal ?? this.config?.signal;\n\t\tthis.setup = new Promise((resolve, reject) => {\n\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => {\n\t\t\t\tthis.firstResult = params.generator.next();\n\t\t\t\tif (params.startSetup) this.firstResult.then(params.startSetup).then(resolve, reject);\n\t\t\t\telse this.firstResult.then((_result) => resolve(void 0), reject);\n\t\t\t}, true);\n\t\t});\n\t}\n\tasync next(...args) {\n\t\tthis.signal?.throwIfAborted();\n\t\tif (!this.firstResultUsed) {\n\t\t\tthis.firstResultUsed = true;\n\t\t\treturn this.firstResult;\n\t\t}\n\t\treturn AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal ? async () => {\n\t\t\treturn raceWithSignal(this.generator.next(...args), this.signal);\n\t\t} : async () => {\n\t\t\treturn this.generator.next(...args);\n\t\t}, true);\n\t}\n\tasync return(value) {\n\t\treturn this.generator.return(value);\n\t}\n\tasync throw(e) {\n\t\treturn this.generator.throw(e);\n\t}\n\t[Symbol.asyncIterator]() {\n\t\treturn this;\n\t}\n\tasync [Symbol.asyncDispose]() {\n\t\tawait this.return();\n\t}\n};\nasync function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) {\n\tconst gen = new AsyncGeneratorWithSetup({\n\t\tgenerator,\n\t\tstartSetup,\n\t\tsignal\n\t});\n\tconst setup = await gen.setup;\n\treturn {\n\t\toutput: to(gen, setup, ...args),\n\t\tsetup\n\t};\n}\n\n//#endregion\nexport { AsyncGeneratorWithSetup, IterableReadableStream, atee, concat, pipeGeneratorWithSetup, stream_exports };\n//# sourceMappingURL=stream.js.map","//#region src/utils/fast-json-patch/src/helpers.ts\n/*!\n* https://github.com/Starcounter-Jack/JSON-Patch\n* (c) 2017-2022 Joachim Wester\n* MIT licensed\n*/\nconst _hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction hasOwnProperty(obj, key) {\n\treturn _hasOwnProperty.call(obj, key);\n}\nfunction _objectKeys(obj) {\n\tif (Array.isArray(obj)) {\n\t\tconst keys$1 = new Array(obj.length);\n\t\tfor (let k = 0; k < keys$1.length; k++) keys$1[k] = \"\" + k;\n\t\treturn keys$1;\n\t}\n\tif (Object.keys) return Object.keys(obj);\n\tlet keys = [];\n\tfor (let i in obj) if (hasOwnProperty(obj, i)) keys.push(i);\n\treturn keys;\n}\n/**\n* Deeply clone the object.\n* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)\n* @param {any} obj value to clone\n* @return {any} cloned obj\n*/\nfunction _deepClone(obj) {\n\tswitch (typeof obj) {\n\t\tcase \"object\": return JSON.parse(JSON.stringify(obj));\n\t\tcase \"undefined\": return null;\n\t\tdefault: return obj;\n\t}\n}\nfunction isInteger(str) {\n\tlet i = 0;\n\tconst len = str.length;\n\tlet charCode;\n\twhile (i < len) {\n\t\tcharCode = str.charCodeAt(i);\n\t\tif (charCode >= 48 && charCode <= 57) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn false;\n\t}\n\treturn true;\n}\n/**\n* Escapes a json pointer path\n* @param path The raw pointer\n* @return the Escaped path\n*/\nfunction escapePathComponent(path) {\n\tif (path.indexOf(\"/\") === -1 && path.indexOf(\"~\") === -1) return path;\n\treturn path.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n/**\n* Unescapes a json pointer path\n* @param path The escaped pointer\n* @return The unescaped path\n*/\nfunction unescapePathComponent(path) {\n\treturn path.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n/**\n* Recursively checks whether an object has any undefined values inside.\n*/\nfunction hasUndefined(obj) {\n\tif (obj === void 0) return true;\n\tif (obj) {\n\t\tif (Array.isArray(obj)) {\n\t\t\tfor (let i$1 = 0, len = obj.length; i$1 < len; i$1++) if (hasUndefined(obj[i$1])) return true;\n\t\t} else if (typeof obj === \"object\") {\n\t\t\tconst objKeys = _objectKeys(obj);\n\t\t\tconst objKeysLength = objKeys.length;\n\t\t\tfor (var i = 0; i < objKeysLength; i++) if (hasUndefined(obj[objKeys[i]])) return true;\n\t\t}\n\t}\n\treturn false;\n}\nfunction patchErrorMessageFormatter(message, args) {\n\tconst messageParts = [message];\n\tfor (const key in args) {\n\t\tconst value = typeof args[key] === \"object\" ? JSON.stringify(args[key], null, 2) : args[key];\n\t\tif (typeof value !== \"undefined\") messageParts.push(`${key}: ${value}`);\n\t}\n\treturn messageParts.join(\"\\n\");\n}\nvar PatchError = class extends Error {\n\tconstructor(message, name, index, operation, tree) {\n\t\tsuper(patchErrorMessageFormatter(message, {\n\t\t\tname,\n\t\t\tindex,\n\t\t\toperation,\n\t\t\ttree\n\t\t}));\n\t\tthis.name = name;\n\t\tthis.index = index;\n\t\tthis.operation = operation;\n\t\tthis.tree = tree;\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t\tthis.message = patchErrorMessageFormatter(message, {\n\t\t\tname,\n\t\t\tindex,\n\t\t\toperation,\n\t\t\ttree\n\t\t});\n\t}\n};\n\n//#endregion\nexport { PatchError, _deepClone, _objectKeys, escapePathComponent, hasOwnProperty, hasUndefined, isInteger, unescapePathComponent };\n//# sourceMappingURL=helpers.js.map","import { __export } from \"../../../_virtual/rolldown_runtime.js\";\nimport { PatchError, _deepClone, hasUndefined, isInteger, unescapePathComponent } from \"./helpers.js\";\n\n//#region src/utils/fast-json-patch/src/core.ts\nvar core_exports = {};\n__export(core_exports, {\n\tJsonPatchError: () => JsonPatchError,\n\t_areEquals: () => _areEquals,\n\tapplyOperation: () => applyOperation,\n\tapplyPatch: () => applyPatch,\n\tapplyReducer: () => applyReducer,\n\tdeepClone: () => deepClone,\n\tgetValueByPointer: () => getValueByPointer,\n\tvalidate: () => validate,\n\tvalidator: () => validator\n});\nconst JsonPatchError = PatchError;\nconst deepClone = _deepClone;\nconst objOps = {\n\tadd: function(obj, key, document) {\n\t\tobj[key] = this.value;\n\t\treturn { newDocument: document };\n\t},\n\tremove: function(obj, key, document) {\n\t\tvar removed = obj[key];\n\t\tdelete obj[key];\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\tremoved\n\t\t};\n\t},\n\treplace: function(obj, key, document) {\n\t\tvar removed = obj[key];\n\t\tobj[key] = this.value;\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\tremoved\n\t\t};\n\t},\n\tmove: function(obj, key, document) {\n\t\tlet removed = getValueByPointer(document, this.path);\n\t\tif (removed) removed = _deepClone(removed);\n\t\tconst originalValue = applyOperation(document, {\n\t\t\top: \"remove\",\n\t\t\tpath: this.from\n\t\t}).removed;\n\t\tapplyOperation(document, {\n\t\t\top: \"add\",\n\t\t\tpath: this.path,\n\t\t\tvalue: originalValue\n\t\t});\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\tremoved\n\t\t};\n\t},\n\tcopy: function(obj, key, document) {\n\t\tconst valueToCopy = getValueByPointer(document, this.from);\n\t\tapplyOperation(document, {\n\t\t\top: \"add\",\n\t\t\tpath: this.path,\n\t\t\tvalue: _deepClone(valueToCopy)\n\t\t});\n\t\treturn { newDocument: document };\n\t},\n\ttest: function(obj, key, document) {\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\ttest: _areEquals(obj[key], this.value)\n\t\t};\n\t},\n\t_get: function(obj, key, document) {\n\t\tthis.value = obj[key];\n\t\treturn { newDocument: document };\n\t}\n};\nvar arrOps = {\n\tadd: function(arr, i, document) {\n\t\tif (isInteger(i)) arr.splice(i, 0, this.value);\n\t\telse arr[i] = this.value;\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\tindex: i\n\t\t};\n\t},\n\tremove: function(arr, i, document) {\n\t\tvar removedList = arr.splice(i, 1);\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\tremoved: removedList[0]\n\t\t};\n\t},\n\treplace: function(arr, i, document) {\n\t\tvar removed = arr[i];\n\t\tarr[i] = this.value;\n\t\treturn {\n\t\t\tnewDocument: document,\n\t\t\tremoved\n\t\t};\n\t},\n\tmove: objOps.move,\n\tcopy: objOps.copy,\n\ttest: objOps.test,\n\t_get: objOps._get\n};\n/**\n* Retrieves a value from a JSON document by a JSON pointer.\n* Returns the value.\n*\n* @param document The document to get the value from\n* @param pointer an escaped JSON pointer\n* @return The retrieved value\n*/\nfunction getValueByPointer(document, pointer) {\n\tif (pointer == \"\") return document;\n\tvar getOriginalDestination = {\n\t\top: \"_get\",\n\t\tpath: pointer\n\t};\n\tapplyOperation(document, getOriginalDestination);\n\treturn getOriginalDestination.value;\n}\n/**\n* Apply a single JSON Patch Operation on a JSON document.\n* Returns the {newDocument, result} of the operation.\n* It modifies the `document` and `operation` objects - it gets the values by reference.\n* If you would like to avoid touching your values, clone them:\n* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n*\n* @param document The document to patch\n* @param operation The operation to apply\n* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n* @param mutateDocument Whether to mutate the original document or clone it before applying\n* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n* @return `{newDocument, result}` after the operation\n*/\nfunction applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) {\n\tif (validateOperation) if (typeof validateOperation == \"function\") validateOperation(operation, 0, document, operation.path);\n\telse validator(operation, 0);\n\tif (operation.path === \"\") {\n\t\tlet returnValue = { newDocument: document };\n\t\tif (operation.op === \"add\") {\n\t\t\treturnValue.newDocument = operation.value;\n\t\t\treturn returnValue;\n\t\t} else if (operation.op === \"replace\") {\n\t\t\treturnValue.newDocument = operation.value;\n\t\t\treturnValue.removed = document;\n\t\t\treturn returnValue;\n\t\t} else if (operation.op === \"move\" || operation.op === \"copy\") {\n\t\t\treturnValue.newDocument = getValueByPointer(document, operation.from);\n\t\t\tif (operation.op === \"move\") returnValue.removed = document;\n\t\t\treturn returnValue;\n\t\t} else if (operation.op === \"test\") {\n\t\t\treturnValue.test = _areEquals(document, operation.value);\n\t\t\tif (returnValue.test === false) throw new JsonPatchError(\"Test operation failed\", \"TEST_OPERATION_FAILED\", index, operation, document);\n\t\t\treturnValue.newDocument = document;\n\t\t\treturn returnValue;\n\t\t} else if (operation.op === \"remove\") {\n\t\t\treturnValue.removed = document;\n\t\t\treturnValue.newDocument = null;\n\t\t\treturn returnValue;\n\t\t} else if (operation.op === \"_get\") {\n\t\t\toperation.value = document;\n\t\t\treturn returnValue;\n\t\t} else if (validateOperation) throw new JsonPatchError(\"Operation `op` property is not one of operations defined in RFC-6902\", \"OPERATION_OP_INVALID\", index, operation, document);\n\t\telse return returnValue;\n\t} else {\n\t\tif (!mutateDocument) document = _deepClone(document);\n\t\tconst path = operation.path || \"\";\n\t\tconst keys = path.split(\"/\");\n\t\tlet obj = document;\n\t\tlet t = 1;\n\t\tlet len = keys.length;\n\t\tlet existingPathFragment = void 0;\n\t\tlet key;\n\t\tlet validateFunction;\n\t\tif (typeof validateOperation == \"function\") validateFunction = validateOperation;\n\t\telse validateFunction = validator;\n\t\twhile (true) {\n\t\t\tkey = keys[t];\n\t\t\tif (key && key.indexOf(\"~\") != -1) key = unescapePathComponent(key);\n\t\t\tif (banPrototypeModifications && (key == \"__proto__\" || key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\")) throw new TypeError(\"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\");\n\t\t\tif (validateOperation) {\n\t\t\t\tif (existingPathFragment === void 0) {\n\t\t\t\t\tif (obj[key] === void 0) existingPathFragment = keys.slice(0, t).join(\"/\");\n\t\t\t\t\telse if (t == len - 1) existingPathFragment = operation.path;\n\t\t\t\t\tif (existingPathFragment !== void 0) validateFunction(operation, 0, document, existingPathFragment);\n\t\t\t\t}\n\t\t\t}\n\t\t\tt++;\n\t\t\tif (Array.isArray(obj)) {\n\t\t\t\tif (key === \"-\") key = obj.length;\n\t\t\t\telse if (validateOperation && !isInteger(key)) throw new JsonPatchError(\"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\", \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\", index, operation, document);\n\t\t\t\telse if (isInteger(key)) key = ~~key;\n\t\t\t\tif (t >= len) {\n\t\t\t\t\tif (validateOperation && operation.op === \"add\" && key > obj.length) throw new JsonPatchError(\"The specified index MUST NOT be greater than the number of elements in the array\", \"OPERATION_VALUE_OUT_OF_BOUNDS\", index, operation, document);\n\t\t\t\t\tconst returnValue = arrOps[operation.op].call(operation, obj, key, document);\n\t\t\t\t\tif (returnValue.test === false) throw new JsonPatchError(\"Test operation failed\", \"TEST_OPERATION_FAILED\", index, operation, document);\n\t\t\t\t\treturn returnValue;\n\t\t\t\t}\n\t\t\t} else if (t >= len) {\n\t\t\t\tconst returnValue = objOps[operation.op].call(operation, obj, key, document);\n\t\t\t\tif (returnValue.test === false) throw new JsonPatchError(\"Test operation failed\", \"TEST_OPERATION_FAILED\", index, operation, document);\n\t\t\t\treturn returnValue;\n\t\t\t}\n\t\t\tobj = obj[key];\n\t\t\tif (validateOperation && t < len && (!obj || typeof obj !== \"object\")) throw new JsonPatchError(\"Cannot perform operation at the desired path\", \"OPERATION_PATH_UNRESOLVABLE\", index, operation, document);\n\t\t}\n\t}\n}\n/**\n* Apply a full JSON Patch array on a JSON document.\n* Returns the {newDocument, result} of the patch.\n* It modifies the `document` object and `patch` - it gets the values by reference.\n* If you would like to avoid touching your values, clone them:\n* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n*\n* @param document The document to patch\n* @param patch The patch to apply\n* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n* @param mutateDocument Whether to mutate the original document or clone it before applying\n* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n* @return An array of `{newDocument, result}` after the patch\n*/\nfunction applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) {\n\tif (validateOperation) {\n\t\tif (!Array.isArray(patch)) throw new JsonPatchError(\"Patch sequence must be an array\", \"SEQUENCE_NOT_AN_ARRAY\");\n\t}\n\tif (!mutateDocument) document = _deepClone(document);\n\tconst results = new Array(patch.length);\n\tfor (let i = 0, length = patch.length; i < length; i++) {\n\t\tresults[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);\n\t\tdocument = results[i].newDocument;\n\t}\n\tresults.newDocument = document;\n\treturn results;\n}\n/**\n* Apply a single JSON Patch Operation on a JSON document.\n* Returns the updated document.\n* Suitable as a reducer.\n*\n* @param document The document to patch\n* @param operation The operation to apply\n* @return The updated document\n*/\nfunction applyReducer(document, operation, index) {\n\tconst operationResult = applyOperation(document, operation);\n\tif (operationResult.test === false) throw new JsonPatchError(\"Test operation failed\", \"TEST_OPERATION_FAILED\", index, operation, document);\n\treturn operationResult.newDocument;\n}\n/**\n* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n* @param {object} operation - operation object (patch)\n* @param {number} index - index of operation in the sequence\n* @param {object} [document] - object where the operation is supposed to be applied\n* @param {string} [existingPathFragment] - comes along with `document`\n*/\nfunction validator(operation, index, document, existingPathFragment) {\n\tif (typeof operation !== \"object\" || operation === null || Array.isArray(operation)) throw new JsonPatchError(\"Operation is not an object\", \"OPERATION_NOT_AN_OBJECT\", index, operation, document);\n\telse if (!objOps[operation.op]) throw new JsonPatchError(\"Operation `op` property is not one of operations defined in RFC-6902\", \"OPERATION_OP_INVALID\", index, operation, document);\n\telse if (typeof operation.path !== \"string\") throw new JsonPatchError(\"Operation `path` property is not a string\", \"OPERATION_PATH_INVALID\", index, operation, document);\n\telse if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) throw new JsonPatchError(\"Operation `path` property must start with \\\"/\\\"\", \"OPERATION_PATH_INVALID\", index, operation, document);\n\telse if ((operation.op === \"move\" || operation.op === \"copy\") && typeof operation.from !== \"string\") throw new JsonPatchError(\"Operation `from` property is not present (applicable in `move` and `copy` operations)\", \"OPERATION_FROM_REQUIRED\", index, operation, document);\n\telse if ((operation.op === \"add\" || operation.op === \"replace\" || operation.op === \"test\") && operation.value === void 0) throw new JsonPatchError(\"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\", \"OPERATION_VALUE_REQUIRED\", index, operation, document);\n\telse if ((operation.op === \"add\" || operation.op === \"replace\" || operation.op === \"test\") && hasUndefined(operation.value)) throw new JsonPatchError(\"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\", \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\", index, operation, document);\n\telse if (document) {\n\t\tif (operation.op == \"add\") {\n\t\t\tvar pathLen = operation.path.split(\"/\").length;\n\t\t\tvar existingPathLen = existingPathFragment.split(\"/\").length;\n\t\t\tif (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) throw new JsonPatchError(\"Cannot perform an `add` operation at the desired path\", \"OPERATION_PATH_CANNOT_ADD\", index, operation, document);\n\t\t} else if (operation.op === \"replace\" || operation.op === \"remove\" || operation.op === \"_get\") {\n\t\t\tif (operation.path !== existingPathFragment) throw new JsonPatchError(\"Cannot perform the operation at a path that does not exist\", \"OPERATION_PATH_UNRESOLVABLE\", index, operation, document);\n\t\t} else if (operation.op === \"move\" || operation.op === \"copy\") {\n\t\t\tvar existingValue = {\n\t\t\t\top: \"_get\",\n\t\t\t\tpath: operation.from,\n\t\t\t\tvalue: void 0\n\t\t\t};\n\t\t\tvar error = validate([existingValue], document);\n\t\t\tif (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") throw new JsonPatchError(\"Cannot perform the operation from a path that does not exist\", \"OPERATION_FROM_UNRESOLVABLE\", index, operation, document);\n\t\t}\n\t}\n}\n/**\n* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n* If error is encountered, returns a JsonPatchError object\n* @param sequence\n* @param document\n* @returns {JsonPatchError|undefined}\n*/\nfunction validate(sequence, document, externalValidator) {\n\ttry {\n\t\tif (!Array.isArray(sequence)) throw new JsonPatchError(\"Patch sequence must be an array\", \"SEQUENCE_NOT_AN_ARRAY\");\n\t\tif (document) applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true);\n\t\telse {\n\t\t\texternalValidator = externalValidator || validator;\n\t\t\tfor (var i = 0; i < sequence.length; i++) externalValidator(sequence[i], i, document, void 0);\n\t\t}\n\t} catch (e) {\n\t\tif (e instanceof JsonPatchError) return e;\n\t\telse throw e;\n\t}\n}\nfunction _areEquals(a, b) {\n\tif (a === b) return true;\n\tif (a && b && typeof a == \"object\" && typeof b == \"object\") {\n\t\tvar arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;\n\t\tif (arrA && arrB) {\n\t\t\tlength = a.length;\n\t\t\tif (length != b.length) return false;\n\t\t\tfor (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false;\n\t\t\treturn true;\n\t\t}\n\t\tif (arrA != arrB) return false;\n\t\tvar keys = Object.keys(a);\n\t\tlength = keys.length;\n\t\tif (length !== Object.keys(b).length) return false;\n\t\tfor (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false;\n\t\tfor (i = length; i-- !== 0;) {\n\t\t\tkey = keys[i];\n\t\t\tif (!_areEquals(a[key], b[key])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn a !== a && b !== b;\n}\n\n//#endregion\nexport { _areEquals, applyOperation, applyPatch, applyReducer, core_exports, getValueByPointer, validate, validator };\n//# sourceMappingURL=core.js.map","import { _deepClone, _objectKeys, escapePathComponent, hasOwnProperty } from \"./helpers.js\";\nimport \"./core.js\";\n\n//#region src/utils/fast-json-patch/src/duplex.ts\nfunction _generate(mirror, obj, patches, path, invertible) {\n\tif (obj === mirror) return;\n\tif (typeof obj.toJSON === \"function\") obj = obj.toJSON();\n\tvar newKeys = _objectKeys(obj);\n\tvar oldKeys = _objectKeys(mirror);\n\tvar changed = false;\n\tvar deleted = false;\n\tfor (var t = oldKeys.length - 1; t >= 0; t--) {\n\t\tvar key = oldKeys[t];\n\t\tvar oldVal = mirror[key];\n\t\tif (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) {\n\t\t\tvar newVal = obj[key];\n\t\t\tif (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) _generate(oldVal, newVal, patches, path + \"/\" + escapePathComponent(key), invertible);\n\t\t\telse if (oldVal !== newVal) {\n\t\t\t\tchanged = true;\n\t\t\t\tif (invertible) patches.push({\n\t\t\t\t\top: \"test\",\n\t\t\t\t\tpath: path + \"/\" + escapePathComponent(key),\n\t\t\t\t\tvalue: _deepClone(oldVal)\n\t\t\t\t});\n\t\t\t\tpatches.push({\n\t\t\t\t\top: \"replace\",\n\t\t\t\t\tpath: path + \"/\" + escapePathComponent(key),\n\t\t\t\t\tvalue: _deepClone(newVal)\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (Array.isArray(mirror) === Array.isArray(obj)) {\n\t\t\tif (invertible) patches.push({\n\t\t\t\top: \"test\",\n\t\t\t\tpath: path + \"/\" + escapePathComponent(key),\n\t\t\t\tvalue: _deepClone(oldVal)\n\t\t\t});\n\t\t\tpatches.push({\n\t\t\t\top: \"remove\",\n\t\t\t\tpath: path + \"/\" + escapePathComponent(key)\n\t\t\t});\n\t\t\tdeleted = true;\n\t\t} else {\n\t\t\tif (invertible) patches.push({\n\t\t\t\top: \"test\",\n\t\t\t\tpath,\n\t\t\t\tvalue: mirror\n\t\t\t});\n\t\t\tpatches.push({\n\t\t\t\top: \"replace\",\n\t\t\t\tpath,\n\t\t\t\tvalue: obj\n\t\t\t});\n\t\t\tchanged = true;\n\t\t}\n\t}\n\tif (!deleted && newKeys.length == oldKeys.length) return;\n\tfor (var t = 0; t < newKeys.length; t++) {\n\t\tvar key = newKeys[t];\n\t\tif (!hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({\n\t\t\top: \"add\",\n\t\t\tpath: path + \"/\" + escapePathComponent(key),\n\t\t\tvalue: _deepClone(obj[key])\n\t\t});\n\t}\n}\n/**\n* Create an array of patches from the differences in two objects\n*/\nfunction compare(tree1, tree2, invertible = false) {\n\tvar patches = [];\n\t_generate(tree1, tree2, patches, \"\", invertible);\n\treturn patches;\n}\n\n//#endregion\nexport { compare };\n//# sourceMappingURL=duplex.js.map","import { PatchError, _deepClone, escapePathComponent, unescapePathComponent } from \"./src/helpers.js\";\nimport { _areEquals, applyOperation, applyPatch, applyReducer, core_exports, getValueByPointer, validate, validator } from \"./src/core.js\";\nimport { compare } from \"./src/duplex.js\";\n\n//#region src/utils/fast-json-patch/index.ts\nvar fast_json_patch_default = {\n\t...core_exports,\n\tJsonPatchError: PatchError,\n\tdeepClone: _deepClone,\n\tescapePathComponent,\n\tunescapePathComponent\n};\n\n//#endregion\n//# sourceMappingURL=index.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { applyPatch } from \"../utils/fast-json-patch/src/core.js\";\nimport \"../utils/fast-json-patch/index.js\";\nimport { BaseTracer } from \"./base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n\n//#region src/tracers/log_stream.ts\nvar log_stream_exports = {};\n__export(log_stream_exports, {\n\tLogStreamCallbackHandler: () => LogStreamCallbackHandler,\n\tRunLog: () => RunLog,\n\tRunLogPatch: () => RunLogPatch,\n\tisLogStreamHandler: () => isLogStreamHandler\n});\n/**\n* List of jsonpatch JSONPatchOperations, which describe how to create the run state\n* from an empty dict. This is the minimal representation of the log, designed to\n* be serialized as JSON and sent over the wire to reconstruct the log on the other\n* side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n* see https://jsonpatch.com for more information.\n*/\nvar RunLogPatch = class {\n\tops;\n\tconstructor(fields) {\n\t\tthis.ops = fields.ops ?? [];\n\t}\n\tconcat(other) {\n\t\tconst ops = this.ops.concat(other.ops);\n\t\tconst states = applyPatch({}, ops);\n\t\treturn new RunLog({\n\t\t\tops,\n\t\t\tstate: states[states.length - 1].newDocument\n\t\t});\n\t}\n};\nvar RunLog = class RunLog extends RunLogPatch {\n\tstate;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.state = fields.state;\n\t}\n\tconcat(other) {\n\t\tconst ops = this.ops.concat(other.ops);\n\t\tconst states = applyPatch(this.state, other.ops);\n\t\treturn new RunLog({\n\t\t\tops,\n\t\t\tstate: states[states.length - 1].newDocument\n\t\t});\n\t}\n\tstatic fromRunLogPatch(patch) {\n\t\tconst states = applyPatch({}, patch.ops);\n\t\treturn new RunLog({\n\t\t\tops: patch.ops,\n\t\t\tstate: states[states.length - 1].newDocument\n\t\t});\n\t}\n};\nconst isLogStreamHandler = (handler) => handler.name === \"log_stream_tracer\";\n/**\n* Extract standardized inputs from a run.\n*\n* Standardizes the inputs based on the type of the runnable used.\n*\n* @param run - Run object\n* @param schemaFormat - The schema format to use.\n*\n* @returns Valid inputs are only dict. By conventions, inputs always represented\n* invocation using named arguments.\n* A null means that the input is not yet known!\n*/\nasync function _getStandardizedInputs(run, schemaFormat) {\n\tif (schemaFormat === \"original\") throw new Error(\"Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.\");\n\tconst { inputs } = run;\n\tif ([\n\t\t\"retriever\",\n\t\t\"llm\",\n\t\t\"prompt\"\n\t].includes(run.run_type)) return inputs;\n\tif (Object.keys(inputs).length === 1 && inputs?.input === \"\") return void 0;\n\treturn inputs.input;\n}\nasync function _getStandardizedOutputs(run, schemaFormat) {\n\tconst { outputs } = run;\n\tif (schemaFormat === \"original\") return outputs;\n\tif ([\n\t\t\"retriever\",\n\t\t\"llm\",\n\t\t\"prompt\"\n\t].includes(run.run_type)) return outputs;\n\tif (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) return outputs.output;\n\treturn outputs;\n}\nfunction isChatGenerationChunk(x) {\n\treturn x !== void 0 && x.message !== void 0;\n}\n/**\n* Class that extends the `BaseTracer` class from the\n* `langchain.callbacks.tracers.base` module. It represents a callback\n* handler that logs the execution of runs and emits `RunLog` instances to a\n* `RunLogStream`.\n*/\nvar LogStreamCallbackHandler = class extends BaseTracer {\n\tautoClose = true;\n\tincludeNames;\n\tincludeTypes;\n\tincludeTags;\n\texcludeNames;\n\texcludeTypes;\n\texcludeTags;\n\t_schemaFormat = \"original\";\n\trootId;\n\tkeyMapByRunId = {};\n\tcounterMapByRunName = {};\n\ttransformStream;\n\twriter;\n\treceiveStream;\n\tname = \"log_stream_tracer\";\n\tlc_prefer_streaming = true;\n\tconstructor(fields) {\n\t\tsuper({\n\t\t\t_awaitHandler: true,\n\t\t\t...fields\n\t\t});\n\t\tthis.autoClose = fields?.autoClose ?? true;\n\t\tthis.includeNames = fields?.includeNames;\n\t\tthis.includeTypes = fields?.includeTypes;\n\t\tthis.includeTags = fields?.includeTags;\n\t\tthis.excludeNames = fields?.excludeNames;\n\t\tthis.excludeTypes = fields?.excludeTypes;\n\t\tthis.excludeTags = fields?.excludeTags;\n\t\tthis._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;\n\t\tthis.transformStream = new TransformStream();\n\t\tthis.writer = this.transformStream.writable.getWriter();\n\t\tthis.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);\n\t}\n\t[Symbol.asyncIterator]() {\n\t\treturn this.receiveStream;\n\t}\n\tasync persistRun(_run) {}\n\t_includeRun(run) {\n\t\tif (run.id === this.rootId) return false;\n\t\tconst runTags = run.tags ?? [];\n\t\tlet include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0;\n\t\tif (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name);\n\t\tif (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.run_type);\n\t\tif (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0;\n\t\tif (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name);\n\t\tif (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.run_type);\n\t\tif (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n\t\treturn include;\n\t}\n\tasync *tapOutputIterable(runId, output) {\n\t\tfor await (const chunk of output) {\n\t\t\tif (runId !== this.rootId) {\n\t\t\t\tconst key = this.keyMapByRunId[runId];\n\t\t\t\tif (key) await this.writer.write(new RunLogPatch({ ops: [{\n\t\t\t\t\top: \"add\",\n\t\t\t\t\tpath: `/logs/${key}/streamed_output/-`,\n\t\t\t\t\tvalue: chunk\n\t\t\t\t}] }));\n\t\t\t}\n\t\t\tyield chunk;\n\t\t}\n\t}\n\tasync onRunCreate(run) {\n\t\tif (this.rootId === void 0) {\n\t\t\tthis.rootId = run.id;\n\t\t\tawait this.writer.write(new RunLogPatch({ ops: [{\n\t\t\t\top: \"replace\",\n\t\t\t\tpath: \"\",\n\t\t\t\tvalue: {\n\t\t\t\t\tid: run.id,\n\t\t\t\t\tname: run.name,\n\t\t\t\t\ttype: run.run_type,\n\t\t\t\t\tstreamed_output: [],\n\t\t\t\t\tfinal_output: void 0,\n\t\t\t\t\tlogs: {}\n\t\t\t\t}\n\t\t\t}] }));\n\t\t}\n\t\tif (!this._includeRun(run)) return;\n\t\tif (this.counterMapByRunName[run.name] === void 0) this.counterMapByRunName[run.name] = 0;\n\t\tthis.counterMapByRunName[run.name] += 1;\n\t\tconst count = this.counterMapByRunName[run.name];\n\t\tthis.keyMapByRunId[run.id] = count === 1 ? run.name : `${run.name}:${count}`;\n\t\tconst logEntry = {\n\t\t\tid: run.id,\n\t\t\tname: run.name,\n\t\t\ttype: run.run_type,\n\t\t\ttags: run.tags ?? [],\n\t\t\tmetadata: run.extra?.metadata ?? {},\n\t\t\tstart_time: new Date(run.start_time).toISOString(),\n\t\t\tstreamed_output: [],\n\t\t\tstreamed_output_str: [],\n\t\t\tfinal_output: void 0,\n\t\t\tend_time: void 0\n\t\t};\n\t\tif (this._schemaFormat === \"streaming_events\") logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);\n\t\tawait this.writer.write(new RunLogPatch({ ops: [{\n\t\t\top: \"add\",\n\t\t\tpath: `/logs/${this.keyMapByRunId[run.id]}`,\n\t\t\tvalue: logEntry\n\t\t}] }));\n\t}\n\tasync onRunUpdate(run) {\n\t\ttry {\n\t\t\tconst runName = this.keyMapByRunId[run.id];\n\t\t\tif (runName === void 0) return;\n\t\t\tconst ops = [];\n\t\t\tif (this._schemaFormat === \"streaming_events\") ops.push({\n\t\t\t\top: \"replace\",\n\t\t\t\tpath: `/logs/${runName}/inputs`,\n\t\t\t\tvalue: await _getStandardizedInputs(run, this._schemaFormat)\n\t\t\t});\n\t\t\tops.push({\n\t\t\t\top: \"add\",\n\t\t\t\tpath: `/logs/${runName}/final_output`,\n\t\t\t\tvalue: await _getStandardizedOutputs(run, this._schemaFormat)\n\t\t\t});\n\t\t\tif (run.end_time !== void 0) ops.push({\n\t\t\t\top: \"add\",\n\t\t\t\tpath: `/logs/${runName}/end_time`,\n\t\t\t\tvalue: new Date(run.end_time).toISOString()\n\t\t\t});\n\t\t\tconst patch = new RunLogPatch({ ops });\n\t\t\tawait this.writer.write(patch);\n\t\t} finally {\n\t\t\tif (run.id === this.rootId) {\n\t\t\t\tconst patch = new RunLogPatch({ ops: [{\n\t\t\t\t\top: \"replace\",\n\t\t\t\t\tpath: \"/final_output\",\n\t\t\t\t\tvalue: await _getStandardizedOutputs(run, this._schemaFormat)\n\t\t\t\t}] });\n\t\t\t\tawait this.writer.write(patch);\n\t\t\t\tif (this.autoClose) await this.writer.close();\n\t\t\t}\n\t\t}\n\t}\n\tasync onLLMNewToken(run, token, kwargs) {\n\t\tconst runName = this.keyMapByRunId[run.id];\n\t\tif (runName === void 0) return;\n\t\tconst isChatModel = run.inputs.messages !== void 0;\n\t\tlet streamedOutputValue;\n\t\tif (isChatModel) if (isChatGenerationChunk(kwargs?.chunk)) streamedOutputValue = kwargs?.chunk;\n\t\telse streamedOutputValue = new AIMessageChunk({\n\t\t\tid: `run-${run.id}`,\n\t\t\tcontent: token\n\t\t});\n\t\telse streamedOutputValue = token;\n\t\tconst patch = new RunLogPatch({ ops: [{\n\t\t\top: \"add\",\n\t\t\tpath: `/logs/${runName}/streamed_output_str/-`,\n\t\t\tvalue: token\n\t\t}, {\n\t\t\top: \"add\",\n\t\t\tpath: `/logs/${runName}/streamed_output/-`,\n\t\t\tvalue: streamedOutputValue\n\t\t}] });\n\t\tawait this.writer.write(patch);\n\t}\n};\n\n//#endregion\nexport { LogStreamCallbackHandler, RunLog, RunLogPatch, isLogStreamHandler, log_stream_exports };\n//# sourceMappingURL=log_stream.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\n\n//#region src/outputs.ts\nvar outputs_exports = {};\n__export(outputs_exports, {\n\tChatGenerationChunk: () => ChatGenerationChunk,\n\tGenerationChunk: () => GenerationChunk,\n\tRUN_KEY: () => RUN_KEY\n});\nconst RUN_KEY = \"__run\";\n/**\n* Chunk of a single generation. Used for streaming.\n*/\nvar GenerationChunk = class GenerationChunk {\n\ttext;\n\tgenerationInfo;\n\tconstructor(fields) {\n\t\tthis.text = fields.text;\n\t\tthis.generationInfo = fields.generationInfo;\n\t}\n\tconcat(chunk) {\n\t\treturn new GenerationChunk({\n\t\t\ttext: this.text + chunk.text,\n\t\t\tgenerationInfo: {\n\t\t\t\t...this.generationInfo,\n\t\t\t\t...chunk.generationInfo\n\t\t\t}\n\t\t});\n\t}\n};\nvar ChatGenerationChunk = class ChatGenerationChunk extends GenerationChunk {\n\tmessage;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.message = fields.message;\n\t}\n\tconcat(chunk) {\n\t\treturn new ChatGenerationChunk({\n\t\t\ttext: this.text + chunk.text,\n\t\t\tgenerationInfo: {\n\t\t\t\t...this.generationInfo,\n\t\t\t\t...chunk.generationInfo\n\t\t\t},\n\t\t\tmessage: this.message.concat(chunk.message)\n\t\t});\n\t}\n};\n\n//#endregion\nexport { ChatGenerationChunk, GenerationChunk, RUN_KEY, outputs_exports };\n//# sourceMappingURL=outputs.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { getAbortSignalError } from \"./signal.js\";\nimport pRetry from \"p-retry\";\nimport PQueueMod from \"p-queue\";\n\n//#region src/utils/async_caller.ts\nvar async_caller_exports = {};\n__export(async_caller_exports, { AsyncCaller: () => AsyncCaller });\nconst STATUS_NO_RETRY = [\n\t400,\n\t401,\n\t402,\n\t403,\n\t404,\n\t405,\n\t406,\n\t407,\n\t409\n];\nconst defaultFailedAttemptHandler = (error) => {\n\tif (error.message.startsWith(\"Cancel\") || error.message.startsWith(\"AbortError\") || error.name === \"AbortError\") throw error;\n\tif (error?.code === \"ECONNABORTED\") throw error;\n\tconst status = error?.response?.status ?? error?.status;\n\tif (status && STATUS_NO_RETRY.includes(+status)) throw error;\n\tif (error?.error?.code === \"insufficient_quota\") {\n\t\tconst err = new Error(error?.message);\n\t\terr.name = \"InsufficientQuotaError\";\n\t\tthrow err;\n\t}\n};\n/**\n* A class that can be used to make async calls with concurrency and retry logic.\n*\n* This is useful for making calls to any kind of \"expensive\" external resource,\n* be it because it's rate-limited, subject to network issues, etc.\n*\n* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n* to `Infinity`. This means that by default, all calls will be made in parallel.\n*\n* Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n* means that by default, each call will be retried up to 6 times, with an\n* exponential backoff between each attempt.\n*/\nvar AsyncCaller = class {\n\tmaxConcurrency;\n\tmaxRetries;\n\tonFailedAttempt;\n\tqueue;\n\tconstructor(params) {\n\t\tthis.maxConcurrency = params.maxConcurrency ?? Infinity;\n\t\tthis.maxRetries = params.maxRetries ?? 6;\n\t\tthis.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler;\n\t\tconst PQueue = \"default\" in PQueueMod ? PQueueMod.default : PQueueMod;\n\t\tthis.queue = new PQueue({ concurrency: this.maxConcurrency });\n\t}\n\tcall(callable, ...args) {\n\t\treturn this.queue.add(() => pRetry(() => callable(...args).catch((error) => {\n\t\t\tif (error instanceof Error) throw error;\n\t\t\telse throw new Error(error);\n\t\t}), {\n\t\t\tonFailedAttempt: this.onFailedAttempt,\n\t\t\tretries: this.maxRetries,\n\t\t\trandomize: true\n\t\t}), { throwOnTimeout: true });\n\t}\n\tcallWithOptions(options, callable, ...args) {\n\t\tif (options.signal) return Promise.race([this.call(callable, ...args), new Promise((_, reject) => {\n\t\t\toptions.signal?.addEventListener(\"abort\", () => {\n\t\t\t\treject(getAbortSignalError(options.signal));\n\t\t\t});\n\t\t})]);\n\t\treturn this.call(callable, ...args);\n\t}\n\tfetch(...args) {\n\t\treturn this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res)));\n\t}\n};\n\n//#endregion\nexport { AsyncCaller, async_caller_exports };\n//# sourceMappingURL=async_caller.js.map","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n var _a;\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod ?? {},\n enumerable: false,\n });\n (_a = inst._zod).traits ?? (_a.traits = new Set());\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n for (const k in _.prototype) {\n if (!(k in inst))\n Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });\n }\n inst._zod.constr = _;\n inst._zod.def = def;\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error();\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport function defineLazy(object, key, getter) {\n const set = false;\n Object.defineProperty(object, key, {\n get() {\n if (!set) {\n const value = getter();\n object[key] = value;\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport const captureStackTrace = Error.captureStackTrace\n ? Error.captureStackTrace\n : (..._args) => { };\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const newShape = {};\n const currDef = schema._zod.def; //.shape;\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // pick key\n newShape[key] = currDef.shape[key];\n }\n return clone(schema, {\n ...schema._zod.def,\n shape: newShape,\n checks: [],\n });\n}\nexport function omit(schema, mask) {\n const newShape = { ...schema._zod.def.shape };\n const currDef = schema._zod.def; //.shape;\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n return clone(schema, {\n ...schema._zod.def,\n shape: newShape,\n checks: [],\n });\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const def = {\n ...schema._zod.def,\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: [], // delete existing checks\n };\n return clone(schema, def);\n}\nexport function merge(a, b) {\n return clone(a, {\n ...a._zod.def,\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n catchall: b._zod.def.catchall,\n checks: [], // delete existing checks\n });\n}\nexport function partial(Class, schema, mask) {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n return clone(schema, {\n ...schema._zod.def,\n shape,\n checks: [],\n });\n}\nexport function required(Class, schema, mask) {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n return clone(schema, {\n ...schema._zod.def,\n shape,\n // optional: [],\n checks: [],\n });\n}\nexport function aborted(x, startIndex = 0) {\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true)\n return true;\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n Object.defineProperty(inst, \"message\", {\n get() {\n return JSON.stringify(def, util.jsonStringifyReplacer, 2);\n },\n enumerable: true,\n // configurable: false,\n });\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(path) {\n const segs = [];\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n","export const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new Map();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n if (this._idmap.has(meta.id)) {\n throw new Error(`ID ${meta.id} already exists in the registry`);\n }\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new Map();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n return { ...pm, ...this._map.get(schema) };\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\nexport const globalRegistry = /*@__PURE__*/ registry();\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inst,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inst,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export const version = {\n major: 4,\n minor: 0,\n patch: 0,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n //\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n inst._zod.run = (payload, ctx) => {\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n inst[\"~standard\"] = {\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n };\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n const orig = payload.value;\n const url = new URL(orig);\n const href = url.href;\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: regexes.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // payload.value = url.href;\n if (!orig.endsWith(\"/\") && href.endsWith(\"/\")) {\n payload.value = href.slice(0, -1);\n }\n else {\n payload.value = href;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = `ipv4`;\n });\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = `ipv6`;\n });\n inst._zod.check = (payload) => {\n try {\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const [address, prefix] = payload.value.split(\"/\");\n try {\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.contentEncoding = \"base64\";\n });\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.contentEncoding = \"base64url\";\n });\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checksp\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handleObjectResult(result, final, key) {\n // if(isOptional)\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n final.value[key] = result.value;\n}\nfunction handleOptionalObjectResult(result, final, key, input) {\n if (result.issues.length) {\n // validation failed against value schema\n if (input[key] === undefined) {\n // if input was undefined, ignore the error\n if (key in input) {\n final.value[key] = undefined;\n }\n else {\n final.value[key] = result.value;\n }\n }\n else {\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n }\n else if (result.value === undefined) {\n // validation returned `undefined`\n if (key in input)\n final.value[key] = undefined;\n }\n else {\n // non-undefined value\n final.value[key] = result.value;\n }\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const _normalized = util.cached(() => {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!(def.shape[k] instanceof $ZodType)) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n shape: def.shape,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n });\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {}`);\n for (const key of normalized.keys) {\n if (normalized.optionalKeys.has(key)) {\n const id = ids[key];\n doc.write(`const ${id} = ${parseStr(key)};`);\n const k = util.esc(key);\n doc.write(`\n if (${id}.issues.length) {\n if (input[${k}] === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${id}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}],\n }))\n );\n }\n } else if (${id}.value === undefined) {\n if (${k} in input) newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n else {\n const id = ids[key];\n // const id = ids[key];\n doc.write(`const ${id} = ${parseStr(key)};`);\n doc.write(`\n if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${util.esc(key)}, ...iss.path] : [${util.esc(key)}]\n })));`);\n doc.write(`newResult[${util.esc(key)}] = ${id}.value`);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n }\n else {\n payload.value = {};\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n // do not add omitted optional keys\n // if (!(key in input)) {\n // if (optionalKeys.has(key)) continue;\n // payload.issues.push({\n // code: \"invalid_type\",\n // path: [key],\n // expected: \"nonoptional\",\n // note: `Missing required key: \"${key}\"`,\n // input,\n // inst,\n // });\n // }\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n const isOptional = el._zod.optin === \"optional\" && el._zod.optout === \"optional\";\n if (r instanceof Promise) {\n proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key)));\n }\n else if (isOptional) {\n handleOptionalObjectResult(r, payload, key, input);\n }\n else {\n handleObjectResult(r, payload, key);\n }\n }\n }\n if (!catchall) {\n // return payload;\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n const unrecognized = [];\n // iterate over input keys\n const keySet = value.keySet;\n const _catchall = catchall._zod;\n const t = _catchall.def.type;\n for (const key of Object.keys(input)) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handleObjectResult(r, payload, key)));\n }\n else {\n handleObjectResult(r, payload, key);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n if (left.issues.length) {\n result.issues.push(...left.issues);\n }\n if (right.issues.length) {\n result.issues.push(...right.issues);\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n input,\n inst,\n origin: \"array\",\n ...(tooBig ? { code: \"too_big\", maximum: items.length } : { code: \"too_small\", minimum: items.length }),\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n if (def.keyType._zod.values) {\n const values = def.keyType._zod.values;\n payload.value = {};\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!values.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n origin: \"record\",\n code: \"invalid_key\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n payload.value[keyResult.value] = keyResult.value;\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_key\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n inst._zod.values = new Set(values);\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (inst._zod.values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.values = new Set(def.values);\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? o.toString() : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (inst._zod.values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const _out = def.transform(payload.value, payload);\n if (_ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n return def.innerType._zod.run(payload, ctx);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault always returns the default value immediately.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n inst._zod.parse = (payload, ctx) => {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def, ctx));\n }\n return handlePipeResult(left, def, ctx);\n };\n});\nfunction handlePipeResult(left, def, ctx) {\n if (util.aborted(left)) {\n return left;\n }\n return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (part instanceof $ZodType) {\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"template_literal\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType._zod.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType._zod.optout);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : defaultValue;\n },\n });\n}\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// export function _refine(\n// Class: util.SchemaClass,\n// fn: (arg: NoInfer) => util.MaybeAsync,\n// _params: string | $ZodCustomParams = {}\n// ): checks.$ZodCheck {\n// return _custom(Class, fn, _params);\n// }\n// same as _custom but defaults to abort:false\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Pipe = Classes.Pipe ?? schemas.$ZodPipe;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const _Transform = Classes.Transform ?? schemas.$ZodTransform;\n const tx = new _Transform({\n type: \"transform\",\n transform: (input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: tx,\n });\n return {};\n }\n },\n error: params.error,\n });\n // params.error;\n const innerPipe = new _Pipe({\n type: \"pipe\",\n in: new _String({ type: \"string\", error: params.error }),\n out: tx,\n error: params.error,\n });\n const outerPipe = new _Pipe({\n type: \"pipe\",\n in: innerPipe,\n out: new _Boolean({\n type: \"boolean\",\n error: params.error,\n }),\n error: params.error,\n });\n return outerPipe;\n}\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { $ZodNever, $ZodOptional, $ZodUnknown, _never, _unknown, clone, globalRegistry, parse, parseAsync, util } from \"zod/v4/core\";\n\n//#region src/utils/types/zod.ts\nfunction isZodSchemaV4(schema) {\n\tif (typeof schema !== \"object\" || schema === null) return false;\n\tconst obj = schema;\n\tif (!(\"_zod\" in obj)) return false;\n\tconst zod = obj._zod;\n\treturn typeof zod === \"object\" && zod !== null && \"def\" in zod;\n}\nfunction isZodSchemaV3(schema) {\n\tif (typeof schema !== \"object\" || schema === null) return false;\n\tconst obj = schema;\n\tif (!(\"_def\" in obj) || \"_zod\" in obj) return false;\n\tconst def = obj._def;\n\treturn typeof def === \"object\" && def != null && \"typeName\" in def;\n}\n/** Backward compatible isZodSchema for Zod 3 */\nfunction isZodSchema(schema) {\n\tif (isZodSchemaV4(schema)) console.warn(\"[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.\");\n\treturn isZodSchemaV3(schema);\n}\n/**\n* Given either a Zod schema, or plain object, determine if the input is a Zod schema.\n*\n* @param {unknown} input\n* @returns {boolean} Whether or not the provided input is a Zod schema.\n*/\nfunction isInteropZodSchema(input) {\n\tif (!input) return false;\n\tif (typeof input !== \"object\") return false;\n\tif (Array.isArray(input)) return false;\n\tif (isZodSchemaV4(input) || isZodSchemaV3(input)) return true;\n\treturn false;\n}\nfunction isZodLiteralV3(obj) {\n\tif (typeof obj === \"object\" && obj !== null && \"_def\" in obj && typeof obj._def === \"object\" && obj._def !== null && \"typeName\" in obj._def && obj._def.typeName === \"ZodLiteral\") return true;\n\treturn false;\n}\nfunction isZodLiteralV4(obj) {\n\tif (!isZodSchemaV4(obj)) return false;\n\tif (typeof obj === \"object\" && obj !== null && \"_zod\" in obj && typeof obj._zod === \"object\" && obj._zod !== null && \"def\" in obj._zod && typeof obj._zod.def === \"object\" && obj._zod.def !== null && \"type\" in obj._zod.def && obj._zod.def.type === \"literal\") return true;\n\treturn false;\n}\n/**\n* Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema).\n*\n* @param obj The value to check.\n* @returns {boolean} True if the value is a Zod v3 or v4 literal schema, false otherwise.\n*/\nfunction isInteropZodLiteral(obj) {\n\tif (isZodLiteralV3(obj)) return true;\n\tif (isZodLiteralV4(obj)) return true;\n\treturn false;\n}\n/**\n* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result.\n* This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure.\n*\n* @template T - The expected output type of the schema.\n* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing.\n* @param {unknown} input - The input value to parse.\n* @returns {Promise>} A promise that resolves to a safe parse result object.\n* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema.\n*/\nasync function interopSafeParseAsync(schema, input) {\n\tif (isZodSchemaV4(schema)) try {\n\t\tconst data = await parseAsync(schema, input);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror\n\t\t};\n\t}\n\tif (isZodSchemaV3(schema)) return await schema.safeParseAsync(input);\n\tthrow new Error(\"Schema must be an instance of z3.ZodType or z4.$ZodType\");\n}\n/**\n* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value.\n* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema.\n*\n* @template T - The expected output type of the schema.\n* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing.\n* @param {unknown} input - The input value to parse.\n* @returns {Promise} A promise that resolves to the parsed value.\n* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema.\n*/\nasync function interopParseAsync(schema, input) {\n\tif (isZodSchemaV4(schema)) return await parseAsync(schema, input);\n\tif (isZodSchemaV3(schema)) return await schema.parseAsync(input);\n\tthrow new Error(\"Schema must be an instance of z3.ZodType or z4.$ZodType\");\n}\n/**\n* Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object\n* indicating success or failure. This function is compatible with both Zod v3 and v4 schemas.\n*\n* @template T - The expected output type of the schema.\n* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing.\n* @param {unknown} input - The input value to parse.\n* @returns {InteropZodSafeParseResult} An object with either the parsed data (on success)\n* or the error (on failure).\n* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema.\n*/\nfunction interopSafeParse(schema, input) {\n\tif (isZodSchemaV4(schema)) try {\n\t\tconst data = parse(schema, input);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror\n\t\t};\n\t}\n\tif (isZodSchemaV3(schema)) return schema.safeParse(input);\n\tthrow new Error(\"Schema must be an instance of z3.ZodType or z4.$ZodType\");\n}\n/**\n* Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value.\n* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema.\n*\n* @template T - The expected output type of the schema.\n* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing.\n* @param {unknown} input - The input value to parse.\n* @returns {T} The parsed value.\n* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema.\n*/\nfunction interopParse(schema, input) {\n\tif (isZodSchemaV4(schema)) return parse(schema, input);\n\tif (isZodSchemaV3(schema)) return schema.parse(input);\n\tthrow new Error(\"Schema must be an instance of z3.ZodType or z4.$ZodType\");\n}\n/**\n* Retrieves the description from a schema definition (v3, v4, or plain object), if available.\n*\n* @param {unknown} schema - The schema to extract the description from.\n* @returns {string | undefined} The description of the schema, or undefined if not present.\n*/\nfunction getSchemaDescription(schema) {\n\tif (isZodSchemaV4(schema)) return globalRegistry.get(schema)?.description;\n\tif (isZodSchemaV3(schema)) return schema.description;\n\tif (\"description\" in schema && typeof schema.description === \"string\") return schema.description;\n\treturn void 0;\n}\n/**\n* Determines if the provided Zod schema is \"shapeless\".\n* A shapeless schema is one that does not define any object shape,\n* such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc.\n* For ZodObject, it must have no shape keys to be considered shapeless.\n* ZodRecord schemas are considered shapeless since they define dynamic\n* key-value mappings without fixed keys.\n*\n* @param schema The Zod schema to check.\n* @returns {boolean} True if the schema is shapeless, false otherwise.\n*/\nfunction isShapelessZodSchema(schema) {\n\tif (!isInteropZodSchema(schema)) return false;\n\tif (isZodSchemaV3(schema)) {\n\t\tconst def = schema._def;\n\t\tif (def.typeName === \"ZodObject\") {\n\t\t\tconst obj = schema;\n\t\t\treturn !obj.shape || Object.keys(obj.shape).length === 0;\n\t\t}\n\t\tif (def.typeName === \"ZodRecord\") return true;\n\t}\n\tif (isZodSchemaV4(schema)) {\n\t\tconst def = schema._zod.def;\n\t\tif (def.type === \"object\") {\n\t\t\tconst obj = schema;\n\t\t\treturn !obj.shape || Object.keys(obj.shape).length === 0;\n\t\t}\n\t\tif (def.type === \"record\") return true;\n\t}\n\tif (typeof schema === \"object\" && schema !== null && !(\"shape\" in schema)) return true;\n\treturn false;\n}\n/**\n* Determines if the provided Zod schema should be treated as a simple string schema\n* that maps to DynamicTool. This aligns with the type-level constraint of\n* InteropZodType which only matches basic string schemas.\n* If the provided schema is just z.string(), we can make the determination that\n* the tool is just a generic string tool that doesn't require any input validation.\n*\n* This function only returns true for basic ZodString schemas, including:\n* - Basic string schemas (z.string())\n* - String schemas with validations (z.string().min(1), z.string().email(), etc.)\n*\n* This function returns false for everything else, including:\n* - String schemas with defaults (z.string().default(\"value\"))\n* - Branded string schemas (z.string().brand<\"UserId\">())\n* - String schemas with catch operations (z.string().catch(\"default\"))\n* - Optional/nullable string schemas (z.string().optional())\n* - Transformed schemas (z.string().transform() or z.object().transform())\n* - Object or record schemas, even if they're empty\n* - Any other schema type\n*\n* @param schema The Zod schema to check.\n* @returns {boolean} True if the schema is a basic ZodString, false otherwise.\n*/\nfunction isSimpleStringZodSchema(schema) {\n\tif (!isInteropZodSchema(schema)) return false;\n\tif (isZodSchemaV3(schema)) {\n\t\tconst def = schema._def;\n\t\treturn def.typeName === \"ZodString\";\n\t}\n\tif (isZodSchemaV4(schema)) {\n\t\tconst def = schema._zod.def;\n\t\treturn def.type === \"string\";\n\t}\n\treturn false;\n}\nfunction isZodObjectV3(obj) {\n\tif (typeof obj === \"object\" && obj !== null && \"_def\" in obj && typeof obj._def === \"object\" && obj._def !== null && \"typeName\" in obj._def && obj._def.typeName === \"ZodObject\") return true;\n\treturn false;\n}\nfunction isZodObjectV4(obj) {\n\tif (!isZodSchemaV4(obj)) return false;\n\tif (typeof obj === \"object\" && obj !== null && \"_zod\" in obj && typeof obj._zod === \"object\" && obj._zod !== null && \"def\" in obj._zod && typeof obj._zod.def === \"object\" && obj._zod.def !== null && \"type\" in obj._zod.def && obj._zod.def.type === \"object\") return true;\n\treturn false;\n}\nfunction isZodArrayV4(obj) {\n\tif (!isZodSchemaV4(obj)) return false;\n\tif (typeof obj === \"object\" && obj !== null && \"_zod\" in obj && typeof obj._zod === \"object\" && obj._zod !== null && \"def\" in obj._zod && typeof obj._zod.def === \"object\" && obj._zod.def !== null && \"type\" in obj._zod.def && obj._zod.def.type === \"array\") return true;\n\treturn false;\n}\n/**\n* Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema).\n*\n* @param obj The value to check.\n* @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise.\n*/\nfunction isInteropZodObject(obj) {\n\tif (isZodObjectV3(obj)) return true;\n\tif (isZodObjectV4(obj)) return true;\n\treturn false;\n}\n/**\n* Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4.\n*\n* @template T - The type of the Zod object schema.\n* @param {T} schema - The Zod object schema instance (either v3 or v4).\n* @returns {InteropZodObjectShape} The shape of the object schema.\n* @throws {Error} If the schema is not a Zod v3 or v4 object.\n*/\nfunction getInteropZodObjectShape(schema) {\n\tif (isZodSchemaV3(schema)) return schema.shape;\n\tif (isZodSchemaV4(schema)) return schema._zod.def.shape;\n\tthrow new Error(\"Schema must be an instance of z3.ZodObject or z4.$ZodObject\");\n}\n/**\n* Extends a Zod object schema with additional fields, supporting both Zod v3 and v4.\n*\n* @template T - The type of the Zod object schema.\n* @param {T} schema - The Zod object schema instance (either v3 or v4).\n* @param {InteropZodObjectShape} extension - The fields to add to the schema.\n* @returns {InteropZodObject} The extended Zod object schema.\n* @throws {Error} If the schema is not a Zod v3 or v4 object.\n*/\nfunction extendInteropZodObject(schema, extension) {\n\tif (isZodSchemaV3(schema)) return schema.extend(extension);\n\tif (isZodSchemaV4(schema)) return util.extend(schema, extension);\n\tthrow new Error(\"Schema must be an instance of z3.ZodObject or z4.$ZodObject\");\n}\n/**\n* Returns a partial version of a Zod object schema, making all fields optional.\n* Supports both Zod v3 and v4.\n*\n* @template T - The type of the Zod object schema.\n* @param {T} schema - The Zod object schema instance (either v3 or v4).\n* @returns {InteropZodObject} The partial Zod object schema.\n* @throws {Error} If the schema is not a Zod v3 or v4 object.\n*/\nfunction interopZodObjectPartial(schema) {\n\tif (isZodSchemaV3(schema)) return schema.partial();\n\tif (isZodSchemaV4(schema)) return util.partial($ZodOptional, schema, void 0);\n\tthrow new Error(\"Schema must be an instance of z3.ZodObject or z4.$ZodObject\");\n}\n/**\n* Returns a strict version of a Zod object schema, disallowing unknown keys.\n* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness\n* recursively to all nested object schemas and arrays of object schemas.\n*\n* @template T - The type of the Zod object schema.\n* @param {T} schema - The Zod object schema instance (either v3 or v4).\n* @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays.\n* @returns {InteropZodObject} The strict Zod object schema.\n* @throws {Error} If the schema is not a Zod v3 or v4 object.\n*/\nfunction interopZodObjectStrict(schema, recursive = false) {\n\tif (isZodSchemaV3(schema)) return schema.strict();\n\tif (isZodObjectV4(schema)) {\n\t\tconst outputShape = schema._zod.def.shape;\n\t\tif (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) {\n\t\t\tif (isZodObjectV4(keySchema)) {\n\t\t\t\tconst outputSchema = interopZodObjectStrict(keySchema, recursive);\n\t\t\t\toutputShape[key] = outputSchema;\n\t\t\t} else if (isZodArrayV4(keySchema)) {\n\t\t\t\tlet elementSchema = keySchema._zod.def.element;\n\t\t\t\tif (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectStrict(elementSchema, recursive);\n\t\t\t\toutputShape[key] = clone(keySchema, {\n\t\t\t\t\t...keySchema._zod.def,\n\t\t\t\t\telement: elementSchema\n\t\t\t\t});\n\t\t\t} else outputShape[key] = keySchema;\n\t\t\tconst meta$1 = globalRegistry.get(keySchema);\n\t\t\tif (meta$1) globalRegistry.add(outputShape[key], meta$1);\n\t\t}\n\t\tconst modifiedSchema = clone(schema, {\n\t\t\t...schema._zod.def,\n\t\t\tshape: outputShape,\n\t\t\tcatchall: _never($ZodNever)\n\t\t});\n\t\tconst meta = globalRegistry.get(schema);\n\t\tif (meta) globalRegistry.add(modifiedSchema, meta);\n\t\treturn modifiedSchema;\n\t}\n\tthrow new Error(\"Schema must be an instance of z3.ZodObject or z4.$ZodObject\");\n}\n/**\n* Returns a passthrough version of a Zod object schema, allowing unknown keys.\n* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough\n* recursively to all nested object schemas and arrays of object schemas.\n*\n* @template T - The type of the Zod object schema.\n* @param {T} schema - The Zod object schema instance (either v3 or v4).\n* @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays.\n* @returns {InteropZodObject} The passthrough Zod object schema.\n* @throws {Error} If the schema is not a Zod v3 or v4 object.\n*/\nfunction interopZodObjectPassthrough(schema, recursive = false) {\n\tif (isZodObjectV3(schema)) return schema.passthrough();\n\tif (isZodObjectV4(schema)) {\n\t\tconst outputShape = schema._zod.def.shape;\n\t\tif (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) {\n\t\t\tif (isZodObjectV4(keySchema)) {\n\t\t\t\tconst outputSchema = interopZodObjectPassthrough(keySchema, recursive);\n\t\t\t\toutputShape[key] = outputSchema;\n\t\t\t} else if (isZodArrayV4(keySchema)) {\n\t\t\t\tlet elementSchema = keySchema._zod.def.element;\n\t\t\t\tif (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectPassthrough(elementSchema, recursive);\n\t\t\t\toutputShape[key] = clone(keySchema, {\n\t\t\t\t\t...keySchema._zod.def,\n\t\t\t\t\telement: elementSchema\n\t\t\t\t});\n\t\t\t} else outputShape[key] = keySchema;\n\t\t\tconst meta$1 = globalRegistry.get(keySchema);\n\t\t\tif (meta$1) globalRegistry.add(outputShape[key], meta$1);\n\t\t}\n\t\tconst modifiedSchema = clone(schema, {\n\t\t\t...schema._zod.def,\n\t\t\tshape: outputShape,\n\t\t\tcatchall: _unknown($ZodUnknown)\n\t\t});\n\t\tconst meta = globalRegistry.get(schema);\n\t\tif (meta) globalRegistry.add(modifiedSchema, meta);\n\t\treturn modifiedSchema;\n\t}\n\tthrow new Error(\"Schema must be an instance of z3.ZodObject or z4.$ZodObject\");\n}\n/**\n* Returns a getter function for the default value of a Zod schema, if one is defined.\n* Supports both Zod v3 and v4 schemas. If the schema has a default value,\n* the returned function will return that value when called. If no default is defined,\n* returns undefined.\n*\n* @template T - The type of the Zod schema.\n* @param {T} schema - The Zod schema instance (either v3 or v4).\n* @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set.\n*/\nfunction getInteropZodDefaultGetter(schema) {\n\tif (isZodSchemaV3(schema)) try {\n\t\tconst defaultValue = schema.parse(void 0);\n\t\treturn () => defaultValue;\n\t} catch {\n\t\treturn void 0;\n\t}\n\tif (isZodSchemaV4(schema)) try {\n\t\tconst defaultValue = parse(schema, void 0);\n\t\treturn () => defaultValue;\n\t} catch {\n\t\treturn void 0;\n\t}\n\treturn void 0;\n}\nfunction isZodTransformV3(schema) {\n\treturn isZodSchemaV3(schema) && \"typeName\" in schema._def && schema._def.typeName === \"ZodEffects\";\n}\nfunction isZodTransformV4(schema) {\n\treturn isZodSchemaV4(schema) && schema._zod.def.type === \"pipe\";\n}\n/**\n* Returns the input type of a Zod transform schema, for both v3 and v4.\n* If the schema is not a transform, returns undefined. If `recursive` is true,\n* recursively processes nested object schemas and arrays of object schemas.\n*\n* @param schema - The Zod schema instance (v3 or v4)\n* @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays.\n* @returns The input Zod schema of the transform, or undefined if not a transform\n*/\nfunction interopZodTransformInputSchema(schema, recursive = false) {\n\tif (isZodSchemaV3(schema)) {\n\t\tif (isZodTransformV3(schema)) return interopZodTransformInputSchema(schema._def.schema, recursive);\n\t\treturn schema;\n\t}\n\tif (isZodSchemaV4(schema)) {\n\t\tlet outputSchema = schema;\n\t\tif (isZodTransformV4(schema)) outputSchema = interopZodTransformInputSchema(schema._zod.def.in, recursive);\n\t\tif (recursive) {\n\t\t\tif (isZodObjectV4(outputSchema)) {\n\t\t\t\tconst outputShape = outputSchema._zod.def.shape;\n\t\t\t\tfor (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) outputShape[key] = interopZodTransformInputSchema(keySchema, recursive);\n\t\t\t\toutputSchema = clone(outputSchema, {\n\t\t\t\t\t...outputSchema._zod.def,\n\t\t\t\t\tshape: outputShape\n\t\t\t\t});\n\t\t\t} else if (isZodArrayV4(outputSchema)) {\n\t\t\t\tconst elementSchema = interopZodTransformInputSchema(outputSchema._zod.def.element, recursive);\n\t\t\t\toutputSchema = clone(outputSchema, {\n\t\t\t\t\t...outputSchema._zod.def,\n\t\t\t\t\telement: elementSchema\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst meta = globalRegistry.get(schema);\n\t\tif (meta) globalRegistry.add(outputSchema, meta);\n\t\treturn outputSchema;\n\t}\n\tthrow new Error(\"Schema must be an instance of z3.ZodType or z4.$ZodType\");\n}\n/**\n* Creates a modified version of a Zod object schema where fields matching a predicate are made optional.\n* Supports both Zod v3 and v4 schemas and preserves the original schema version.\n*\n* @template T - The type of the Zod object schema.\n* @param {T} schema - The Zod object schema instance (either v3 or v4).\n* @param {(key: string, value: InteropZodType) => boolean} predicate - Function to determine which fields should be optional.\n* @returns {InteropZodObject} The modified Zod object schema.\n* @throws {Error} If the schema is not a Zod v3 or v4 object.\n*/\nfunction interopZodObjectMakeFieldsOptional(schema, predicate) {\n\tif (isZodSchemaV3(schema)) {\n\t\tconst shape = getInteropZodObjectShape(schema);\n\t\tconst modifiedShape = {};\n\t\tfor (const [key, value] of Object.entries(shape)) if (predicate(key, value)) modifiedShape[key] = value.optional();\n\t\telse modifiedShape[key] = value;\n\t\treturn schema.extend(modifiedShape);\n\t}\n\tif (isZodSchemaV4(schema)) {\n\t\tconst shape = getInteropZodObjectShape(schema);\n\t\tconst outputShape = { ...schema._zod.def.shape };\n\t\tfor (const [key, value] of Object.entries(shape)) if (predicate(key, value)) outputShape[key] = new $ZodOptional({\n\t\t\ttype: \"optional\",\n\t\t\tinnerType: value\n\t\t});\n\t\tconst modifiedSchema = clone(schema, {\n\t\t\t...schema._zod.def,\n\t\t\tshape: outputShape\n\t\t});\n\t\tconst meta = globalRegistry.get(schema);\n\t\tif (meta) globalRegistry.add(modifiedSchema, meta);\n\t\treturn modifiedSchema;\n\t}\n\tthrow new Error(\"Schema must be an instance of z3.ZodObject or z4.$ZodObject\");\n}\n\n//#endregion\nexport { extendInteropZodObject, getInteropZodDefaultGetter, getInteropZodObjectShape, getSchemaDescription, interopParse, interopParseAsync, interopSafeParse, interopSafeParseAsync, interopZodObjectMakeFieldsOptional, interopZodObjectPartial, interopZodObjectPassthrough, interopZodObjectStrict, interopZodTransformInputSchema, isInteropZodLiteral, isInteropZodObject, isInteropZodSchema, isShapelessZodSchema, isSimpleStringZodSchema, isZodArrayV4, isZodLiteralV3, isZodLiteralV4, isZodObjectV3, isZodObjectV4, isZodSchema, isZodSchemaV3, isZodSchemaV4 };\n//# sourceMappingURL=zod.js.map","//#region src/utils/zod-to-json-schema/Options.ts\nconst ignoreOverride = Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nconst defaultOptions = {\n\tname: void 0,\n\t$refStrategy: \"root\",\n\tbasePath: [\"#\"],\n\teffectStrategy: \"input\",\n\tpipeStrategy: \"all\",\n\tdateStrategy: \"format:date-time\",\n\tmapStrategy: \"entries\",\n\tremoveAdditionalStrategy: \"passthrough\",\n\tallowedAdditionalProperties: true,\n\trejectedAdditionalProperties: false,\n\tdefinitionPath: \"definitions\",\n\ttarget: \"jsonSchema7\",\n\tstrictUnions: false,\n\tdefinitions: {},\n\terrorMessages: false,\n\tmarkdownDescription: false,\n\tpatternStrategy: \"escape\",\n\tapplyRegexFlags: false,\n\temailStrategy: \"format:email\",\n\tbase64Strategy: \"contentEncoding:base64\",\n\tnameStrategy: \"ref\",\n\topenAiAnyTypeName: \"OpenAiAnyType\"\n};\nconst getDefaultOptions = (options) => typeof options === \"string\" ? {\n\t...defaultOptions,\n\tname: options\n} : {\n\t...defaultOptions,\n\t...options\n};\n\n//#endregion\nexport { defaultOptions, getDefaultOptions, ignoreOverride };\n//# sourceMappingURL=Options.js.map","import { getDefaultOptions } from \"./Options.js\";\n\n//#region src/utils/zod-to-json-schema/Refs.ts\nconst getRefs = (options) => {\n\tconst _options = getDefaultOptions(options);\n\tconst currentPath = _options.name !== void 0 ? [\n\t\t..._options.basePath,\n\t\t_options.definitionPath,\n\t\t_options.name\n\t] : _options.basePath;\n\treturn {\n\t\t..._options,\n\t\tflags: { hasReferencedOpenAiAnyType: false },\n\t\tcurrentPath,\n\t\tpropertyPath: void 0,\n\t\tseen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, {\n\t\t\tdef: def._def,\n\t\t\tpath: [\n\t\t\t\t..._options.basePath,\n\t\t\t\t_options.definitionPath,\n\t\t\t\tname\n\t\t\t],\n\t\t\tjsonSchema: void 0\n\t\t}]))\n\t};\n};\n\n//#endregion\nexport { getRefs };\n//# sourceMappingURL=Refs.js.map","//#region src/utils/zod-to-json-schema/getRelativePath.ts\nconst getRelativePath = (pathA, pathB) => {\n\tlet i = 0;\n\tfor (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;\n\treturn [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n\n//#endregion\nexport { getRelativePath };\n//# sourceMappingURL=getRelativePath.js.map","import { getRelativePath } from \"../getRelativePath.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/any.ts\nfunction parseAnyDef(refs) {\n\tif (refs.target !== \"openAi\") return {};\n\tconst anyDefinitionPath = [\n\t\t...refs.basePath,\n\t\trefs.definitionPath,\n\t\trefs.openAiAnyTypeName\n\t];\n\trefs.flags.hasReferencedOpenAiAnyType = true;\n\treturn { $ref: refs.$refStrategy === \"relative\" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join(\"/\") };\n}\n\n//#endregion\nexport { parseAnyDef };\n//# sourceMappingURL=any.js.map","//#region src/utils/zod-to-json-schema/errorMessages.ts\nfunction addErrorMessage(res, key, errorMessage, refs) {\n\tif (!refs?.errorMessages) return;\n\tif (errorMessage) res.errorMessage = {\n\t\t...res.errorMessage,\n\t\t[key]: errorMessage\n\t};\n}\nfunction setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n\tres[key] = value;\n\taddErrorMessage(res, key, errorMessage, refs);\n}\n\n//#endregion\nexport { addErrorMessage, setResponseValueAndErrors };\n//# sourceMappingURL=errorMessages.js.map","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\n\n//#region src/utils/zod-to-json-schema/parsers/array.ts\nfunction parseArrayDef(def, refs) {\n\tconst res = { type: \"array\" };\n\tif (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t});\n\tif (def.minLength) setResponseValueAndErrors(res, \"minItems\", def.minLength.value, def.minLength.message, refs);\n\tif (def.maxLength) setResponseValueAndErrors(res, \"maxItems\", def.maxLength.value, def.maxLength.message, refs);\n\tif (def.exactLength) {\n\t\tsetResponseValueAndErrors(res, \"minItems\", def.exactLength.value, def.exactLength.message, refs);\n\t\tsetResponseValueAndErrors(res, \"maxItems\", def.exactLength.value, def.exactLength.message, refs);\n\t}\n\treturn res;\n}\n\n//#endregion\nexport { parseArrayDef };\n//# sourceMappingURL=array.js.map","import { setResponseValueAndErrors } from \"../errorMessages.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/bigint.ts\nfunction parseBigintDef(def, refs) {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"int64\"\n\t};\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tif (refs.target === \"jsonSchema7\") if (check.inclusive) setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n\t\t\telse setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n\t\t\telse {\n\t\t\t\tif (!check.inclusive) res.exclusiveMinimum = true;\n\t\t\t\tsetResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (refs.target === \"jsonSchema7\") if (check.inclusive) setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n\t\t\telse setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n\t\t\telse {\n\t\t\t\tif (!check.inclusive) res.exclusiveMaximum = true;\n\t\t\t\tsetResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"multipleOf\":\n\t\t\tsetResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n\t\t\tbreak;\n\t}\n\treturn res;\n}\n\n//#endregion\nexport { parseBigintDef };\n//# sourceMappingURL=bigint.js.map","//#region src/utils/zod-to-json-schema/parsers/boolean.ts\nfunction parseBooleanDef() {\n\treturn { type: \"boolean\" };\n}\n\n//#endregion\nexport { parseBooleanDef };\n//# sourceMappingURL=boolean.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/branded.ts\nfunction parseBrandedDef(_def, refs) {\n\treturn parseDef(_def.type._def, refs);\n}\n\n//#endregion\nexport { parseBrandedDef };\n//# sourceMappingURL=branded.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/catch.ts\nconst parseCatchDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\n\n//#endregion\nexport { parseCatchDef };\n//# sourceMappingURL=catch.js.map","import { setResponseValueAndErrors } from \"../errorMessages.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/date.ts\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n\tconst strategy = overrideDateStrategy ?? refs.dateStrategy;\n\tif (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) };\n\tswitch (strategy) {\n\t\tcase \"string\":\n\t\tcase \"format:date-time\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date-time\"\n\t\t};\n\t\tcase \"format:date\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date\"\n\t\t};\n\t\tcase \"integer\": return integerDateParser(def, refs);\n\t}\n}\nconst integerDateParser = (def, refs) => {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"unix-time\"\n\t};\n\tif (refs.target === \"openApi3\") return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tsetResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tsetResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n\t\t\tbreak;\n\t}\n\treturn res;\n};\n\n//#endregion\nexport { parseDateDef };\n//# sourceMappingURL=date.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/default.ts\nfunction parseDefaultDef(_def, refs) {\n\treturn {\n\t\t...parseDef(_def.innerType._def, refs),\n\t\tdefault: _def.defaultValue()\n\t};\n}\n\n//#endregion\nexport { parseDefaultDef };\n//# sourceMappingURL=default.js.map","import { parseAnyDef } from \"./any.js\";\nimport { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/effects.ts\nfunction parseEffectsDef(_def, refs) {\n\treturn refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);\n}\n\n//#endregion\nexport { parseEffectsDef };\n//# sourceMappingURL=effects.js.map","//#region src/utils/zod-to-json-schema/parsers/enum.ts\nfunction parseEnumDef(def) {\n\treturn {\n\t\ttype: \"string\",\n\t\tenum: Array.from(def.values)\n\t};\n}\n\n//#endregion\nexport { parseEnumDef };\n//# sourceMappingURL=enum.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/intersection.ts\nconst isJsonSchema7AllOfType = (type) => {\n\tif (\"type\" in type && type.type === \"string\") return false;\n\treturn \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n\tconst allOf = [parseDef(def.left._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t}), parseDef(def.right._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"1\"\n\t\t]\n\t})].filter((x) => !!x);\n\tlet unevaluatedProperties = refs.target === \"jsonSchema2019-09\" ? { unevaluatedProperties: false } : void 0;\n\tconst mergedAllOf = [];\n\tallOf.forEach((schema) => {\n\t\tif (isJsonSchema7AllOfType(schema)) {\n\t\t\tmergedAllOf.push(...schema.allOf);\n\t\t\tif (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0;\n\t\t} else {\n\t\t\tlet nestedSchema = schema;\n\t\t\tif (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n\t\t\t\tconst { additionalProperties,...rest } = schema;\n\t\t\t\tnestedSchema = rest;\n\t\t\t} else unevaluatedProperties = void 0;\n\t\t\tmergedAllOf.push(nestedSchema);\n\t\t}\n\t});\n\treturn mergedAllOf.length ? {\n\t\tallOf: mergedAllOf,\n\t\t...unevaluatedProperties\n\t} : void 0;\n}\n\n//#endregion\nexport { parseIntersectionDef };\n//# sourceMappingURL=intersection.js.map","//#region src/utils/zod-to-json-schema/parsers/literal.ts\nfunction parseLiteralDef(def, refs) {\n\tconst parsedType = typeof def.value;\n\tif (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") return { type: Array.isArray(def.value) ? \"array\" : \"object\" };\n\tif (refs.target === \"openApi3\") return {\n\t\ttype: parsedType === \"bigint\" ? \"integer\" : parsedType,\n\t\tenum: [def.value]\n\t};\n\treturn {\n\t\ttype: parsedType === \"bigint\" ? \"integer\" : parsedType,\n\t\tconst: def.value\n\t};\n}\n\n//#endregion\nexport { parseLiteralDef };\n//# sourceMappingURL=literal.js.map","import { setResponseValueAndErrors } from \"../errorMessages.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/string.ts\nlet emojiRegex = void 0;\n/**\n* Generated from the regular expressions found here as of 2024-05-22:\n* https://github.com/colinhacks/zod/blob/master/src/types.ts.\n*\n* Expressions with /i flag have been changed accordingly.\n*/\nconst zodPatterns = {\n\tcuid: /^[cC][^\\s-]{8,}$/,\n\tcuid2: /^[0-9a-z]+$/,\n\tulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n\temail: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n\temoji: () => {\n\t\tif (emojiRegex === void 0) emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n\t\treturn emojiRegex;\n\t},\n\tuuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n\tipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n\tipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n\tipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n\tipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n\tbase64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n\tbase64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n\tnanoid: /^[a-zA-Z0-9_-]{21}$/,\n\tjwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n\tconst res = { type: \"string\" };\n\tif (def.checks) for (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tsetResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tsetResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"email\":\n\t\t\tswitch (refs.emailStrategy) {\n\t\t\t\tcase \"format:email\":\n\t\t\t\t\taddFormat(res, \"email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"format:idn-email\":\n\t\t\t\t\taddFormat(res, \"idn-email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\":\n\t\t\t\t\taddPattern(res, zodPatterns.email, check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"url\":\n\t\t\taddFormat(res, \"uri\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"uuid\":\n\t\t\taddFormat(res, \"uuid\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"regex\":\n\t\t\taddPattern(res, check.regex, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid\":\n\t\t\taddPattern(res, zodPatterns.cuid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid2\":\n\t\t\taddPattern(res, zodPatterns.cuid2, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"startsWith\":\n\t\t\taddPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"endsWith\":\n\t\t\taddPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"datetime\":\n\t\t\taddFormat(res, \"date-time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"date\":\n\t\t\taddFormat(res, \"date\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"time\":\n\t\t\taddFormat(res, \"time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"duration\":\n\t\t\taddFormat(res, \"duration\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"length\":\n\t\t\tsetResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n\t\t\tsetResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"includes\":\n\t\t\taddPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ip\":\n\t\t\tif (check.version !== \"v6\") addFormat(res, \"ipv4\", check.message, refs);\n\t\t\tif (check.version !== \"v4\") addFormat(res, \"ipv6\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64url\":\n\t\t\taddPattern(res, zodPatterns.base64url, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"jwt\":\n\t\t\taddPattern(res, zodPatterns.jwt, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cidr\":\n\t\t\tif (check.version !== \"v6\") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n\t\t\tif (check.version !== \"v4\") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"emoji\":\n\t\t\taddPattern(res, zodPatterns.emoji(), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ulid\":\n\t\t\taddPattern(res, zodPatterns.ulid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64\":\n\t\t\tswitch (refs.base64Strategy) {\n\t\t\t\tcase \"format:binary\":\n\t\t\t\t\taddFormat(res, \"binary\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"contentEncoding:base64\":\n\t\t\t\t\tsetResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\":\n\t\t\t\t\taddPattern(res, zodPatterns.base64, check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"nanoid\":\n\t\t\taddPattern(res, zodPatterns.nanoid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"toLowerCase\":\n\t\tcase \"toUpperCase\":\n\t\tcase \"trim\": break;\n\t\tdefault:\n /* c8 ignore next */\n\t\t((_) => {})(check);\n\t}\n\treturn res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n\treturn refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nconst ALPHA_NUMERIC = /* @__PURE__ */ new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n\tlet result = \"\";\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (!ALPHA_NUMERIC.has(source[i])) result += \"\\\\\";\n\t\tresult += source[i];\n\t}\n\treturn result;\n}\nfunction addFormat(schema, value, message, refs) {\n\tif (schema.format || schema.anyOf?.some((x) => x.format)) {\n\t\tif (!schema.anyOf) schema.anyOf = [];\n\t\tif (schema.format) {\n\t\t\tschema.anyOf.push({\n\t\t\t\tformat: schema.format,\n\t\t\t\t...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } }\n\t\t\t});\n\t\t\tdelete schema.format;\n\t\t\tif (schema.errorMessage) {\n\t\t\t\tdelete schema.errorMessage.format;\n\t\t\t\tif (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage;\n\t\t\t}\n\t\t}\n\t\tschema.anyOf.push({\n\t\t\tformat: value,\n\t\t\t...message && refs.errorMessages && { errorMessage: { format: message } }\n\t\t});\n\t} else setResponseValueAndErrors(schema, \"format\", value, message, refs);\n}\nfunction addPattern(schema, regex, message, refs) {\n\tif (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n\t\tif (!schema.allOf) schema.allOf = [];\n\t\tif (schema.pattern) {\n\t\t\tschema.allOf.push({\n\t\t\t\tpattern: schema.pattern,\n\t\t\t\t...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } }\n\t\t\t});\n\t\t\tdelete schema.pattern;\n\t\t\tif (schema.errorMessage) {\n\t\t\t\tdelete schema.errorMessage.pattern;\n\t\t\t\tif (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage;\n\t\t\t}\n\t\t}\n\t\tschema.allOf.push({\n\t\t\tpattern: stringifyRegExpWithFlags(regex, refs),\n\t\t\t...message && refs.errorMessages && { errorMessage: { pattern: message } }\n\t\t});\n\t} else setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n\tif (!refs.applyRegexFlags || !regex.flags) return regex.source;\n\tconst flags = {\n\t\ti: regex.flags.includes(\"i\"),\n\t\tm: regex.flags.includes(\"m\"),\n\t\ts: regex.flags.includes(\"s\")\n\t};\n\tconst source = flags.i ? regex.source.toLowerCase() : regex.source;\n\tlet pattern = \"\";\n\tlet isEscaped = false;\n\tlet inCharGroup = false;\n\tlet inCharRange = false;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (isEscaped) {\n\t\t\tpattern += source[i];\n\t\t\tisEscaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (flags.i) {\n\t\t\tif (inCharGroup) {\n\t\t\t\tif (source[i].match(/[a-z]/)) {\n\t\t\t\t\tif (inCharRange) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tpattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n\t\t\t\t\t\tinCharRange = false;\n\t\t\t\t\t} else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tinCharRange = true;\n\t\t\t\t\t} else pattern += `${source[i]}${source[i].toUpperCase()}`;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (source[i].match(/[a-z]/)) {\n\t\t\t\tpattern += `[${source[i]}${source[i].toUpperCase()}]`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.m) {\n\t\t\tif (source[i] === \"^\") {\n\t\t\t\tpattern += `(^|(?<=[\\r\\n]))`;\n\t\t\t\tcontinue;\n\t\t\t} else if (source[i] === \"$\") {\n\t\t\t\tpattern += `($|(?=[\\r\\n]))`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.s && source[i] === \".\") {\n\t\t\tpattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n\t\t\tcontinue;\n\t\t}\n\t\tpattern += source[i];\n\t\tif (source[i] === \"\\\\\") isEscaped = true;\n\t\telse if (inCharGroup && source[i] === \"]\") inCharGroup = false;\n\t\telse if (!inCharGroup && source[i] === \"[\") inCharGroup = true;\n\t}\n\ttry {\n\t\tnew RegExp(pattern);\n\t} catch {\n\t\tconsole.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n\t\treturn regex.source;\n\t}\n\treturn pattern;\n}\n\n//#endregion\nexport { parseStringDef, zodPatterns };\n//# sourceMappingURL=string.js.map","import { parseAnyDef } from \"./any.js\";\nimport { parseBrandedDef } from \"./branded.js\";\nimport { parseStringDef } from \"./string.js\";\nimport { parseDef } from \"../parseDef.js\";\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\n\n//#region src/utils/zod-to-json-schema/parsers/record.ts\nfunction parseRecordDef(def, refs) {\n\tif (refs.target === \"openAi\") console.warn(\"Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.\");\n\tif (refs.target === \"openApi3\" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {\n\t\ttype: \"object\",\n\t\trequired: def.keyType._def.values,\n\t\tproperties: def.keyType._def.values.reduce((acc, key) => ({\n\t\t\t...acc,\n\t\t\t[key]: parseDef(def.valueType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"properties\",\n\t\t\t\t\tkey\n\t\t\t\t]\n\t\t\t}) ?? parseAnyDef(refs)\n\t\t}), {}),\n\t\tadditionalProperties: refs.rejectedAdditionalProperties\n\t};\n\tconst schema = {\n\t\ttype: \"object\",\n\t\tadditionalProperties: parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t\t}) ?? refs.allowedAdditionalProperties\n\t};\n\tif (refs.target === \"openApi3\") return schema;\n\tif (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {\n\t\tconst { type,...keyType } = parseStringDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t} else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {\n\t\t...schema,\n\t\tpropertyNames: { enum: def.keyType._def.values }\n\t};\n\telse if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {\n\t\tconst { type,...keyType } = parseBrandedDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t}\n\treturn schema;\n}\n\n//#endregion\nexport { parseRecordDef };\n//# sourceMappingURL=record.js.map","import { parseAnyDef } from \"./any.js\";\nimport { parseRecordDef } from \"./record.js\";\nimport { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/map.ts\nfunction parseMapDef(def, refs) {\n\tif (refs.mapStrategy === \"record\") return parseRecordDef(def, refs);\n\tconst keys = parseDef(def.keyType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"items\",\n\t\t\t\"items\",\n\t\t\t\"0\"\n\t\t]\n\t}) || parseAnyDef(refs);\n\tconst values = parseDef(def.valueType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"items\",\n\t\t\t\"items\",\n\t\t\t\"1\"\n\t\t]\n\t}) || parseAnyDef(refs);\n\treturn {\n\t\ttype: \"array\",\n\t\tmaxItems: 125,\n\t\titems: {\n\t\t\ttype: \"array\",\n\t\t\titems: [keys, values],\n\t\t\tminItems: 2,\n\t\t\tmaxItems: 2\n\t\t}\n\t};\n}\n\n//#endregion\nexport { parseMapDef };\n//# sourceMappingURL=map.js.map","//#region src/utils/zod-to-json-schema/parsers/nativeEnum.ts\nfunction parseNativeEnumDef(def) {\n\tconst object = def.values;\n\tconst actualKeys = Object.keys(def.values).filter((key) => {\n\t\treturn typeof object[object[key]] !== \"number\";\n\t});\n\tconst actualValues = actualKeys.map((key) => object[key]);\n\tconst parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n\treturn {\n\t\ttype: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n\t\tenum: actualValues\n\t};\n}\n\n//#endregion\nexport { parseNativeEnumDef };\n//# sourceMappingURL=nativeEnum.js.map","import { parseAnyDef } from \"./any.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/never.ts\nfunction parseNeverDef(refs) {\n\treturn refs.target === \"openAi\" ? void 0 : { not: parseAnyDef({\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"not\"]\n\t}) };\n}\n\n//#endregion\nexport { parseNeverDef };\n//# sourceMappingURL=never.js.map","//#region src/utils/zod-to-json-schema/parsers/null.ts\nfunction parseNullDef(refs) {\n\treturn refs.target === \"openApi3\" ? {\n\t\tenum: [\"null\"],\n\t\tnullable: true\n\t} : { type: \"null\" };\n}\n\n//#endregion\nexport { parseNullDef };\n//# sourceMappingURL=null.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/union.ts\nconst primitiveMappings = {\n\tZodString: \"string\",\n\tZodNumber: \"number\",\n\tZodBigInt: \"integer\",\n\tZodBoolean: \"boolean\",\n\tZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n\tif (refs.target === \"openApi3\") return asAnyOf(def, refs);\n\tconst options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\tif (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n\t\tconst types = options.reduce((types$1, x) => {\n\t\t\tconst type = primitiveMappings[x._def.typeName];\n\t\t\treturn type && !types$1.includes(type) ? [...types$1, type] : types$1;\n\t\t}, []);\n\t\treturn { type: types.length > 1 ? types : types[0] };\n\t} else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n\t\tconst types = options.reduce((acc, x) => {\n\t\t\tconst type = typeof x._def.value;\n\t\t\tswitch (type) {\n\t\t\t\tcase \"string\":\n\t\t\t\tcase \"number\":\n\t\t\t\tcase \"boolean\": return [...acc, type];\n\t\t\t\tcase \"bigint\": return [...acc, \"integer\"];\n\t\t\t\tcase \"object\":\n\t\t\t\t\tif (x._def.value === null) return [...acc, \"null\"];\n\t\t\t\t\treturn acc;\n\t\t\t\tcase \"symbol\":\n\t\t\t\tcase \"undefined\":\n\t\t\t\tcase \"function\":\n\t\t\t\tdefault: return acc;\n\t\t\t}\n\t\t}, []);\n\t\tif (types.length === options.length) {\n\t\t\tconst uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n\t\t\treturn {\n\t\t\t\ttype: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n\t\t\t\tenum: options.reduce((acc, x) => {\n\t\t\t\t\treturn acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n\t\t\t\t}, [])\n\t\t\t};\n\t\t}\n\t} else if (options.every((x) => x._def.typeName === \"ZodEnum\")) return {\n\t\ttype: \"string\",\n\t\tenum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x$1) => !acc.includes(x$1))], [])\n\t};\n\treturn asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n\tconst anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t`${i}`\n\t\t]\n\t})).filter((x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0));\n\treturn anyOf.length ? { anyOf } : void 0;\n};\n\n//#endregion\nexport { parseUnionDef, primitiveMappings };\n//# sourceMappingURL=union.js.map","import { primitiveMappings } from \"./union.js\";\nimport { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/nullable.ts\nfunction parseNullableDef(def, refs) {\n\tif ([\n\t\t\"ZodString\",\n\t\t\"ZodNumber\",\n\t\t\"ZodBigInt\",\n\t\t\"ZodBoolean\",\n\t\t\"ZodNull\"\n\t].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n\t\tif (refs.target === \"openApi3\") return {\n\t\t\ttype: primitiveMappings[def.innerType._def.typeName],\n\t\t\tnullable: true\n\t\t};\n\t\treturn { type: [primitiveMappings[def.innerType._def.typeName], \"null\"] };\n\t}\n\tif (refs.target === \"openApi3\") {\n\t\tconst base$1 = parseDef(def.innerType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath]\n\t\t});\n\t\tif (base$1 && \"$ref\" in base$1) return {\n\t\t\tallOf: [base$1],\n\t\t\tnullable: true\n\t\t};\n\t\treturn base$1 && {\n\t\t\t...base$1,\n\t\t\tnullable: true\n\t\t};\n\t}\n\tconst base = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn base && { anyOf: [base, { type: \"null\" }] };\n}\n\n//#endregion\nexport { parseNullableDef };\n//# sourceMappingURL=nullable.js.map","import { addErrorMessage, setResponseValueAndErrors } from \"../errorMessages.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/number.ts\nfunction parseNumberDef(def, refs) {\n\tconst res = { type: \"number\" };\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"int\":\n\t\t\tres.type = \"integer\";\n\t\t\taddErrorMessage(res, \"type\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"min\":\n\t\t\tif (refs.target === \"jsonSchema7\") if (check.inclusive) setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n\t\t\telse setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n\t\t\telse {\n\t\t\t\tif (!check.inclusive) res.exclusiveMinimum = true;\n\t\t\t\tsetResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (refs.target === \"jsonSchema7\") if (check.inclusive) setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n\t\t\telse setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n\t\t\telse {\n\t\t\t\tif (!check.inclusive) res.exclusiveMaximum = true;\n\t\t\t\tsetResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"multipleOf\":\n\t\t\tsetResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n\t\t\tbreak;\n\t}\n\treturn res;\n}\n\n//#endregion\nexport { parseNumberDef };\n//# sourceMappingURL=number.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/object.ts\nfunction parseObjectDef(def, refs) {\n\tconst forceOptionalIntoNullable = refs.target === \"openAi\";\n\tconst result = {\n\t\ttype: \"object\",\n\t\tproperties: {}\n\t};\n\tconst required = [];\n\tconst shape = def.shape();\n\tfor (const propName in shape) {\n\t\tlet propDef = shape[propName];\n\t\tif (propDef === void 0 || propDef._def === void 0) continue;\n\t\tlet propOptional = safeIsOptional(propDef);\n\t\tif (propOptional && forceOptionalIntoNullable) {\n\t\t\tif (propDef._def.typeName === \"ZodOptional\") propDef = propDef._def.innerType;\n\t\t\tif (!propDef.isNullable()) propDef = propDef.nullable();\n\t\t\tpropOptional = false;\n\t\t}\n\t\tconst parsedDef = parseDef(propDef._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t],\n\t\t\tpropertyPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t]\n\t\t});\n\t\tif (parsedDef === void 0) continue;\n\t\tresult.properties[propName] = parsedDef;\n\t\tif (!propOptional) required.push(propName);\n\t}\n\tif (required.length) result.required = required;\n\tconst additionalProperties = decideAdditionalProperties(def, refs);\n\tif (additionalProperties !== void 0) result.additionalProperties = additionalProperties;\n\treturn result;\n}\nfunction decideAdditionalProperties(def, refs) {\n\tif (def.catchall._def.typeName !== \"ZodNever\") return parseDef(def.catchall._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t});\n\tswitch (def.unknownKeys) {\n\t\tcase \"passthrough\": return refs.allowedAdditionalProperties;\n\t\tcase \"strict\": return refs.rejectedAdditionalProperties;\n\t\tcase \"strip\": return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n\t}\n}\nfunction safeIsOptional(schema) {\n\ttry {\n\t\treturn schema.isOptional();\n\t} catch {\n\t\treturn true;\n\t}\n}\n\n//#endregion\nexport { parseObjectDef };\n//# sourceMappingURL=object.js.map","import { parseAnyDef } from \"./any.js\";\nimport { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/optional.ts\nconst parseOptionalDef = (def, refs) => {\n\tif (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs);\n\tconst innerSchema = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"1\"\n\t\t]\n\t});\n\treturn innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs);\n};\n\n//#endregion\nexport { parseOptionalDef };\n//# sourceMappingURL=optional.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/pipeline.ts\nconst parsePipelineDef = (def, refs) => {\n\tif (refs.pipeStrategy === \"input\") return parseDef(def.in._def, refs);\n\telse if (refs.pipeStrategy === \"output\") return parseDef(def.out._def, refs);\n\tconst a = parseDef(def.in._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\tconst b = parseDef(def.out._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\ta ? \"1\" : \"0\"\n\t\t]\n\t});\n\treturn { allOf: [a, b].filter((x) => x !== void 0) };\n};\n\n//#endregion\nexport { parsePipelineDef };\n//# sourceMappingURL=pipeline.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/promise.ts\nfunction parsePromiseDef(def, refs) {\n\treturn parseDef(def.type._def, refs);\n}\n\n//#endregion\nexport { parsePromiseDef };\n//# sourceMappingURL=promise.js.map","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/set.ts\nfunction parseSetDef(def, refs) {\n\tconst items = parseDef(def.valueType._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t});\n\tconst schema = {\n\t\ttype: \"array\",\n\t\tuniqueItems: true,\n\t\titems\n\t};\n\tif (def.minSize) setResponseValueAndErrors(schema, \"minItems\", def.minSize.value, def.minSize.message, refs);\n\tif (def.maxSize) setResponseValueAndErrors(schema, \"maxItems\", def.maxSize.value, def.maxSize.message, refs);\n\treturn schema;\n}\n\n//#endregion\nexport { parseSetDef };\n//# sourceMappingURL=set.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/tuple.ts\nfunction parseTupleDef(def, refs) {\n\tif (def.rest) return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),\n\t\tadditionalItems: parseDef(def.rest._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalItems\"]\n\t\t})\n\t};\n\telse return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\tmaxItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])\n\t};\n}\n\n//#endregion\nexport { parseTupleDef };\n//# sourceMappingURL=tuple.js.map","import { parseAnyDef } from \"./any.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/undefined.ts\nfunction parseUndefinedDef(refs) {\n\treturn { not: parseAnyDef(refs) };\n}\n\n//#endregion\nexport { parseUndefinedDef };\n//# sourceMappingURL=undefined.js.map","import { parseAnyDef } from \"./any.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/unknown.ts\nfunction parseUnknownDef(refs) {\n\treturn parseAnyDef(refs);\n}\n\n//#endregion\nexport { parseUnknownDef };\n//# sourceMappingURL=unknown.js.map","import { parseDef } from \"../parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/parsers/readonly.ts\nconst parseReadonlyDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\n\n//#endregion\nexport { parseReadonlyDef };\n//# sourceMappingURL=readonly.js.map","import { parseAnyDef } from \"./parsers/any.js\";\nimport { parseArrayDef } from \"./parsers/array.js\";\nimport { parseBigintDef } from \"./parsers/bigint.js\";\nimport { parseBooleanDef } from \"./parsers/boolean.js\";\nimport { parseBrandedDef } from \"./parsers/branded.js\";\nimport { parseCatchDef } from \"./parsers/catch.js\";\nimport { parseDateDef } from \"./parsers/date.js\";\nimport { parseDefaultDef } from \"./parsers/default.js\";\nimport { parseEffectsDef } from \"./parsers/effects.js\";\nimport { parseEnumDef } from \"./parsers/enum.js\";\nimport { parseIntersectionDef } from \"./parsers/intersection.js\";\nimport { parseLiteralDef } from \"./parsers/literal.js\";\nimport { parseStringDef } from \"./parsers/string.js\";\nimport { parseRecordDef } from \"./parsers/record.js\";\nimport { parseMapDef } from \"./parsers/map.js\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.js\";\nimport { parseNeverDef } from \"./parsers/never.js\";\nimport { parseNullDef } from \"./parsers/null.js\";\nimport { parseUnionDef } from \"./parsers/union.js\";\nimport { parseNullableDef } from \"./parsers/nullable.js\";\nimport { parseNumberDef } from \"./parsers/number.js\";\nimport { parseObjectDef } from \"./parsers/object.js\";\nimport { parseOptionalDef } from \"./parsers/optional.js\";\nimport { parsePipelineDef } from \"./parsers/pipeline.js\";\nimport { parsePromiseDef } from \"./parsers/promise.js\";\nimport { parseSetDef } from \"./parsers/set.js\";\nimport { parseTupleDef } from \"./parsers/tuple.js\";\nimport { parseUndefinedDef } from \"./parsers/undefined.js\";\nimport { parseUnknownDef } from \"./parsers/unknown.js\";\nimport { parseReadonlyDef } from \"./parsers/readonly.js\";\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\n\n//#region src/utils/zod-to-json-schema/selectParser.ts\nconst selectParser = (def, typeName, refs) => {\n\tswitch (typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();\n\t\tcase ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs);\n\t\tcase ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\tcase ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;\n\t\tcase ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNaN:\n\t\tcase ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs);\n\t\tcase ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs);\n\t\tcase ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodFunction:\n\t\tcase ZodFirstPartyTypeKind.ZodVoid:\n\t\tcase ZodFirstPartyTypeKind.ZodSymbol: return void 0;\n\t\tdefault:\n /* c8 ignore next */\n\t\treturn ((_) => void 0)(typeName);\n\t}\n};\n\n//#endregion\nexport { selectParser };\n//# sourceMappingURL=selectParser.js.map","import { ignoreOverride } from \"./Options.js\";\nimport { getRelativePath } from \"./getRelativePath.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { selectParser } from \"./selectParser.js\";\n\n//#region src/utils/zod-to-json-schema/parseDef.ts\nfunction parseDef(def, refs, forceResolution = false) {\n\tconst seenItem = refs.seen.get(def);\n\tif (refs.override) {\n\t\tconst overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n\t\tif (overrideResult !== ignoreOverride) return overrideResult;\n\t}\n\tif (seenItem && !forceResolution) {\n\t\tconst seenSchema = get$ref(seenItem, refs);\n\t\tif (seenSchema !== void 0) return seenSchema;\n\t}\n\tconst newItem = {\n\t\tdef,\n\t\tpath: refs.currentPath,\n\t\tjsonSchema: void 0\n\t};\n\trefs.seen.set(def, newItem);\n\tconst jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n\tconst jsonSchema = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n\tif (jsonSchema) addMeta(def, refs, jsonSchema);\n\tif (refs.postProcess) {\n\t\tconst postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\t\tnewItem.jsonSchema = jsonSchema;\n\t\treturn postProcessResult;\n\t}\n\tnewItem.jsonSchema = jsonSchema;\n\treturn jsonSchema;\n}\nconst get$ref = (item, refs) => {\n\tswitch (refs.$refStrategy) {\n\t\tcase \"root\": return { $ref: item.path.join(\"/\") };\n\t\tcase \"relative\": return { $ref: getRelativePath(refs.currentPath, item.path) };\n\t\tcase \"none\":\n\t\tcase \"seen\":\n\t\t\tif (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n\t\t\t\tconsole.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n\t\t\t\treturn parseAnyDef(refs);\n\t\t\t}\n\t\t\treturn refs.$refStrategy === \"seen\" ? parseAnyDef(refs) : void 0;\n\t}\n};\nconst addMeta = (def, refs, jsonSchema) => {\n\tif (def.description) {\n\t\tjsonSchema.description = def.description;\n\t\tif (refs.markdownDescription) jsonSchema.markdownDescription = def.description;\n\t}\n\treturn jsonSchema;\n};\n\n//#endregion\nexport { parseDef };\n//# sourceMappingURL=parseDef.js.map","import { getRefs } from \"./Refs.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { parseDef } from \"./parseDef.js\";\n\n//#region src/utils/zod-to-json-schema/zodToJsonSchema.ts\nconst zodToJsonSchema = (schema, options) => {\n\tconst refs = getRefs(options);\n\tlet definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name$1, schema$1]) => ({\n\t\t...acc,\n\t\t[name$1]: parseDef(schema$1._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.basePath,\n\t\t\t\trefs.definitionPath,\n\t\t\t\tname$1\n\t\t\t]\n\t\t}, true) ?? parseAnyDef(refs)\n\t}), {}) : void 0;\n\tconst name = typeof options === \"string\" ? options : options?.nameStrategy === \"title\" ? void 0 : options?.name;\n\tconst main = parseDef(schema._def, name === void 0 ? refs : {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname\n\t\t]\n\t}, false) ?? parseAnyDef(refs);\n\tconst title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n\tif (title !== void 0) main.title = title;\n\tif (refs.flags.hasReferencedOpenAiAnyType) {\n\t\tif (!definitions) definitions = {};\n\t\tif (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = {\n\t\t\ttype: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"array\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\titems: { $ref: refs.$refStrategy === \"relative\" ? \"1\" : [\n\t\t\t\t...refs.basePath,\n\t\t\t\trefs.definitionPath,\n\t\t\t\trefs.openAiAnyTypeName\n\t\t\t].join(\"/\") }\n\t\t};\n\t}\n\tconst combined = name === void 0 ? definitions ? {\n\t\t...main,\n\t\t[refs.definitionPath]: definitions\n\t} : main : {\n\t\t$ref: [\n\t\t\t...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname\n\t\t].join(\"/\"),\n\t\t[refs.definitionPath]: {\n\t\t\t...definitions,\n\t\t\t[name]: main\n\t\t}\n\t};\n\tif (refs.target === \"jsonSchema7\") combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n\telse if (refs.target === \"jsonSchema2019-09\" || refs.target === \"openAi\") combined.$schema = \"https://json-schema.org/draft/2019-09/schema#\";\n\tif (refs.target === \"openAi\" && (\"anyOf\" in combined || \"oneOf\" in combined || \"allOf\" in combined || \"type\" in combined && Array.isArray(combined.type))) console.warn(\"Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.\");\n\treturn combined;\n};\n\n//#endregion\nexport { zodToJsonSchema };\n//# sourceMappingURL=zodToJsonSchema.js.map","import { defaultOptions, getDefaultOptions, ignoreOverride } from \"./Options.js\";\nimport { getRefs } from \"./Refs.js\";\nimport { addErrorMessage, setResponseValueAndErrors } from \"./errorMessages.js\";\nimport { getRelativePath } from \"./getRelativePath.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { parseArrayDef } from \"./parsers/array.js\";\nimport { parseBigintDef } from \"./parsers/bigint.js\";\nimport { parseBooleanDef } from \"./parsers/boolean.js\";\nimport { parseBrandedDef } from \"./parsers/branded.js\";\nimport { parseCatchDef } from \"./parsers/catch.js\";\nimport { parseDateDef } from \"./parsers/date.js\";\nimport { parseDefaultDef } from \"./parsers/default.js\";\nimport { parseEffectsDef } from \"./parsers/effects.js\";\nimport { parseEnumDef } from \"./parsers/enum.js\";\nimport { parseIntersectionDef } from \"./parsers/intersection.js\";\nimport { parseLiteralDef } from \"./parsers/literal.js\";\nimport { parseStringDef, zodPatterns } from \"./parsers/string.js\";\nimport { parseRecordDef } from \"./parsers/record.js\";\nimport { parseMapDef } from \"./parsers/map.js\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.js\";\nimport { parseNeverDef } from \"./parsers/never.js\";\nimport { parseNullDef } from \"./parsers/null.js\";\nimport { parseUnionDef, primitiveMappings } from \"./parsers/union.js\";\nimport { parseNullableDef } from \"./parsers/nullable.js\";\nimport { parseNumberDef } from \"./parsers/number.js\";\nimport { parseObjectDef } from \"./parsers/object.js\";\nimport { parseOptionalDef } from \"./parsers/optional.js\";\nimport { parsePipelineDef } from \"./parsers/pipeline.js\";\nimport { parsePromiseDef } from \"./parsers/promise.js\";\nimport { parseSetDef } from \"./parsers/set.js\";\nimport { parseTupleDef } from \"./parsers/tuple.js\";\nimport { parseUndefinedDef } from \"./parsers/undefined.js\";\nimport { parseUnknownDef } from \"./parsers/unknown.js\";\nimport { parseReadonlyDef } from \"./parsers/readonly.js\";\nimport { selectParser } from \"./selectParser.js\";\nimport { parseDef } from \"./parseDef.js\";\nimport { zodToJsonSchema } from \"./zodToJsonSchema.js\";\n","import { $ZodRegistry, globalRegistry } from \"./registries.js\";\nimport { getEnumValues } from \"./util.js\";\nexport class JSONSchemaGenerator {\n constructor(params) {\n this.counter = 0;\n this.metadataRegistry = params?.metadata ?? globalRegistry;\n this.target = params?.target ?? \"draft-2020-12\";\n this.unrepresentable = params?.unrepresentable ?? \"throw\";\n this.override = params?.override ?? (() => { });\n this.io = params?.io ?? \"output\";\n this.seen = new Map();\n }\n process(schema, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n const formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n };\n // check for schema in seens\n const seen = this.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n this.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n const parent = schema._zod.parent;\n if (parent) {\n // schema was cloned from another schema\n result.ref = parent;\n this.process(parent, params);\n this.seen.get(parent).isParent = true;\n }\n else {\n const _json = result.schema;\n switch (def.type) {\n case \"string\": {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n result.schema.allOf = [\n ...regexes.map((regex) => ({\n ...(this.target === \"draft-7\" ? { type: \"string\" } : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n break;\n }\n case \"number\": {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\")\n json.exclusiveMinimum = exclusiveMinimum;\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\")\n json.exclusiveMaximum = exclusiveMaximum;\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n break;\n }\n case \"boolean\": {\n const json = _json;\n json.type = \"boolean\";\n break;\n }\n case \"bigint\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"symbol\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"null\": {\n _json.type = \"null\";\n break;\n }\n case \"any\": {\n break;\n }\n case \"unknown\": {\n break;\n }\n case \"undefined\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"void\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"never\": {\n _json.not = {};\n break;\n }\n case \"date\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"array\": {\n const json = _json;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = this.process(def.element, { ...params, path: [...params.path, \"items\"] });\n break;\n }\n case \"object\": {\n const json = _json;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape; // params.shapeCache.get(schema)!;\n for (const key in shape) {\n json.properties[key] = this.process(shape[key], {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n // const optionalKeys = new Set(def.optional);\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (this.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (this.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = this.process(def.catchall, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n break;\n }\n case \"union\": {\n const json = _json;\n json.anyOf = def.options.map((x, i) => this.process(x, {\n ...params,\n path: [...params.path, \"anyOf\", i],\n }));\n break;\n }\n case \"intersection\": {\n const json = _json;\n const a = this.process(def.left, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = this.process(def.right, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n break;\n }\n case \"tuple\": {\n const json = _json;\n json.type = \"array\";\n const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, \"prefixItems\", i] }));\n if (this.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n }\n else {\n json.items = prefixItems;\n }\n if (def.rest) {\n const rest = this.process(def.rest, {\n ...params,\n path: [...params.path, \"items\"],\n });\n if (this.target === \"draft-2020-12\") {\n json.items = rest;\n }\n else {\n json.additionalItems = rest;\n }\n }\n // additionalItems\n if (def.rest) {\n json.items = this.process(def.rest, {\n ...params,\n path: [...params.path, \"items\"],\n });\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n break;\n }\n case \"record\": {\n const json = _json;\n json.type = \"object\";\n json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, \"propertyNames\"] });\n json.additionalProperties = this.process(def.valueType, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n break;\n }\n case \"map\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"set\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"enum\": {\n const json = _json;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n break;\n }\n case \"literal\": {\n const json = _json;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n json.const = val;\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"string\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n break;\n }\n case \"file\": {\n const json = _json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(json, file);\n }\n else {\n json.anyOf = mime.map((m) => {\n const mFile = { ...file, contentMediaType: m };\n return mFile;\n });\n }\n }\n else {\n Object.assign(json, file);\n }\n // if (this.unrepresentable === \"throw\") {\n // throw new Error(\"File cannot be represented in JSON Schema\");\n // }\n break;\n }\n case \"transform\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"nullable\": {\n const inner = this.process(def.innerType, params);\n _json.anyOf = [inner, { type: \"null\" }];\n break;\n }\n case \"nonoptional\": {\n this.process(def.innerType, params);\n result.ref = def.innerType;\n break;\n }\n case \"success\": {\n const json = _json;\n json.type = \"boolean\";\n break;\n }\n case \"default\": {\n this.process(def.innerType, params);\n result.ref = def.innerType;\n _json.default = JSON.parse(JSON.stringify(def.defaultValue));\n break;\n }\n case \"prefault\": {\n this.process(def.innerType, params);\n result.ref = def.innerType;\n if (this.io === \"input\")\n _json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n break;\n }\n case \"catch\": {\n // use conditionals\n this.process(def.innerType, params);\n result.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n _json.default = catchValue;\n break;\n }\n case \"nan\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n break;\n }\n case \"template_literal\": {\n const json = _json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n json.type = \"string\";\n json.pattern = pattern.source;\n break;\n }\n case \"pipe\": {\n const innerType = this.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n this.process(innerType, params);\n result.ref = innerType;\n break;\n }\n case \"readonly\": {\n this.process(def.innerType, params);\n result.ref = def.innerType;\n _json.readOnly = true;\n break;\n }\n // passthrough types\n case \"promise\": {\n this.process(def.innerType, params);\n result.ref = def.innerType;\n break;\n }\n case \"optional\": {\n this.process(def.innerType, params);\n result.ref = def.innerType;\n break;\n }\n case \"lazy\": {\n const innerType = schema._zod.innerType;\n this.process(innerType, params);\n result.ref = innerType;\n break;\n }\n case \"custom\": {\n if (this.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n break;\n }\n default: {\n def;\n }\n }\n }\n }\n // metadata\n const meta = this.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (this.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (this.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from this.seen in case it was overwritten\n const _result = this.seen.get(schema);\n return _result.schema;\n }\n emit(schema, _params) {\n const params = {\n cycles: _params?.cycles ?? \"ref\",\n reused: _params?.reused ?? \"inline\",\n // unrepresentable: _params?.unrepresentable ?? \"throw\",\n // uri: _params?.uri ?? ((id) => `${id}`),\n external: _params?.external ?? undefined,\n };\n // iterate over seen map;\n const root = this.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // initialize result with root schema fields\n // Object.assign(result, seen.cached);\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = this.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (params.external) {\n const externalId = params.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${this.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = params.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${this.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (params.cycles === \"throw\") {\n for (const entry of this.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of this.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (params.external) {\n const ext = params.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = this.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (params.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n // flatten _refs\n const flattenRef = (zodSchema, params) => {\n const seen = this.seen.get(zodSchema);\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n // already seen\n if (seen.ref === null) {\n return;\n }\n // flatten ref if defined\n const ref = seen.ref;\n seen.ref = null; // prevent recursion\n if (ref) {\n flattenRef(ref, params);\n // merge referenced schema into current\n const refSchema = this.seen.get(ref).schema;\n if (refSchema.$ref && params.target === \"draft-7\") {\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n Object.assign(schema, _cached); // prevent overwriting any fields in the original schema\n }\n }\n // execute overrides\n if (!seen.isParent)\n this.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...this.seen.entries()].reverse()) {\n flattenRef(entry[0], { target: this.target });\n }\n const result = {};\n if (this.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (this.target === \"draft-7\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else {\n console.warn(`Invalid target: ${this.target}`);\n }\n if (params.external?.uri) {\n const id = params.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = params.external.uri(id);\n }\n Object.assign(result, root.def);\n // build defs object\n const defs = params.external?.defs ?? {};\n for (const entry of this.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (params.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (this.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to .emit() is functionally independent\n // though the seen map is shared\n return JSON.parse(JSON.stringify(result));\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n }\n}\nexport function toJSONSchema(input, _params) {\n if (input instanceof $ZodRegistry) {\n const gen = new JSONSchemaGenerator(_params);\n const defs = {};\n for (const entry of input._idmap.entries()) {\n const [_, schema] = entry;\n gen.process(schema);\n }\n const schemas = {};\n const external = {\n registry: input,\n uri: _params?.uri,\n defs,\n };\n for (const entry of input._idmap.entries()) {\n const [key, schema] = entry;\n schemas[key] = gen.emit(schema, {\n ..._params,\n external,\n });\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = gen.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n const gen = new JSONSchemaGenerator(_params);\n gen.process(input);\n return gen.emit(input, _params);\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const schema = _schema;\n const def = schema._zod.def;\n switch (def.type) {\n case \"string\":\n case \"number\":\n case \"bigint\":\n case \"boolean\":\n case \"date\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"any\":\n case \"unknown\":\n case \"never\":\n case \"void\":\n case \"literal\":\n case \"enum\":\n case \"nan\":\n case \"file\":\n case \"template_literal\":\n return false;\n case \"array\": {\n return isTransforming(def.element, ctx);\n }\n case \"object\": {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n case \"union\": {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n case \"intersection\": {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n case \"tuple\": {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n case \"record\": {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n case \"map\": {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n case \"set\": {\n return isTransforming(def.valueType, ctx);\n }\n // inner types\n case \"promise\":\n case \"optional\":\n case \"nonoptional\":\n case \"nullable\":\n case \"readonly\":\n return isTransforming(def.innerType, ctx);\n case \"lazy\":\n return isTransforming(def.getter(), ctx);\n case \"default\": {\n return isTransforming(def.innerType, ctx);\n }\n case \"prefault\": {\n return isTransforming(def.innerType, ctx);\n }\n case \"custom\": {\n return false;\n }\n case \"transform\": {\n return true;\n }\n case \"pipe\": {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n case \"success\": {\n return false;\n }\n case \"catch\": {\n return false;\n }\n default:\n def;\n }\n throw new Error(`Unknown schema type: ${def.type}`);\n}\n","export function deepCompareStrict(a, b) {\n const typeofa = typeof a;\n if (typeofa !== typeof b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) {\n return false;\n }\n const length = a.length;\n if (length !== b.length) {\n return false;\n }\n for (let i = 0; i < length; i++) {\n if (!deepCompareStrict(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n if (typeofa === 'object') {\n if (!a || !b) {\n return a === b;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n const length = aKeys.length;\n if (length !== bKeys.length) {\n return false;\n }\n for (const k of aKeys) {\n if (!deepCompareStrict(a[k], b[k])) {\n return false;\n }\n }\n return true;\n }\n return a === b;\n}\n","export function encodePointer(p) {\n return encodeURI(escapePointer(p));\n}\nexport function escapePointer(p) {\n return p.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","import { encodePointer } from './pointer.js';\nexport const schemaKeyword = {\n additionalItems: true,\n unevaluatedItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n unevaluatedProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\nexport const schemaArrayKeyword = {\n prefixItems: true,\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\nexport const schemaMapKeyword = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependentSchemas: true\n};\nexport const ignoredKeyword = {\n id: true,\n $id: true,\n $ref: true,\n $schema: true,\n $anchor: true,\n $vocabulary: true,\n $comment: true,\n default: true,\n enum: true,\n const: true,\n required: true,\n type: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\nexport let initialBaseURI = typeof self !== 'undefined' &&\n self.location &&\n self.location.origin !== 'null'\n ?\n new URL(self.location.origin + self.location.pathname + location.search)\n : new URL('https://github.com/cfworker');\nexport function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') {\n if (schema && typeof schema === 'object' && !Array.isArray(schema)) {\n const id = schema.$id || schema.id;\n if (id) {\n const url = new URL(id, baseURI.href);\n if (url.hash.length > 1) {\n lookup[url.href] = schema;\n }\n else {\n url.hash = '';\n if (basePointer === '') {\n baseURI = url;\n }\n else {\n dereference(schema, lookup, baseURI);\n }\n }\n }\n }\n else if (schema !== true && schema !== false) {\n return lookup;\n }\n const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : '');\n if (lookup[schemaURI] !== undefined) {\n throw new Error(`Duplicate schema URI \"${schemaURI}\".`);\n }\n lookup[schemaURI] = schema;\n if (schema === true || schema === false) {\n return lookup;\n }\n if (schema.__absolute_uri__ === undefined) {\n Object.defineProperty(schema, '__absolute_uri__', {\n enumerable: false,\n value: schemaURI\n });\n }\n if (schema.$ref && schema.__absolute_ref__ === undefined) {\n const url = new URL(schema.$ref, baseURI.href);\n url.hash = url.hash;\n Object.defineProperty(schema, '__absolute_ref__', {\n enumerable: false,\n value: url.href\n });\n }\n if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) {\n const url = new URL(schema.$recursiveRef, baseURI.href);\n url.hash = url.hash;\n Object.defineProperty(schema, '__absolute_recursive_ref__', {\n enumerable: false,\n value: url.href\n });\n }\n if (schema.$anchor) {\n const url = new URL('#' + schema.$anchor, baseURI.href);\n lookup[url.href] = schema;\n }\n for (let key in schema) {\n if (ignoredKeyword[key]) {\n continue;\n }\n const keyBase = `${basePointer}/${encodePointer(key)}`;\n const subSchema = schema[key];\n if (Array.isArray(subSchema)) {\n if (schemaArrayKeyword[key]) {\n const length = subSchema.length;\n for (let i = 0; i < length; i++) {\n dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`);\n }\n }\n }\n else if (schemaMapKeyword[key]) {\n for (let subKey in subSchema) {\n dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`);\n }\n }\n else {\n dereference(subSchema, lookup, baseURI, keyBase);\n }\n }\n return lookup;\n}\n","const DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?(z|[+-]\\d\\d(?::?\\d\\d)?)?$/i;\nconst HOSTNAME = /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i;\nconst URIREF = /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;\nconst URITEMPLATE = /^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i;\nconst URL_ = /^(?:(?:https?|ftp):\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-?)*[a-z\\u{00a1}-\\u{ffff}0-9]+)(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-?)*[a-z\\u{00a1}-\\u{ffff}0-9]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu;\nconst UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;\nconst JSON_POINTER = /^(?:\\/(?:[^~/]|~0|~1)*)*$/;\nconst JSON_POINTER_URI_FRAGMENT = /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;\nconst RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;\nconst EMAIL = (input) => {\n if (input[0] === '\"')\n return false;\n const [name, host, ...rest] = input.split('@');\n if (!name ||\n !host ||\n rest.length !== 0 ||\n name.length > 64 ||\n host.length > 253)\n return false;\n if (name[0] === '.' || name.endsWith('.') || name.includes('..'))\n return false;\n if (!/^[a-z0-9.-]+$/i.test(host) ||\n !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name))\n return false;\n return host\n .split('.')\n .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part));\n};\nconst IPV4 = /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/;\nconst IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i;\nconst DURATION = (input) => input.length > 1 &&\n input.length < 80 &&\n (/^P\\d+([.,]\\d+)?W$/.test(input) ||\n (/^P[\\dYMDTHS]*(\\d[.,]\\d+)?[YMDHS]$/.test(input) &&\n /^P([.,\\d]+Y)?([.,\\d]+M)?([.,\\d]+D)?(T([.,\\d]+H)?([.,\\d]+M)?([.,\\d]+S)?)?$/.test(input)));\nfunction bind(r) {\n return r.test.bind(r);\n}\nexport const format = {\n date,\n time: time.bind(undefined, false),\n 'date-time': date_time,\n duration: DURATION,\n uri,\n 'uri-reference': bind(URIREF),\n 'uri-template': bind(URITEMPLATE),\n url: bind(URL_),\n email: EMAIL,\n hostname: bind(HOSTNAME),\n ipv4: bind(IPV4),\n ipv6: bind(IPV6),\n regex: regex,\n uuid: bind(UUID),\n 'json-pointer': bind(JSON_POINTER),\n 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT),\n 'relative-json-pointer': bind(RELATIVE_JSON_POINTER)\n};\nfunction isLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nfunction date(str) {\n const matches = str.match(DATE);\n if (!matches)\n return false;\n const year = +matches[1];\n const month = +matches[2];\n const day = +matches[3];\n return (month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction time(full, str) {\n const matches = str.match(TIME);\n if (!matches)\n return false;\n const hour = +matches[1];\n const minute = +matches[2];\n const second = +matches[3];\n const timeZone = !!matches[5];\n return (((hour <= 23 && minute <= 59 && second <= 59) ||\n (hour == 23 && minute == 59 && second == 60)) &&\n (!full || timeZone));\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction date_time(str) {\n const dateTime = str.split(DATE_TIME_SEPARATOR);\n return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]);\n}\nconst NOT_URI_FRAGMENT = /\\/|:/;\nconst URI_PATTERN = /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;\nfunction uri(str) {\n return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str);\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n if (Z_ANCHOR.test(str))\n return false;\n try {\n new RegExp(str, 'u');\n return true;\n }\n catch (e) {\n return false;\n }\n}\n","export var OutputFormat;\n(function (OutputFormat) {\n OutputFormat[OutputFormat[\"Flag\"] = 1] = \"Flag\";\n OutputFormat[OutputFormat[\"Basic\"] = 2] = \"Basic\";\n OutputFormat[OutputFormat[\"Detailed\"] = 4] = \"Detailed\";\n})(OutputFormat || (OutputFormat = {}));\n","export function ucs2length(s) {\n let result = 0;\n let length = s.length;\n let index = 0;\n let charCode;\n while (index < length) {\n result++;\n charCode = s.charCodeAt(index++);\n if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) {\n charCode = s.charCodeAt(index);\n if ((charCode & 0xfc00) == 0xdc00) {\n index++;\n }\n }\n }\n return result;\n}\n","import { deepCompareStrict } from './deep-compare-strict.js';\nimport { dereference } from './dereference.js';\nimport { format } from './format.js';\nimport { encodePointer } from './pointer.js';\nimport { ucs2length } from './ucs2-length.js';\nexport function validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) {\n if (schema === true) {\n return { valid: true, errors: [] };\n }\n if (schema === false) {\n return {\n valid: false,\n errors: [\n {\n instanceLocation,\n keyword: 'false',\n keywordLocation: instanceLocation,\n error: 'False boolean schema.'\n }\n ]\n };\n }\n const rawInstanceType = typeof instance;\n let instanceType;\n switch (rawInstanceType) {\n case 'boolean':\n case 'number':\n case 'string':\n instanceType = rawInstanceType;\n break;\n case 'object':\n if (instance === null) {\n instanceType = 'null';\n }\n else if (Array.isArray(instance)) {\n instanceType = 'array';\n }\n else {\n instanceType = 'object';\n }\n break;\n default:\n throw new Error(`Instances of \"${rawInstanceType}\" type are not supported.`);\n }\n const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema;\n const errors = [];\n if ($recursiveAnchor === true && recursiveAnchor === null) {\n recursiveAnchor = schema;\n }\n if ($recursiveRef === '#') {\n const refSchema = recursiveAnchor === null\n ? lookup[__absolute_recursive_ref__]\n : recursiveAnchor;\n const keywordLocation = `${schemaLocation}/$recursiveRef`;\n const result = validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: '$recursiveRef',\n keywordLocation,\n error: 'A subschema had errors.'\n }, ...result.errors);\n }\n }\n if ($ref !== undefined) {\n const uri = __absolute_ref__ || $ref;\n const refSchema = lookup[uri];\n if (refSchema === undefined) {\n let message = `Unresolved $ref \"${$ref}\".`;\n if (__absolute_ref__ && __absolute_ref__ !== $ref) {\n message += ` Absolute URI \"${__absolute_ref__}\".`;\n }\n message += `\\nKnown schemas:\\n- ${Object.keys(lookup).join('\\n- ')}`;\n throw new Error(message);\n }\n const keywordLocation = `${schemaLocation}/$ref`;\n const result = validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: '$ref',\n keywordLocation,\n error: 'A subschema had errors.'\n }, ...result.errors);\n }\n if (draft === '4' || draft === '7') {\n return { valid: errors.length === 0, errors };\n }\n }\n if (Array.isArray($type)) {\n let length = $type.length;\n let valid = false;\n for (let i = 0; i < length; i++) {\n if (instanceType === $type[i] ||\n ($type[i] === 'integer' &&\n instanceType === 'number' &&\n instance % 1 === 0 &&\n instance === instance)) {\n valid = true;\n break;\n }\n }\n if (!valid) {\n errors.push({\n instanceLocation,\n keyword: 'type',\n keywordLocation: `${schemaLocation}/type`,\n error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type.join('\", \"')}\".`\n });\n }\n }\n else if ($type === 'integer') {\n if (instanceType !== 'number' || instance % 1 || instance !== instance) {\n errors.push({\n instanceLocation,\n keyword: 'type',\n keywordLocation: `${schemaLocation}/type`,\n error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type}\".`\n });\n }\n }\n else if ($type !== undefined && instanceType !== $type) {\n errors.push({\n instanceLocation,\n keyword: 'type',\n keywordLocation: `${schemaLocation}/type`,\n error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type}\".`\n });\n }\n if ($const !== undefined) {\n if (instanceType === 'object' || instanceType === 'array') {\n if (!deepCompareStrict(instance, $const)) {\n errors.push({\n instanceLocation,\n keyword: 'const',\n keywordLocation: `${schemaLocation}/const`,\n error: `Instance does not match ${JSON.stringify($const)}.`\n });\n }\n }\n else if (instance !== $const) {\n errors.push({\n instanceLocation,\n keyword: 'const',\n keywordLocation: `${schemaLocation}/const`,\n error: `Instance does not match ${JSON.stringify($const)}.`\n });\n }\n }\n if ($enum !== undefined) {\n if (instanceType === 'object' || instanceType === 'array') {\n if (!$enum.some(value => deepCompareStrict(instance, value))) {\n errors.push({\n instanceLocation,\n keyword: 'enum',\n keywordLocation: `${schemaLocation}/enum`,\n error: `Instance does not match any of ${JSON.stringify($enum)}.`\n });\n }\n }\n else if (!$enum.some(value => instance === value)) {\n errors.push({\n instanceLocation,\n keyword: 'enum',\n keywordLocation: `${schemaLocation}/enum`,\n error: `Instance does not match any of ${JSON.stringify($enum)}.`\n });\n }\n }\n if ($not !== undefined) {\n const keywordLocation = `${schemaLocation}/not`;\n const result = validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation);\n if (result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'not',\n keywordLocation,\n error: 'Instance matched \"not\" schema.'\n });\n }\n }\n let subEvaluateds = [];\n if ($anyOf !== undefined) {\n const keywordLocation = `${schemaLocation}/anyOf`;\n const errorsLength = errors.length;\n let anyValid = false;\n for (let i = 0; i < $anyOf.length; i++) {\n const subSchema = $anyOf[i];\n const subEvaluated = Object.create(evaluated);\n const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n errors.push(...result.errors);\n anyValid = anyValid || result.valid;\n if (result.valid) {\n subEvaluateds.push(subEvaluated);\n }\n }\n if (anyValid) {\n errors.length = errorsLength;\n }\n else {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'anyOf',\n keywordLocation,\n error: 'Instance does not match any subschemas.'\n });\n }\n }\n if ($allOf !== undefined) {\n const keywordLocation = `${schemaLocation}/allOf`;\n const errorsLength = errors.length;\n let allValid = true;\n for (let i = 0; i < $allOf.length; i++) {\n const subSchema = $allOf[i];\n const subEvaluated = Object.create(evaluated);\n const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n errors.push(...result.errors);\n allValid = allValid && result.valid;\n if (result.valid) {\n subEvaluateds.push(subEvaluated);\n }\n }\n if (allValid) {\n errors.length = errorsLength;\n }\n else {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'allOf',\n keywordLocation,\n error: `Instance does not match every subschema.`\n });\n }\n }\n if ($oneOf !== undefined) {\n const keywordLocation = `${schemaLocation}/oneOf`;\n const errorsLength = errors.length;\n const matches = $oneOf.filter((subSchema, i) => {\n const subEvaluated = Object.create(evaluated);\n const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n errors.push(...result.errors);\n if (result.valid) {\n subEvaluateds.push(subEvaluated);\n }\n return result.valid;\n }).length;\n if (matches === 1) {\n errors.length = errorsLength;\n }\n else {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'oneOf',\n keywordLocation,\n error: `Instance does not match exactly one subschema (${matches} matches).`\n });\n }\n }\n if (instanceType === 'object' || instanceType === 'array') {\n Object.assign(evaluated, ...subEvaluateds);\n }\n if ($if !== undefined) {\n const keywordLocation = `${schemaLocation}/if`;\n const conditionResult = validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid;\n if (conditionResult) {\n if ($then !== undefined) {\n const thenResult = validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated);\n if (!thenResult.valid) {\n errors.push({\n instanceLocation,\n keyword: 'if',\n keywordLocation,\n error: `Instance does not match \"then\" schema.`\n }, ...thenResult.errors);\n }\n }\n }\n else if ($else !== undefined) {\n const elseResult = validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated);\n if (!elseResult.valid) {\n errors.push({\n instanceLocation,\n keyword: 'if',\n keywordLocation,\n error: `Instance does not match \"else\" schema.`\n }, ...elseResult.errors);\n }\n }\n }\n if (instanceType === 'object') {\n if ($required !== undefined) {\n for (const key of $required) {\n if (!(key in instance)) {\n errors.push({\n instanceLocation,\n keyword: 'required',\n keywordLocation: `${schemaLocation}/required`,\n error: `Instance does not have required property \"${key}\".`\n });\n }\n }\n }\n const keys = Object.keys(instance);\n if ($minProperties !== undefined && keys.length < $minProperties) {\n errors.push({\n instanceLocation,\n keyword: 'minProperties',\n keywordLocation: `${schemaLocation}/minProperties`,\n error: `Instance does not have at least ${$minProperties} properties.`\n });\n }\n if ($maxProperties !== undefined && keys.length > $maxProperties) {\n errors.push({\n instanceLocation,\n keyword: 'maxProperties',\n keywordLocation: `${schemaLocation}/maxProperties`,\n error: `Instance does not have at least ${$maxProperties} properties.`\n });\n }\n if ($propertyNames !== undefined) {\n const keywordLocation = `${schemaLocation}/propertyNames`;\n for (const key in instance) {\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'propertyNames',\n keywordLocation,\n error: `Property name \"${key}\" does not match schema.`\n }, ...result.errors);\n }\n }\n }\n if ($dependentRequired !== undefined) {\n const keywordLocation = `${schemaLocation}/dependantRequired`;\n for (const key in $dependentRequired) {\n if (key in instance) {\n const required = $dependentRequired[key];\n for (const dependantKey of required) {\n if (!(dependantKey in instance)) {\n errors.push({\n instanceLocation,\n keyword: 'dependentRequired',\n keywordLocation,\n error: `Instance has \"${key}\" but does not have \"${dependantKey}\".`\n });\n }\n }\n }\n }\n }\n if ($dependentSchemas !== undefined) {\n for (const key in $dependentSchemas) {\n const keywordLocation = `${schemaLocation}/dependentSchemas`;\n if (key in instance) {\n const result = validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'dependentSchemas',\n keywordLocation,\n error: `Instance has \"${key}\" but does not match dependant schema.`\n }, ...result.errors);\n }\n }\n }\n }\n if ($dependencies !== undefined) {\n const keywordLocation = `${schemaLocation}/dependencies`;\n for (const key in $dependencies) {\n if (key in instance) {\n const propsOrSchema = $dependencies[key];\n if (Array.isArray(propsOrSchema)) {\n for (const dependantKey of propsOrSchema) {\n if (!(dependantKey in instance)) {\n errors.push({\n instanceLocation,\n keyword: 'dependencies',\n keywordLocation,\n error: `Instance has \"${key}\" but does not have \"${dependantKey}\".`\n });\n }\n }\n }\n else {\n const result = validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'dependencies',\n keywordLocation,\n error: `Instance has \"${key}\" but does not match dependant schema.`\n }, ...result.errors);\n }\n }\n }\n }\n }\n const thisEvaluated = Object.create(null);\n let stop = false;\n if ($properties !== undefined) {\n const keywordLocation = `${schemaLocation}/properties`;\n for (const key in $properties) {\n if (!(key in instance)) {\n continue;\n }\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`);\n if (result.valid) {\n evaluated[key] = thisEvaluated[key] = true;\n }\n else {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'properties',\n keywordLocation,\n error: `Property \"${key}\" does not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n if (!stop && $patternProperties !== undefined) {\n const keywordLocation = `${schemaLocation}/patternProperties`;\n for (const pattern in $patternProperties) {\n const regex = new RegExp(pattern, 'u');\n const subSchema = $patternProperties[pattern];\n for (const key in instance) {\n if (!regex.test(key)) {\n continue;\n }\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`);\n if (result.valid) {\n evaluated[key] = thisEvaluated[key] = true;\n }\n else {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'patternProperties',\n keywordLocation,\n error: `Property \"${key}\" matches pattern \"${pattern}\" but does not match associated schema.`\n }, ...result.errors);\n }\n }\n }\n }\n if (!stop && $additionalProperties !== undefined) {\n const keywordLocation = `${schemaLocation}/additionalProperties`;\n for (const key in instance) {\n if (thisEvaluated[key]) {\n continue;\n }\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n if (result.valid) {\n evaluated[key] = true;\n }\n else {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'additionalProperties',\n keywordLocation,\n error: `Property \"${key}\" does not match additional properties schema.`\n }, ...result.errors);\n }\n }\n }\n else if (!stop && $unevaluatedProperties !== undefined) {\n const keywordLocation = `${schemaLocation}/unevaluatedProperties`;\n for (const key in instance) {\n if (!evaluated[key]) {\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n if (result.valid) {\n evaluated[key] = true;\n }\n else {\n errors.push({\n instanceLocation,\n keyword: 'unevaluatedProperties',\n keywordLocation,\n error: `Property \"${key}\" does not match unevaluated properties schema.`\n }, ...result.errors);\n }\n }\n }\n }\n }\n else if (instanceType === 'array') {\n if ($maxItems !== undefined && instance.length > $maxItems) {\n errors.push({\n instanceLocation,\n keyword: 'maxItems',\n keywordLocation: `${schemaLocation}/maxItems`,\n error: `Array has too many items (${instance.length} > ${$maxItems}).`\n });\n }\n if ($minItems !== undefined && instance.length < $minItems) {\n errors.push({\n instanceLocation,\n keyword: 'minItems',\n keywordLocation: `${schemaLocation}/minItems`,\n error: `Array has too few items (${instance.length} < ${$minItems}).`\n });\n }\n const length = instance.length;\n let i = 0;\n let stop = false;\n if ($prefixItems !== undefined) {\n const keywordLocation = `${schemaLocation}/prefixItems`;\n const length2 = Math.min($prefixItems.length, length);\n for (; i < length2; i++) {\n const result = validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'prefixItems',\n keywordLocation,\n error: `Items did not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n if ($items !== undefined) {\n const keywordLocation = `${schemaLocation}/items`;\n if (Array.isArray($items)) {\n const length2 = Math.min($items.length, length);\n for (; i < length2; i++) {\n const result = validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'items',\n keywordLocation,\n error: `Items did not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n else {\n for (; i < length; i++) {\n const result = validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'items',\n keywordLocation,\n error: `Items did not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n if (!stop && $additionalItems !== undefined) {\n const keywordLocation = `${schemaLocation}/additionalItems`;\n for (; i < length; i++) {\n const result = validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'additionalItems',\n keywordLocation,\n error: `Items did not match additional items schema.`\n }, ...result.errors);\n }\n }\n }\n }\n if ($contains !== undefined) {\n if (length === 0 && $minContains === undefined) {\n errors.push({\n instanceLocation,\n keyword: 'contains',\n keywordLocation: `${schemaLocation}/contains`,\n error: `Array is empty. It must contain at least one item matching the schema.`\n });\n }\n else if ($minContains !== undefined && length < $minContains) {\n errors.push({\n instanceLocation,\n keyword: 'minContains',\n keywordLocation: `${schemaLocation}/minContains`,\n error: `Array has less items (${length}) than minContains (${$minContains}).`\n });\n }\n else {\n const keywordLocation = `${schemaLocation}/contains`;\n const errorsLength = errors.length;\n let contained = 0;\n for (let j = 0; j < length; j++) {\n const result = validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation);\n if (result.valid) {\n evaluated[j] = true;\n contained++;\n }\n else {\n errors.push(...result.errors);\n }\n }\n if (contained >= ($minContains || 0)) {\n errors.length = errorsLength;\n }\n if ($minContains === undefined &&\n $maxContains === undefined &&\n contained === 0) {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'contains',\n keywordLocation,\n error: `Array does not contain item matching schema.`\n });\n }\n else if ($minContains !== undefined && contained < $minContains) {\n errors.push({\n instanceLocation,\n keyword: 'minContains',\n keywordLocation: `${schemaLocation}/minContains`,\n error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.`\n });\n }\n else if ($maxContains !== undefined && contained > $maxContains) {\n errors.push({\n instanceLocation,\n keyword: 'maxContains',\n keywordLocation: `${schemaLocation}/maxContains`,\n error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.`\n });\n }\n }\n }\n if (!stop && $unevaluatedItems !== undefined) {\n const keywordLocation = `${schemaLocation}/unevaluatedItems`;\n for (i; i < length; i++) {\n if (evaluated[i]) {\n continue;\n }\n const result = validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n evaluated[i] = true;\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'unevaluatedItems',\n keywordLocation,\n error: `Items did not match unevaluated items schema.`\n }, ...result.errors);\n }\n }\n }\n if ($uniqueItems) {\n for (let j = 0; j < length; j++) {\n const a = instance[j];\n const ao = typeof a === 'object' && a !== null;\n for (let k = 0; k < length; k++) {\n if (j === k) {\n continue;\n }\n const b = instance[k];\n const bo = typeof b === 'object' && b !== null;\n if (a === b || (ao && bo && deepCompareStrict(a, b))) {\n errors.push({\n instanceLocation,\n keyword: 'uniqueItems',\n keywordLocation: `${schemaLocation}/uniqueItems`,\n error: `Duplicate items at indexes ${j} and ${k}.`\n });\n j = Number.MAX_SAFE_INTEGER;\n k = Number.MAX_SAFE_INTEGER;\n }\n }\n }\n }\n }\n else if (instanceType === 'number') {\n if (draft === '4') {\n if ($minimum !== undefined &&\n (($exclusiveMinimum === true && instance <= $minimum) ||\n instance < $minimum)) {\n errors.push({\n instanceLocation,\n keyword: 'minimum',\n keywordLocation: `${schemaLocation}/minimum`,\n error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.`\n });\n }\n if ($maximum !== undefined &&\n (($exclusiveMaximum === true && instance >= $maximum) ||\n instance > $maximum)) {\n errors.push({\n instanceLocation,\n keyword: 'maximum',\n keywordLocation: `${schemaLocation}/maximum`,\n error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.`\n });\n }\n }\n else {\n if ($minimum !== undefined && instance < $minimum) {\n errors.push({\n instanceLocation,\n keyword: 'minimum',\n keywordLocation: `${schemaLocation}/minimum`,\n error: `${instance} is less than ${$minimum}.`\n });\n }\n if ($maximum !== undefined && instance > $maximum) {\n errors.push({\n instanceLocation,\n keyword: 'maximum',\n keywordLocation: `${schemaLocation}/maximum`,\n error: `${instance} is greater than ${$maximum}.`\n });\n }\n if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) {\n errors.push({\n instanceLocation,\n keyword: 'exclusiveMinimum',\n keywordLocation: `${schemaLocation}/exclusiveMinimum`,\n error: `${instance} is less than ${$exclusiveMinimum}.`\n });\n }\n if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) {\n errors.push({\n instanceLocation,\n keyword: 'exclusiveMaximum',\n keywordLocation: `${schemaLocation}/exclusiveMaximum`,\n error: `${instance} is greater than or equal to ${$exclusiveMaximum}.`\n });\n }\n }\n if ($multipleOf !== undefined) {\n const remainder = instance % $multipleOf;\n if (Math.abs(0 - remainder) >= 1.1920929e-7 &&\n Math.abs($multipleOf - remainder) >= 1.1920929e-7) {\n errors.push({\n instanceLocation,\n keyword: 'multipleOf',\n keywordLocation: `${schemaLocation}/multipleOf`,\n error: `${instance} is not a multiple of ${$multipleOf}.`\n });\n }\n }\n }\n else if (instanceType === 'string') {\n const length = $minLength === undefined && $maxLength === undefined\n ? 0\n : ucs2length(instance);\n if ($minLength !== undefined && length < $minLength) {\n errors.push({\n instanceLocation,\n keyword: 'minLength',\n keywordLocation: `${schemaLocation}/minLength`,\n error: `String is too short (${length} < ${$minLength}).`\n });\n }\n if ($maxLength !== undefined && length > $maxLength) {\n errors.push({\n instanceLocation,\n keyword: 'maxLength',\n keywordLocation: `${schemaLocation}/maxLength`,\n error: `String is too long (${length} > ${$maxLength}).`\n });\n }\n if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) {\n errors.push({\n instanceLocation,\n keyword: 'pattern',\n keywordLocation: `${schemaLocation}/pattern`,\n error: `String does not match pattern.`\n });\n }\n if ($format !== undefined &&\n format[$format] &&\n !format[$format](instance)) {\n errors.push({\n instanceLocation,\n keyword: 'format',\n keywordLocation: `${schemaLocation}/format`,\n error: `String does not match format \"${$format}\".`\n });\n }\n }\n return { valid: errors.length === 0, errors };\n}\n","import { dereference } from './dereference.js';\nimport { validate } from './validate.js';\nexport class Validator {\n schema;\n draft;\n shortCircuit;\n lookup;\n constructor(schema, draft = '2019-09', shortCircuit = true) {\n this.schema = schema;\n this.draft = draft;\n this.shortCircuit = shortCircuit;\n this.lookup = dereference(schema);\n }\n validate(instance) {\n return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit);\n }\n addSchema(schema, id) {\n if (id) {\n schema = { ...schema, $id: id };\n }\n dereference(schema, this.lookup);\n }\n}\n","export * from './deep-compare-strict.js';\nexport * from './dereference.js';\nexport * from './format.js';\nexport * from './pointer.js';\nexport * from './types.js';\nexport * from './ucs2-length.js';\nexport * from './validate.js';\nexport * from './validator.js';\n","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { interopZodObjectStrict, interopZodTransformInputSchema, isZodObjectV4, isZodSchemaV3, isZodSchemaV4 } from \"./types/zod.js\";\nimport { zodToJsonSchema } from \"./zod-to-json-schema/zodToJsonSchema.js\";\nimport \"./zod-to-json-schema/index.js\";\nimport { toJSONSchema } from \"zod/v4/core\";\nimport { Validator, deepCompareStrict, dereference } from \"@cfworker/json-schema\";\n\n//#region src/utils/json_schema.ts\nvar json_schema_exports = {};\n__export(json_schema_exports, {\n\tValidator: () => Validator,\n\tdeepCompareStrict: () => deepCompareStrict,\n\ttoJsonSchema: () => toJsonSchema,\n\tvalidatesOnlyStrings: () => validatesOnlyStrings\n});\n/**\n* Converts a Zod schema or JSON schema to a JSON schema.\n* @param schema - The schema to convert.\n* @returns The converted schema.\n*/\nfunction toJsonSchema(schema) {\n\tif (isZodSchemaV4(schema)) {\n\t\tconst inputSchema = interopZodTransformInputSchema(schema, true);\n\t\tif (isZodObjectV4(inputSchema)) {\n\t\t\tconst strictSchema = interopZodObjectStrict(inputSchema, true);\n\t\t\treturn toJSONSchema(strictSchema);\n\t\t} else return toJSONSchema(schema);\n\t}\n\tif (isZodSchemaV3(schema)) return zodToJsonSchema(schema);\n\treturn schema;\n}\n/**\n* Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n* (like recursive or unresolvable refs).\n*\n* @param schema - The schema to validate.\n* @returns `true` if the schema validates only strings, `false` otherwise.\n*/\nfunction validatesOnlyStrings(schema) {\n\tif (!schema || typeof schema !== \"object\" || Object.keys(schema).length === 0 || Array.isArray(schema)) return false;\n\tif (\"type\" in schema) {\n\t\tif (typeof schema.type === \"string\") return schema.type === \"string\";\n\t\tif (Array.isArray(schema.type)) return schema.type.every((t) => t === \"string\");\n\t\treturn false;\n\t}\n\tif (\"enum\" in schema) return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === \"string\");\n\tif (\"const\" in schema) return typeof schema.const === \"string\";\n\tif (\"allOf\" in schema && Array.isArray(schema.allOf)) return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n\tif (\"anyOf\" in schema && Array.isArray(schema.anyOf) || \"oneOf\" in schema && Array.isArray(schema.oneOf)) {\n\t\tconst subschemas = \"anyOf\" in schema ? schema.anyOf : schema.oneOf;\n\t\treturn subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema));\n\t}\n\tif (\"not\" in schema) return false;\n\tif (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n\t\tconst ref = schema.$ref;\n\t\tconst resolved = dereference(schema);\n\t\tif (resolved[ref]) return validatesOnlyStrings(resolved[ref]);\n\t\treturn false;\n\t}\n\treturn false;\n}\n\n//#endregion\nexport { Validator, deepCompareStrict, json_schema_exports, toJsonSchema, validatesOnlyStrings };\n//# sourceMappingURL=json_schema.js.map","//#region src/runnables/utils.ts\nfunction isRunnableInterface(thing) {\n\treturn thing ? thing.lc_runnable : false;\n}\n/**\n* Utility to filter the root event in the streamEvents implementation.\n* This is simply binding the arguments to the namespace to make save on\n* a bit of typing in the streamEvents implementation.\n*\n* TODO: Refactor and remove.\n*/\nvar _RootEventFilter = class {\n\tincludeNames;\n\tincludeTypes;\n\tincludeTags;\n\texcludeNames;\n\texcludeTypes;\n\texcludeTags;\n\tconstructor(fields) {\n\t\tthis.includeNames = fields.includeNames;\n\t\tthis.includeTypes = fields.includeTypes;\n\t\tthis.includeTags = fields.includeTags;\n\t\tthis.excludeNames = fields.excludeNames;\n\t\tthis.excludeTypes = fields.excludeTypes;\n\t\tthis.excludeTags = fields.excludeTags;\n\t}\n\tincludeEvent(event, rootType) {\n\t\tlet include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0;\n\t\tconst eventTags = event.tags ?? [];\n\t\tif (this.includeNames !== void 0) include = include || this.includeNames.includes(event.name);\n\t\tif (this.includeTypes !== void 0) include = include || this.includeTypes.includes(rootType);\n\t\tif (this.includeTags !== void 0) include = include || eventTags.some((tag) => this.includeTags?.includes(tag));\n\t\tif (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(event.name);\n\t\tif (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(rootType);\n\t\tif (this.excludeTags !== void 0) include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag));\n\t\treturn include;\n\t}\n};\n\n//#endregion\nexport { _RootEventFilter, isRunnableInterface };\n//# sourceMappingURL=utils.js.map","//#region src/runnables/graph_mermaid.ts\nfunction _escapeNodeLabel(nodeLabel) {\n\treturn nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\nconst MARKDOWN_SPECIAL_CHARS = [\n\t\"*\",\n\t\"_\",\n\t\"`\"\n];\nfunction _generateMermaidGraphStyles(nodeColors) {\n\tlet styles = \"\";\n\tfor (const [className, color] of Object.entries(nodeColors)) styles += `\\tclassDef ${className} ${color};\\n`;\n\treturn styles;\n}\n/**\n* Draws a Mermaid graph using the provided graph data\n*/\nfunction drawMermaid(nodes, edges, config) {\n\tconst { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = \"linear\", wrapLabelNWords = 9 } = config ?? {};\n\tlet mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n` : \"graph TD;\\n\";\n\tif (withStyles) {\n\t\tconst defaultClassLabel = \"default\";\n\t\tconst formatDict = { [defaultClassLabel]: \"{0}({1})\" };\n\t\tif (firstNode !== void 0) formatDict[firstNode] = \"{0}([{1}]):::first\";\n\t\tif (lastNode !== void 0) formatDict[lastNode] = \"{0}([{1}]):::last\";\n\t\tfor (const [key, node] of Object.entries(nodes)) {\n\t\t\tconst nodeName = node.name.split(\":\").pop() ?? \"\";\n\t\t\tconst label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName;\n\t\t\tlet finalLabel = label;\n\t\t\tif (Object.keys(node.metadata ?? {}).length) finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join(\"\\n\")}`;\n\t\t\tconst nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace(\"{0}\", _escapeNodeLabel(key)).replace(\"{1}\", finalLabel);\n\t\t\tmermaidGraph += `\\t${nodeLabel}\\n`;\n\t\t}\n\t}\n\tconst edgeGroups = {};\n\tfor (const edge of edges) {\n\t\tconst srcParts = edge.source.split(\":\");\n\t\tconst tgtParts = edge.target.split(\":\");\n\t\tconst commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(\":\");\n\t\tif (!edgeGroups[commonPrefix]) edgeGroups[commonPrefix] = [];\n\t\tedgeGroups[commonPrefix].push(edge);\n\t}\n\tconst seenSubgraphs = /* @__PURE__ */ new Set();\n\tfunction addSubgraph(edges$1, prefix) {\n\t\tconst selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target;\n\t\tif (prefix && !selfLoop) {\n\t\t\tconst subgraph = prefix.split(\":\").pop();\n\t\t\tif (seenSubgraphs.has(subgraph)) throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);\n\t\t\tseenSubgraphs.add(subgraph);\n\t\t\tmermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n\t\t}\n\t\tfor (const edge of edges$1) {\n\t\t\tconst { source, target, data, conditional } = edge;\n\t\t\tlet edgeLabel = \"\";\n\t\t\tif (data !== void 0) {\n\t\t\t\tlet edgeData = data;\n\t\t\t\tconst words = edgeData.split(\" \");\n\t\t\t\tif (words.length > wrapLabelNWords) edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(\" \")).join(\" 
 \");\n\t\t\t\tedgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `;\n\t\t\t} else edgeLabel = conditional ? \" -.-> \" : \" --> \";\n\t\t\tmermaidGraph += `\\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n\t\t}\n\t\tfor (const nestedPrefix in edgeGroups) if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n\t\tif (prefix && !selfLoop) mermaidGraph += \"\tend\\n\";\n\t}\n\taddSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\tfor (const prefix in edgeGroups) if (!prefix.includes(\":\") && prefix !== \"\") addSubgraph(edgeGroups[prefix], prefix);\n\tif (withStyles) mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n\treturn mermaidGraph;\n}\n/**\n* Renders Mermaid graph using the Mermaid.INK API.\n*\n* @example\n* ```javascript\n* const image = await drawMermaidImage(mermaidSyntax, {\n* backgroundColor: \"white\",\n* imageType: \"png\",\n* });\n* fs.writeFileSync(\"image.png\", image);\n* ```\n*\n* @param mermaidSyntax - The Mermaid syntax to render.\n* @param config - The configuration for the image.\n* @returns The image as a Blob.\n*/\nasync function drawMermaidImage(mermaidSyntax, config) {\n\tlet backgroundColor = config?.backgroundColor ?? \"white\";\n\tconst imageType = config?.imageType ?? \"png\";\n\tconst mermaidSyntaxEncoded = btoa(mermaidSyntax);\n\tif (backgroundColor !== void 0) {\n\t\tconst hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n\t\tif (!hexColorPattern.test(backgroundColor)) backgroundColor = `!${backgroundColor}`;\n\t}\n\tconst imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n\tconst res = await fetch(imageUrl);\n\tif (!res.ok) throw new Error([\n\t\t`Failed to render the graph using the Mermaid.INK API.`,\n\t\t`Status code: ${res.status}`,\n\t\t`Status text: ${res.statusText}`\n\t].join(\"\\n\"));\n\tconst content = await res.blob();\n\treturn content;\n}\n\n//#endregion\nexport { drawMermaid, drawMermaidImage };\n//# sourceMappingURL=graph_mermaid.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\nimport { v4, validate } from \"uuid\";\n\n//#region src/runnables/graph.ts\nvar graph_exports = {};\n__export(graph_exports, { Graph: () => Graph });\nfunction nodeDataStr(id, data) {\n\tif (id !== void 0 && !validate(id)) return id;\n\telse if (isRunnableInterface(data)) try {\n\t\tlet dataStr = data.getName();\n\t\tdataStr = dataStr.startsWith(\"Runnable\") ? dataStr.slice(8) : dataStr;\n\t\treturn dataStr;\n\t} catch {\n\t\treturn data.getName();\n\t}\n\telse return data.name ?? \"UnknownSchema\";\n}\nfunction nodeDataJson(node) {\n\tif (isRunnableInterface(node.data)) return {\n\t\ttype: \"runnable\",\n\t\tdata: {\n\t\t\tid: node.data.lc_id,\n\t\t\tname: node.data.getName()\n\t\t}\n\t};\n\telse return {\n\t\ttype: \"schema\",\n\t\tdata: {\n\t\t\t...toJsonSchema(node.data.schema),\n\t\t\ttitle: node.data.name\n\t\t}\n\t};\n}\nvar Graph = class Graph {\n\tnodes = {};\n\tedges = [];\n\tconstructor(params) {\n\t\tthis.nodes = params?.nodes ?? this.nodes;\n\t\tthis.edges = params?.edges ?? this.edges;\n\t}\n\ttoJSON() {\n\t\tconst stableNodeIds = {};\n\t\tObject.values(this.nodes).forEach((node, i) => {\n\t\t\tstableNodeIds[node.id] = validate(node.id) ? i : node.id;\n\t\t});\n\t\treturn {\n\t\t\tnodes: Object.values(this.nodes).map((node) => ({\n\t\t\t\tid: stableNodeIds[node.id],\n\t\t\t\t...nodeDataJson(node)\n\t\t\t})),\n\t\t\tedges: this.edges.map((edge) => {\n\t\t\t\tconst item = {\n\t\t\t\t\tsource: stableNodeIds[edge.source],\n\t\t\t\t\ttarget: stableNodeIds[edge.target]\n\t\t\t\t};\n\t\t\t\tif (typeof edge.data !== \"undefined\") item.data = edge.data;\n\t\t\t\tif (typeof edge.conditional !== \"undefined\") item.conditional = edge.conditional;\n\t\t\t\treturn item;\n\t\t\t})\n\t\t};\n\t}\n\taddNode(data, id, metadata) {\n\t\tif (id !== void 0 && this.nodes[id] !== void 0) throw new Error(`Node with id ${id} already exists`);\n\t\tconst nodeId = id ?? v4();\n\t\tconst node = {\n\t\t\tid: nodeId,\n\t\t\tdata,\n\t\t\tname: nodeDataStr(id, data),\n\t\t\tmetadata\n\t\t};\n\t\tthis.nodes[nodeId] = node;\n\t\treturn node;\n\t}\n\tremoveNode(node) {\n\t\tdelete this.nodes[node.id];\n\t\tthis.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id);\n\t}\n\taddEdge(source, target, data, conditional) {\n\t\tif (this.nodes[source.id] === void 0) throw new Error(`Source node ${source.id} not in graph`);\n\t\tif (this.nodes[target.id] === void 0) throw new Error(`Target node ${target.id} not in graph`);\n\t\tconst edge = {\n\t\t\tsource: source.id,\n\t\t\ttarget: target.id,\n\t\t\tdata,\n\t\t\tconditional\n\t\t};\n\t\tthis.edges.push(edge);\n\t\treturn edge;\n\t}\n\tfirstNode() {\n\t\treturn _firstNode(this);\n\t}\n\tlastNode() {\n\t\treturn _lastNode(this);\n\t}\n\t/**\n\t* Add all nodes and edges from another graph.\n\t* Note this doesn't check for duplicates, nor does it connect the graphs.\n\t*/\n\textend(graph, prefix = \"\") {\n\t\tlet finalPrefix = prefix;\n\t\tconst nodeIds = Object.values(graph.nodes).map((node) => node.id);\n\t\tif (nodeIds.every(validate)) finalPrefix = \"\";\n\t\tconst prefixed = (id) => {\n\t\t\treturn finalPrefix ? `${finalPrefix}:${id}` : id;\n\t\t};\n\t\tObject.entries(graph.nodes).forEach(([key, value]) => {\n\t\t\tthis.nodes[prefixed(key)] = {\n\t\t\t\t...value,\n\t\t\t\tid: prefixed(key)\n\t\t\t};\n\t\t});\n\t\tconst newEdges = graph.edges.map((edge) => {\n\t\t\treturn {\n\t\t\t\t...edge,\n\t\t\t\tsource: prefixed(edge.source),\n\t\t\t\ttarget: prefixed(edge.target)\n\t\t\t};\n\t\t});\n\t\tthis.edges = [...this.edges, ...newEdges];\n\t\tconst first = graph.firstNode();\n\t\tconst last = graph.lastNode();\n\t\treturn [first ? {\n\t\t\tid: prefixed(first.id),\n\t\t\tdata: first.data\n\t\t} : void 0, last ? {\n\t\t\tid: prefixed(last.id),\n\t\t\tdata: last.data\n\t\t} : void 0];\n\t}\n\ttrimFirstNode() {\n\t\tconst firstNode = this.firstNode();\n\t\tif (firstNode && _firstNode(this, [firstNode.id])) this.removeNode(firstNode);\n\t}\n\ttrimLastNode() {\n\t\tconst lastNode = this.lastNode();\n\t\tif (lastNode && _lastNode(this, [lastNode.id])) this.removeNode(lastNode);\n\t}\n\t/**\n\t* Return a new graph with all nodes re-identified,\n\t* using their unique, readable names where possible.\n\t*/\n\treid() {\n\t\tconst nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name]));\n\t\tconst nodeLabelCounts = /* @__PURE__ */ new Map();\n\t\tObject.values(nodeLabels).forEach((label) => {\n\t\t\tnodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n\t\t});\n\t\tconst getNodeId = (nodeId) => {\n\t\t\tconst label = nodeLabels[nodeId];\n\t\t\tif (validate(nodeId) && nodeLabelCounts.get(label) === 1) return label;\n\t\t\telse return nodeId;\n\t\t};\n\t\treturn new Graph({\n\t\t\tnodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), {\n\t\t\t\t...node,\n\t\t\t\tid: getNodeId(id)\n\t\t\t}])),\n\t\t\tedges: this.edges.map((edge) => ({\n\t\t\t\t...edge,\n\t\t\t\tsource: getNodeId(edge.source),\n\t\t\t\ttarget: getNodeId(edge.target)\n\t\t\t}))\n\t\t});\n\t}\n\tdrawMermaid(params) {\n\t\tconst { withStyles, curveStyle, nodeColors = {\n\t\t\tdefault: \"fill:#f2f0ff,line-height:1.2\",\n\t\t\tfirst: \"fill-opacity:0\",\n\t\t\tlast: \"fill:#bfb6fc\"\n\t\t}, wrapLabelNWords } = params ?? {};\n\t\tconst graph = this.reid();\n\t\tconst firstNode = graph.firstNode();\n\t\tconst lastNode = graph.lastNode();\n\t\treturn drawMermaid(graph.nodes, graph.edges, {\n\t\t\tfirstNode: firstNode?.id,\n\t\t\tlastNode: lastNode?.id,\n\t\t\twithStyles,\n\t\t\tcurveStyle,\n\t\t\tnodeColors,\n\t\t\twrapLabelNWords\n\t\t});\n\t}\n\tasync drawMermaidPng(params) {\n\t\tconst mermaidSyntax = this.drawMermaid(params);\n\t\treturn drawMermaidImage(mermaidSyntax, { backgroundColor: params?.backgroundColor });\n\t}\n};\n/**\n* Find the single node that is not a target of any edge.\n* Exclude nodes/sources with ids in the exclude list.\n* If there is no such node, or there are multiple, return undefined.\n* When drawing the graph, this node would be the origin.\n*/\nfunction _firstNode(graph, exclude = []) {\n\tconst targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target));\n\tconst found = [];\n\tfor (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !targets.has(node.id)) found.push(node);\n\treturn found.length === 1 ? found[0] : void 0;\n}\n/**\n* Find the single node that is not a source of any edge.\n* Exclude nodes/targets with ids in the exclude list.\n* If there is no such node, or there are multiple, return undefined.\n* When drawing the graph, this node would be the destination.\n*/\nfunction _lastNode(graph, exclude = []) {\n\tconst sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source));\n\tconst found = [];\n\tfor (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !sources.has(node.id)) found.push(node);\n\treturn found.length === 1 ? found[0] : void 0;\n}\n\n//#endregion\nexport { Graph, graph_exports };\n//# sourceMappingURL=graph.js.map","import { AIMessageChunk } from \"../messages/ai.js\";\nimport { BaseTracer } from \"./base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { GenerationChunk } from \"../outputs.js\";\n\n//#region src/tracers/event_stream.ts\nfunction assignName({ name, serialized }) {\n\tif (name !== void 0) return name;\n\tif (serialized?.name !== void 0) return serialized.name;\n\telse if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) return serialized.id[serialized.id.length - 1];\n\treturn \"Unnamed\";\n}\nconst isStreamEventsHandler = (handler) => handler.name === \"event_stream_tracer\";\n/**\n* Class that extends the `BaseTracer` class from the\n* `langchain.callbacks.tracers.base` module. It represents a callback\n* handler that logs the execution of runs and emits `RunLog` instances to a\n* `RunLogStream`.\n*/\nvar EventStreamCallbackHandler = class extends BaseTracer {\n\tautoClose = true;\n\tincludeNames;\n\tincludeTypes;\n\tincludeTags;\n\texcludeNames;\n\texcludeTypes;\n\texcludeTags;\n\trunInfoMap = /* @__PURE__ */ new Map();\n\ttappedPromises = /* @__PURE__ */ new Map();\n\ttransformStream;\n\twriter;\n\treceiveStream;\n\tname = \"event_stream_tracer\";\n\tlc_prefer_streaming = true;\n\tconstructor(fields) {\n\t\tsuper({\n\t\t\t_awaitHandler: true,\n\t\t\t...fields\n\t\t});\n\t\tthis.autoClose = fields?.autoClose ?? true;\n\t\tthis.includeNames = fields?.includeNames;\n\t\tthis.includeTypes = fields?.includeTypes;\n\t\tthis.includeTags = fields?.includeTags;\n\t\tthis.excludeNames = fields?.excludeNames;\n\t\tthis.excludeTypes = fields?.excludeTypes;\n\t\tthis.excludeTags = fields?.excludeTags;\n\t\tthis.transformStream = new TransformStream();\n\t\tthis.writer = this.transformStream.writable.getWriter();\n\t\tthis.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);\n\t}\n\t[Symbol.asyncIterator]() {\n\t\treturn this.receiveStream;\n\t}\n\tasync persistRun(_run) {}\n\t_includeRun(run) {\n\t\tconst runTags = run.tags ?? [];\n\t\tlet include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0;\n\t\tif (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name);\n\t\tif (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.runType);\n\t\tif (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0;\n\t\tif (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name);\n\t\tif (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.runType);\n\t\tif (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n\t\treturn include;\n\t}\n\tasync *tapOutputIterable(runId, outputStream) {\n\t\tconst firstChunk = await outputStream.next();\n\t\tif (firstChunk.done) return;\n\t\tconst runInfo = this.runInfoMap.get(runId);\n\t\tif (runInfo === void 0) {\n\t\t\tyield firstChunk.value;\n\t\t\treturn;\n\t\t}\n\t\tfunction _formatOutputChunk(eventType, data) {\n\t\t\tif (eventType === \"llm\" && typeof data === \"string\") return new GenerationChunk({ text: data });\n\t\t\treturn data;\n\t\t}\n\t\tlet tappedPromise = this.tappedPromises.get(runId);\n\t\tif (tappedPromise === void 0) {\n\t\t\tlet tappedPromiseResolver;\n\t\t\ttappedPromise = new Promise((resolve) => {\n\t\t\t\ttappedPromiseResolver = resolve;\n\t\t\t});\n\t\t\tthis.tappedPromises.set(runId, tappedPromise);\n\t\t\ttry {\n\t\t\t\tconst event = {\n\t\t\t\t\tevent: `on_${runInfo.runType}_stream`,\n\t\t\t\t\trun_id: runId,\n\t\t\t\t\tname: runInfo.name,\n\t\t\t\t\ttags: runInfo.tags,\n\t\t\t\t\tmetadata: runInfo.metadata,\n\t\t\t\t\tdata: {}\n\t\t\t\t};\n\t\t\t\tawait this.send({\n\t\t\t\t\t...event,\n\t\t\t\t\tdata: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) }\n\t\t\t\t}, runInfo);\n\t\t\t\tyield firstChunk.value;\n\t\t\t\tfor await (const chunk of outputStream) {\n\t\t\t\t\tif (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") await this.send({\n\t\t\t\t\t\t...event,\n\t\t\t\t\t\tdata: { chunk: _formatOutputChunk(runInfo.runType, chunk) }\n\t\t\t\t\t}, runInfo);\n\t\t\t\t\tyield chunk;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\ttappedPromiseResolver?.();\n\t\t\t}\n\t\t} else {\n\t\t\tyield firstChunk.value;\n\t\t\tfor await (const chunk of outputStream) yield chunk;\n\t\t}\n\t}\n\tasync send(payload, run) {\n\t\tif (this._includeRun(run)) await this.writer.write(payload);\n\t}\n\tasync sendEndEvent(payload, run) {\n\t\tconst tappedPromise = this.tappedPromises.get(payload.run_id);\n\t\tif (tappedPromise !== void 0) tappedPromise.then(() => {\n\t\t\tthis.send(payload, run);\n\t\t});\n\t\telse await this.send(payload, run);\n\t}\n\tasync onLLMStart(run) {\n\t\tconst runName = assignName(run);\n\t\tconst runType = run.inputs.messages !== void 0 ? \"chat_model\" : \"llm\";\n\t\tconst runInfo = {\n\t\t\ttags: run.tags ?? [],\n\t\t\tmetadata: run.extra?.metadata ?? {},\n\t\t\tname: runName,\n\t\t\trunType,\n\t\t\tinputs: run.inputs\n\t\t};\n\t\tthis.runInfoMap.set(run.id, runInfo);\n\t\tconst eventName = `on_${runType}_start`;\n\t\tawait this.send({\n\t\t\tevent: eventName,\n\t\t\tdata: { input: run.inputs },\n\t\t\tname: runName,\n\t\t\ttags: run.tags ?? [],\n\t\t\trun_id: run.id,\n\t\t\tmetadata: run.extra?.metadata ?? {}\n\t\t}, runInfo);\n\t}\n\tasync onLLMNewToken(run, token, kwargs) {\n\t\tconst runInfo = this.runInfoMap.get(run.id);\n\t\tlet chunk;\n\t\tlet eventName;\n\t\tif (runInfo === void 0) throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n\t\tif (this.runInfoMap.size === 1) return;\n\t\tif (runInfo.runType === \"chat_model\") {\n\t\t\teventName = \"on_chat_model_stream\";\n\t\t\tif (kwargs?.chunk === void 0) chunk = new AIMessageChunk({\n\t\t\t\tcontent: token,\n\t\t\t\tid: `run-${run.id}`\n\t\t\t});\n\t\t\telse chunk = kwargs.chunk.message;\n\t\t} else if (runInfo.runType === \"llm\") {\n\t\t\teventName = \"on_llm_stream\";\n\t\t\tif (kwargs?.chunk === void 0) chunk = new GenerationChunk({ text: token });\n\t\t\telse chunk = kwargs.chunk;\n\t\t} else throw new Error(`Unexpected run type ${runInfo.runType}`);\n\t\tawait this.send({\n\t\t\tevent: eventName,\n\t\t\tdata: { chunk },\n\t\t\trun_id: run.id,\n\t\t\tname: runInfo.name,\n\t\t\ttags: runInfo.tags,\n\t\t\tmetadata: runInfo.metadata\n\t\t}, runInfo);\n\t}\n\tasync onLLMEnd(run) {\n\t\tconst runInfo = this.runInfoMap.get(run.id);\n\t\tthis.runInfoMap.delete(run.id);\n\t\tlet eventName;\n\t\tif (runInfo === void 0) throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n\t\tconst generations = run.outputs?.generations;\n\t\tlet output;\n\t\tif (runInfo.runType === \"chat_model\") {\n\t\t\tfor (const generation of generations ?? []) {\n\t\t\t\tif (output !== void 0) break;\n\t\t\t\toutput = generation[0]?.message;\n\t\t\t}\n\t\t\teventName = \"on_chat_model_end\";\n\t\t} else if (runInfo.runType === \"llm\") {\n\t\t\toutput = {\n\t\t\t\tgenerations: generations?.map((generation) => {\n\t\t\t\t\treturn generation.map((chunk) => {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: chunk.text,\n\t\t\t\t\t\t\tgenerationInfo: chunk.generationInfo\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t}),\n\t\t\t\tllmOutput: run.outputs?.llmOutput ?? {}\n\t\t\t};\n\t\t\teventName = \"on_llm_end\";\n\t\t} else throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n\t\tawait this.sendEndEvent({\n\t\t\tevent: eventName,\n\t\t\tdata: {\n\t\t\t\toutput,\n\t\t\t\tinput: runInfo.inputs\n\t\t\t},\n\t\t\trun_id: run.id,\n\t\t\tname: runInfo.name,\n\t\t\ttags: runInfo.tags,\n\t\t\tmetadata: runInfo.metadata\n\t\t}, runInfo);\n\t}\n\tasync onChainStart(run) {\n\t\tconst runName = assignName(run);\n\t\tconst runType = run.run_type ?? \"chain\";\n\t\tconst runInfo = {\n\t\t\ttags: run.tags ?? [],\n\t\t\tmetadata: run.extra?.metadata ?? {},\n\t\t\tname: runName,\n\t\t\trunType: run.run_type\n\t\t};\n\t\tlet eventData = {};\n\t\tif (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n\t\t\teventData = {};\n\t\t\trunInfo.inputs = {};\n\t\t} else if (run.inputs.input !== void 0) {\n\t\t\teventData.input = run.inputs.input;\n\t\t\trunInfo.inputs = run.inputs.input;\n\t\t} else {\n\t\t\teventData.input = run.inputs;\n\t\t\trunInfo.inputs = run.inputs;\n\t\t}\n\t\tthis.runInfoMap.set(run.id, runInfo);\n\t\tawait this.send({\n\t\t\tevent: `on_${runType}_start`,\n\t\t\tdata: eventData,\n\t\t\tname: runName,\n\t\t\ttags: run.tags ?? [],\n\t\t\trun_id: run.id,\n\t\t\tmetadata: run.extra?.metadata ?? {}\n\t\t}, runInfo);\n\t}\n\tasync onChainEnd(run) {\n\t\tconst runInfo = this.runInfoMap.get(run.id);\n\t\tthis.runInfoMap.delete(run.id);\n\t\tif (runInfo === void 0) throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n\t\tconst eventName = `on_${run.run_type}_end`;\n\t\tconst inputs = run.inputs ?? runInfo.inputs ?? {};\n\t\tconst outputs = run.outputs?.output ?? run.outputs;\n\t\tconst data = {\n\t\t\toutput: outputs,\n\t\t\tinput: inputs\n\t\t};\n\t\tif (inputs.input && Object.keys(inputs).length === 1) {\n\t\t\tdata.input = inputs.input;\n\t\t\trunInfo.inputs = inputs.input;\n\t\t}\n\t\tawait this.sendEndEvent({\n\t\t\tevent: eventName,\n\t\t\tdata,\n\t\t\trun_id: run.id,\n\t\t\tname: runInfo.name,\n\t\t\ttags: runInfo.tags,\n\t\t\tmetadata: runInfo.metadata ?? {}\n\t\t}, runInfo);\n\t}\n\tasync onToolStart(run) {\n\t\tconst runName = assignName(run);\n\t\tconst runInfo = {\n\t\t\ttags: run.tags ?? [],\n\t\t\tmetadata: run.extra?.metadata ?? {},\n\t\t\tname: runName,\n\t\t\trunType: \"tool\",\n\t\t\tinputs: run.inputs ?? {}\n\t\t};\n\t\tthis.runInfoMap.set(run.id, runInfo);\n\t\tawait this.send({\n\t\t\tevent: \"on_tool_start\",\n\t\t\tdata: { input: run.inputs ?? {} },\n\t\t\tname: runName,\n\t\t\trun_id: run.id,\n\t\t\ttags: run.tags ?? [],\n\t\t\tmetadata: run.extra?.metadata ?? {}\n\t\t}, runInfo);\n\t}\n\tasync onToolEnd(run) {\n\t\tconst runInfo = this.runInfoMap.get(run.id);\n\t\tthis.runInfoMap.delete(run.id);\n\t\tif (runInfo === void 0) throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n\t\tif (runInfo.inputs === void 0) throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`);\n\t\tconst output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output;\n\t\tawait this.sendEndEvent({\n\t\t\tevent: \"on_tool_end\",\n\t\t\tdata: {\n\t\t\t\toutput,\n\t\t\t\tinput: runInfo.inputs\n\t\t\t},\n\t\t\trun_id: run.id,\n\t\t\tname: runInfo.name,\n\t\t\ttags: runInfo.tags,\n\t\t\tmetadata: runInfo.metadata\n\t\t}, runInfo);\n\t}\n\tasync onRetrieverStart(run) {\n\t\tconst runName = assignName(run);\n\t\tconst runType = \"retriever\";\n\t\tconst runInfo = {\n\t\t\ttags: run.tags ?? [],\n\t\t\tmetadata: run.extra?.metadata ?? {},\n\t\t\tname: runName,\n\t\t\trunType,\n\t\t\tinputs: { query: run.inputs.query }\n\t\t};\n\t\tthis.runInfoMap.set(run.id, runInfo);\n\t\tawait this.send({\n\t\t\tevent: \"on_retriever_start\",\n\t\t\tdata: { input: { query: run.inputs.query } },\n\t\t\tname: runName,\n\t\t\ttags: run.tags ?? [],\n\t\t\trun_id: run.id,\n\t\t\tmetadata: run.extra?.metadata ?? {}\n\t\t}, runInfo);\n\t}\n\tasync onRetrieverEnd(run) {\n\t\tconst runInfo = this.runInfoMap.get(run.id);\n\t\tthis.runInfoMap.delete(run.id);\n\t\tif (runInfo === void 0) throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n\t\tawait this.sendEndEvent({\n\t\t\tevent: \"on_retriever_end\",\n\t\t\tdata: {\n\t\t\t\toutput: run.outputs?.documents ?? run.outputs,\n\t\t\t\tinput: runInfo.inputs\n\t\t\t},\n\t\t\trun_id: run.id,\n\t\t\tname: runInfo.name,\n\t\t\ttags: runInfo.tags,\n\t\t\tmetadata: runInfo.metadata\n\t\t}, runInfo);\n\t}\n\tasync handleCustomEvent(eventName, data, runId) {\n\t\tconst runInfo = this.runInfoMap.get(runId);\n\t\tif (runInfo === void 0) throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`);\n\t\tawait this.send({\n\t\t\tevent: \"on_custom_event\",\n\t\t\trun_id: runId,\n\t\t\tname: eventName,\n\t\t\ttags: runInfo.tags,\n\t\t\tmetadata: runInfo.metadata,\n\t\t\tdata\n\t\t}, runInfo);\n\t}\n\tasync finish() {\n\t\tconst pendingPromises = [...this.tappedPromises.values()];\n\t\tPromise.all(pendingPromises).finally(() => {\n\t\t\tthis.writer.close();\n\t\t});\n\t}\n};\n\n//#endregion\nexport { EventStreamCallbackHandler, isStreamEventsHandler };\n//# sourceMappingURL=event_stream.js.map","import { BaseTracer } from \"./base.js\";\n\n//#region src/tracers/root_listener.ts\nvar RootListenersTracer = class extends BaseTracer {\n\tname = \"RootListenersTracer\";\n\t/** The Run's ID. Type UUID */\n\trootId;\n\tconfig;\n\targOnStart;\n\targOnEnd;\n\targOnError;\n\tconstructor({ config, onStart, onEnd, onError }) {\n\t\tsuper({ _awaitHandler: true });\n\t\tthis.config = config;\n\t\tthis.argOnStart = onStart;\n\t\tthis.argOnEnd = onEnd;\n\t\tthis.argOnError = onError;\n\t}\n\t/**\n\t* This is a legacy method only called once for an entire run tree\n\t* therefore not useful here\n\t* @param {Run} _ Not used\n\t*/\n\tpersistRun(_) {\n\t\treturn Promise.resolve();\n\t}\n\tasync onRunCreate(run) {\n\t\tif (this.rootId) return;\n\t\tthis.rootId = run.id;\n\t\tif (this.argOnStart) await this.argOnStart(run, this.config);\n\t}\n\tasync onRunUpdate(run) {\n\t\tif (run.id !== this.rootId) return;\n\t\tif (!run.error) {\n\t\t\tif (this.argOnEnd) await this.argOnEnd(run, this.config);\n\t\t} else if (this.argOnError) await this.argOnError(run, this.config);\n\t}\n};\n\n//#endregion\nexport { RootListenersTracer };\n//# sourceMappingURL=root_listener.js.map","import { IterableReadableStream } from \"../utils/stream.js\";\n\n//#region src/runnables/wrappers.ts\nfunction convertToHttpEventStream(stream) {\n\tconst encoder = new TextEncoder();\n\tconst finalStream = new ReadableStream({ async start(controller) {\n\t\tfor await (const chunk of stream) controller.enqueue(encoder.encode(`event: data\\ndata: ${JSON.stringify(chunk)}\\n\\n`));\n\t\tcontroller.enqueue(encoder.encode(\"event: end\\n\\n\"));\n\t\tcontroller.close();\n\t} });\n\treturn IterableReadableStream.fromReadableStream(finalStream);\n}\n\n//#endregion\nexport { convertToHttpEventStream };\n//# sourceMappingURL=wrappers.js.map","import { AsyncLocalStorageProviderSingleton } from \"../singletons/async_local_storage/index.js\";\nimport \"../singletons/index.js\";\nimport { pickRunnableConfigKeys } from \"./config.js\";\n\n//#region src/runnables/iter.ts\nfunction isIterableIterator(thing) {\n\treturn typeof thing === \"object\" && thing !== null && typeof thing[Symbol.iterator] === \"function\" && typeof thing.next === \"function\";\n}\nconst isIterator = (x) => x != null && typeof x === \"object\" && \"next\" in x && typeof x.next === \"function\";\nfunction isAsyncIterable(thing) {\n\treturn typeof thing === \"object\" && thing !== null && typeof thing[Symbol.asyncIterator] === \"function\";\n}\nfunction* consumeIteratorInContext(context, iter) {\n\twhile (true) {\n\t\tconst { value, done } = AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true);\n\t\tif (done) break;\n\t\telse yield value;\n\t}\n}\nasync function* consumeAsyncIterableInContext(context, iter) {\n\tconst iterator = iter[Symbol.asyncIterator]();\n\twhile (true) {\n\t\tconst { value, done } = await AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true);\n\t\tif (done) break;\n\t\telse yield value;\n\t}\n}\n\n//#endregion\nexport { consumeAsyncIterableInContext, consumeIteratorInContext, isAsyncIterable, isIterableIterator, isIterator };\n//# sourceMappingURL=iter.js.map","import { Serializable } from \"../load/serializable.js\";\nimport { ToolInputParsingException, _isToolCall } from \"../tools/utils.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/async_local_storage/index.js\";\nimport \"../singletons/index.js\";\nimport { DEFAULT_RECURSION_LIMIT, ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys } from \"./config.js\";\nimport { getAbortSignalError, raceWithSignal } from \"../utils/signal.js\";\nimport { AsyncGeneratorWithSetup, IterableReadableStream, atee, concat, pipeGeneratorWithSetup } from \"../utils/stream.js\";\nimport { LogStreamCallbackHandler, RunLog, RunLogPatch, isLogStreamHandler } from \"../tracers/log_stream.js\";\nimport { EventStreamCallbackHandler, isStreamEventsHandler } from \"../tracers/event_stream.js\";\nimport { AsyncCaller } from \"../utils/async_caller.js\";\nimport { RootListenersTracer } from \"../tracers/root_listener.js\";\nimport { _RootEventFilter, isRunnableInterface } from \"./utils.js\";\nimport { getSchemaDescription, interopParseAsync, isSimpleStringZodSchema } from \"../utils/types/zod.js\";\nimport { Graph } from \"./graph.js\";\nimport { convertToHttpEventStream } from \"./wrappers.js\";\nimport { consumeAsyncIterableInContext, consumeIteratorInContext, isAsyncIterable, isIterableIterator, isIterator } from \"./iter.js\";\nimport { z } from \"zod/v3\";\nimport pRetry from \"p-retry\";\nimport { v4 } from \"uuid\";\nimport { isTraceableFunction } from \"langsmith/singletons/traceable\";\n\n//#region src/runnables/base.ts\nfunction _coerceToDict(value, defaultKey) {\n\treturn value && !Array.isArray(value) && !(value instanceof Date) && typeof value === \"object\" ? value : { [defaultKey]: value };\n}\n/**\n* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or\n* transformed.\n*/\nvar Runnable = class extends Serializable {\n\tlc_runnable = true;\n\tname;\n\tgetName(suffix) {\n\t\tconst name = this.name ?? this.constructor.lc_name() ?? this.constructor.name;\n\t\treturn suffix ? `${name}${suffix}` : name;\n\t}\n\t/**\n\t* Add retry logic to an existing runnable.\n\t* @param fields.stopAfterAttempt The number of attempts to retry.\n\t* @param fields.onFailedAttempt A function that is called when a retry fails.\n\t* @returns A new RunnableRetry that, when invoked, will retry according to the parameters.\n\t*/\n\twithRetry(fields) {\n\t\treturn new RunnableRetry({\n\t\t\tbound: this,\n\t\t\tkwargs: {},\n\t\t\tconfig: {},\n\t\t\tmaxAttemptNumber: fields?.stopAfterAttempt,\n\t\t\t...fields\n\t\t});\n\t}\n\t/**\n\t* Bind config to a Runnable, returning a new Runnable.\n\t* @param config New configuration parameters to attach to the new runnable.\n\t* @returns A new RunnableBinding with a config matching what's passed.\n\t*/\n\twithConfig(config) {\n\t\treturn new RunnableBinding({\n\t\t\tbound: this,\n\t\t\tconfig,\n\t\t\tkwargs: {}\n\t\t});\n\t}\n\t/**\n\t* Create a new runnable from the current one that will try invoking\n\t* other passed fallback runnables if the initial invocation fails.\n\t* @param fields.fallbacks Other runnables to call if the runnable errors.\n\t* @returns A new RunnableWithFallbacks.\n\t*/\n\twithFallbacks(fields) {\n\t\tconst fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;\n\t\treturn new RunnableWithFallbacks({\n\t\t\trunnable: this,\n\t\t\tfallbacks\n\t\t});\n\t}\n\t_getOptionsList(options, length = 0) {\n\t\tif (Array.isArray(options) && options.length !== length) throw new Error(`Passed \"options\" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`);\n\t\tif (Array.isArray(options)) return options.map(ensureConfig);\n\t\tif (length > 1 && !Array.isArray(options) && options.runId) {\n\t\t\tconsole.warn(\"Provided runId will be used only for the first element of the batch.\");\n\t\t\tconst subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== \"runId\"));\n\t\t\treturn Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent));\n\t\t}\n\t\treturn Array.from({ length }, () => ensureConfig(options));\n\t}\n\tasync batch(inputs, options, batchOptions) {\n\t\tconst configList = this._getOptionsList(options ?? {}, inputs.length);\n\t\tconst maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;\n\t\tconst caller = new AsyncCaller({\n\t\t\tmaxConcurrency,\n\t\t\tonFailedAttempt: (e) => {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t});\n\t\tconst batchCalls = inputs.map((input, i) => caller.call(async () => {\n\t\t\ttry {\n\t\t\t\tconst result = await this.invoke(input, configList[i]);\n\t\t\t\treturn result;\n\t\t\t} catch (e) {\n\t\t\t\tif (batchOptions?.returnExceptions) return e;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}));\n\t\treturn Promise.all(batchCalls);\n\t}\n\t/**\n\t* Default streaming implementation.\n\t* Subclasses should override this method if they support streaming output.\n\t* @param input\n\t* @param options\n\t*/\n\tasync *_streamIterator(input, options) {\n\t\tyield this.invoke(input, options);\n\t}\n\t/**\n\t* Stream output in chunks.\n\t* @param input\n\t* @param options\n\t* @returns A readable stream that is also an iterable.\n\t*/\n\tasync stream(input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tconst wrappedGenerator = new AsyncGeneratorWithSetup({\n\t\t\tgenerator: this._streamIterator(input, config),\n\t\t\tconfig\n\t\t});\n\t\tawait wrappedGenerator.setup;\n\t\treturn IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n\t}\n\t_separateRunnableConfigFromCallOptions(options) {\n\t\tlet runnableConfig;\n\t\tif (options === void 0) runnableConfig = ensureConfig(options);\n\t\telse runnableConfig = ensureConfig({\n\t\t\tcallbacks: options.callbacks,\n\t\t\ttags: options.tags,\n\t\t\tmetadata: options.metadata,\n\t\t\trunName: options.runName,\n\t\t\tconfigurable: options.configurable,\n\t\t\trecursionLimit: options.recursionLimit,\n\t\t\tmaxConcurrency: options.maxConcurrency,\n\t\t\trunId: options.runId,\n\t\t\ttimeout: options.timeout,\n\t\t\tsignal: options.signal\n\t\t});\n\t\tconst callOptions = { ...options };\n\t\tdelete callOptions.callbacks;\n\t\tdelete callOptions.tags;\n\t\tdelete callOptions.metadata;\n\t\tdelete callOptions.runName;\n\t\tdelete callOptions.configurable;\n\t\tdelete callOptions.recursionLimit;\n\t\tdelete callOptions.maxConcurrency;\n\t\tdelete callOptions.runId;\n\t\tdelete callOptions.timeout;\n\t\tdelete callOptions.signal;\n\t\treturn [runnableConfig, callOptions];\n\t}\n\tasync _callWithConfig(func, input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName());\n\t\tdelete config.runId;\n\t\tlet output;\n\t\ttry {\n\t\t\tconst promise = func.call(this, input, config, runManager);\n\t\t\toutput = await raceWithSignal(promise, options?.signal);\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(_coerceToDict(output, \"output\"));\n\t\treturn output;\n\t}\n\t/**\n\t* Internal method that handles batching and configuration for a runnable\n\t* It takes a function, input values, and optional configuration, and\n\t* returns a promise that resolves to the output values.\n\t* @param func The function to be executed for each input value.\n\t* @param input The input values to be processed.\n\t* @param config Optional configuration for the function execution.\n\t* @returns A promise that resolves to the output values.\n\t*/\n\tasync _batchWithConfig(func, inputs, options, batchOptions) {\n\t\tconst optionsList = this._getOptionsList(options ?? {}, inputs.length);\n\t\tconst callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig));\n\t\tconst runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {\n\t\t\tconst handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], \"input\"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName());\n\t\t\tdelete optionsList[i].runId;\n\t\t\treturn handleStartRes;\n\t\t}));\n\t\tlet outputs;\n\t\ttry {\n\t\t\tconst promise = func.call(this, inputs, optionsList, runManagers, batchOptions);\n\t\t\toutputs = await raceWithSignal(promise, optionsList?.[0]?.signal);\n\t\t} catch (e) {\n\t\t\tawait Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));\n\t\t\tthrow e;\n\t\t}\n\t\tawait Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, \"output\"))));\n\t\treturn outputs;\n\t}\n\t/** @internal */\n\t_concatOutputChunks(first, second) {\n\t\treturn concat(first, second);\n\t}\n\t/**\n\t* Helper method to transform an Iterator of Input values into an Iterator of\n\t* Output values, with callbacks.\n\t* Use this to implement `stream()` or `transform()` in Runnable subclasses.\n\t*/\n\tasync *_transformStreamWithConfig(inputGenerator, transformer, options) {\n\t\tlet finalInput;\n\t\tlet finalInputSupported = true;\n\t\tlet finalOutput;\n\t\tlet finalOutputSupported = true;\n\t\tconst config = ensureConfig(options);\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst outerThis = this;\n\t\tasync function* wrapInputForTracing() {\n\t\t\tfor await (const chunk of inputGenerator) {\n\t\t\t\tif (finalInputSupported) if (finalInput === void 0) finalInput = chunk;\n\t\t\t\telse try {\n\t\t\t\t\tfinalInput = outerThis._concatOutputChunks(finalInput, chunk);\n\t\t\t\t} catch {\n\t\t\t\t\tfinalInput = void 0;\n\t\t\t\t\tfinalInputSupported = false;\n\t\t\t\t}\n\t\t\t\tyield chunk;\n\t\t\t}\n\t\t}\n\t\tlet runManager;\n\t\ttry {\n\t\t\tconst pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: \"\" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName()), options?.signal, config);\n\t\t\tdelete config.runId;\n\t\t\trunManager = pipe.setup;\n\t\t\tconst streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler);\n\t\t\tlet iterator = pipe.output;\n\t\t\tif (streamEventsHandler !== void 0 && runManager !== void 0) iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator);\n\t\t\tconst streamLogHandler = runManager?.handlers.find(isLogStreamHandler);\n\t\t\tif (streamLogHandler !== void 0 && runManager !== void 0) iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator);\n\t\t\tfor await (const chunk of iterator) {\n\t\t\t\tyield chunk;\n\t\t\t\tif (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk;\n\t\t\t\telse try {\n\t\t\t\t\tfinalOutput = this._concatOutputChunks(finalOutput, chunk);\n\t\t\t\t} catch {\n\t\t\t\t\tfinalOutput = void 0;\n\t\t\t\t\tfinalOutputSupported = false;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e, void 0, void 0, void 0, { inputs: _coerceToDict(finalInput, \"input\") });\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict(finalInput, \"input\") });\n\t}\n\tgetGraph(_) {\n\t\tconst graph = new Graph();\n\t\tconst inputNode = graph.addNode({\n\t\t\tname: `${this.getName()}Input`,\n\t\t\tschema: z.any()\n\t\t});\n\t\tconst runnableNode = graph.addNode(this);\n\t\tconst outputNode = graph.addNode({\n\t\t\tname: `${this.getName()}Output`,\n\t\t\tschema: z.any()\n\t\t});\n\t\tgraph.addEdge(inputNode, runnableNode);\n\t\tgraph.addEdge(runnableNode, outputNode);\n\t\treturn graph;\n\t}\n\t/**\n\t* Create a new runnable sequence that runs each individual runnable in series,\n\t* piping the output of one runnable into another runnable or runnable-like.\n\t* @param coerceable A runnable, function, or object whose values are functions or runnables.\n\t* @returns A new runnable sequence.\n\t*/\n\tpipe(coerceable) {\n\t\treturn new RunnableSequence({\n\t\t\tfirst: this,\n\t\t\tlast: _coerceToRunnable(coerceable)\n\t\t});\n\t}\n\t/**\n\t* Pick keys from the dict output of this runnable. Returns a new runnable.\n\t*/\n\tpick(keys) {\n\t\treturn this.pipe(new RunnablePick(keys));\n\t}\n\t/**\n\t* Assigns new fields to the dict output of this runnable. Returns a new runnable.\n\t*/\n\tassign(mapping) {\n\t\treturn this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping })));\n\t}\n\t/**\n\t* Default implementation of transform, which buffers input and then calls stream.\n\t* Subclasses should override this method if they can start producing output while\n\t* input is still being generated.\n\t* @param generator\n\t* @param options\n\t*/\n\tasync *transform(generator, options) {\n\t\tlet finalChunk;\n\t\tfor await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk;\n\t\telse finalChunk = this._concatOutputChunks(finalChunk, chunk);\n\t\tyield* this._streamIterator(finalChunk, ensureConfig(options));\n\t}\n\t/**\n\t* Stream all output from a runnable, as reported to the callback system.\n\t* This includes all inner runs of LLMs, Retrievers, Tools, etc.\n\t* Output is streamed as Log objects, which include a list of\n\t* jsonpatch ops that describe how the state of the run has changed in each\n\t* step, and the final state of the run.\n\t* The jsonpatch ops can be applied in order to construct state.\n\t* @param input\n\t* @param options\n\t* @param streamOptions\n\t*/\n\tasync *streamLog(input, options, streamOptions) {\n\t\tconst logStreamCallbackHandler = new LogStreamCallbackHandler({\n\t\t\t...streamOptions,\n\t\t\tautoClose: false,\n\t\t\t_schemaFormat: \"original\"\n\t\t});\n\t\tconst config = ensureConfig(options);\n\t\tyield* this._streamLog(input, logStreamCallbackHandler, config);\n\t}\n\tasync *_streamLog(input, logStreamCallbackHandler, config) {\n\t\tconst { callbacks } = config;\n\t\tif (callbacks === void 0) config.callbacks = [logStreamCallbackHandler];\n\t\telse if (Array.isArray(callbacks)) config.callbacks = callbacks.concat([logStreamCallbackHandler]);\n\t\telse {\n\t\t\tconst copiedCallbacks = callbacks.copy();\n\t\t\tcopiedCallbacks.addHandler(logStreamCallbackHandler, true);\n\t\t\tconfig.callbacks = copiedCallbacks;\n\t\t}\n\t\tconst runnableStreamPromise = this.stream(input, config);\n\t\tasync function consumeRunnableStream() {\n\t\t\ttry {\n\t\t\t\tconst runnableStream = await runnableStreamPromise;\n\t\t\t\tfor await (const chunk of runnableStream) {\n\t\t\t\t\tconst patch = new RunLogPatch({ ops: [{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/streamed_output/-\",\n\t\t\t\t\t\tvalue: chunk\n\t\t\t\t\t}] });\n\t\t\t\t\tawait logStreamCallbackHandler.writer.write(patch);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait logStreamCallbackHandler.writer.close();\n\t\t\t}\n\t\t}\n\t\tconst runnableStreamConsumePromise = consumeRunnableStream();\n\t\ttry {\n\t\t\tfor await (const log of logStreamCallbackHandler) yield log;\n\t\t} finally {\n\t\t\tawait runnableStreamConsumePromise;\n\t\t}\n\t}\n\tstreamEvents(input, options, streamOptions) {\n\t\tlet stream;\n\t\tif (options.version === \"v1\") stream = this._streamEventsV1(input, options, streamOptions);\n\t\telse if (options.version === \"v2\") stream = this._streamEventsV2(input, options, streamOptions);\n\t\telse throw new Error(`Only versions \"v1\" and \"v2\" of the schema are currently supported.`);\n\t\tif (options.encoding === \"text/event-stream\") return convertToHttpEventStream(stream);\n\t\telse return IterableReadableStream.fromAsyncGenerator(stream);\n\t}\n\tasync *_streamEventsV2(input, options, streamOptions) {\n\t\tconst eventStreamer = new EventStreamCallbackHandler({\n\t\t\t...streamOptions,\n\t\t\tautoClose: false\n\t\t});\n\t\tconst config = ensureConfig(options);\n\t\tconst runId = config.runId ?? v4();\n\t\tconfig.runId = runId;\n\t\tconst callbacks = config.callbacks;\n\t\tif (callbacks === void 0) config.callbacks = [eventStreamer];\n\t\telse if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(eventStreamer);\n\t\telse {\n\t\t\tconst copiedCallbacks = callbacks.copy();\n\t\t\tcopiedCallbacks.addHandler(eventStreamer, true);\n\t\t\tconfig.callbacks = copiedCallbacks;\n\t\t}\n\t\tconst abortController = new AbortController();\n\t\tconst outerThis = this;\n\t\tasync function consumeRunnableStream() {\n\t\t\tlet signal;\n\t\t\tlet listener = null;\n\t\t\ttry {\n\t\t\t\tif (options?.signal) if (\"any\" in AbortSignal) signal = AbortSignal.any([abortController.signal, options.signal]);\n\t\t\t\telse {\n\t\t\t\t\tsignal = options.signal;\n\t\t\t\t\tlistener = () => {\n\t\t\t\t\t\tabortController.abort();\n\t\t\t\t\t};\n\t\t\t\t\toptions.signal.addEventListener(\"abort\", listener, { once: true });\n\t\t\t\t}\n\t\t\t\telse signal = abortController.signal;\n\t\t\t\tconst runnableStream = await outerThis.stream(input, {\n\t\t\t\t\t...config,\n\t\t\t\t\tsignal\n\t\t\t\t});\n\t\t\t\tconst tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream);\n\t\t\t\tfor await (const _ of tappedStream) if (abortController.signal.aborted) break;\n\t\t\t} finally {\n\t\t\t\tawait eventStreamer.finish();\n\t\t\t\tif (signal && listener) signal.removeEventListener(\"abort\", listener);\n\t\t\t}\n\t\t}\n\t\tconst runnableStreamConsumePromise = consumeRunnableStream();\n\t\tlet firstEventSent = false;\n\t\tlet firstEventRunId;\n\t\ttry {\n\t\t\tfor await (const event of eventStreamer) {\n\t\t\t\tif (!firstEventSent) {\n\t\t\t\t\tevent.data.input = input;\n\t\t\t\t\tfirstEventSent = true;\n\t\t\t\t\tfirstEventRunId = event.run_id;\n\t\t\t\t\tyield event;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.run_id === firstEventRunId && event.event.endsWith(\"_end\")) {\n\t\t\t\t\tif (event.data?.input) delete event.data.input;\n\t\t\t\t}\n\t\t\t\tyield event;\n\t\t\t}\n\t\t} finally {\n\t\t\tabortController.abort();\n\t\t\tawait runnableStreamConsumePromise;\n\t\t}\n\t}\n\tasync *_streamEventsV1(input, options, streamOptions) {\n\t\tlet runLog;\n\t\tlet hasEncounteredStartEvent = false;\n\t\tconst config = ensureConfig(options);\n\t\tconst rootTags = config.tags ?? [];\n\t\tconst rootMetadata = config.metadata ?? {};\n\t\tconst rootName = config.runName ?? this.getName();\n\t\tconst logStreamCallbackHandler = new LogStreamCallbackHandler({\n\t\t\t...streamOptions,\n\t\t\tautoClose: false,\n\t\t\t_schemaFormat: \"streaming_events\"\n\t\t});\n\t\tconst rootEventFilter = new _RootEventFilter({ ...streamOptions });\n\t\tconst logStream = this._streamLog(input, logStreamCallbackHandler, config);\n\t\tfor await (const log of logStream) {\n\t\t\tif (!runLog) runLog = RunLog.fromRunLogPatch(log);\n\t\t\telse runLog = runLog.concat(log);\n\t\t\tif (runLog.state === void 0) throw new Error(`Internal error: \"streamEvents\" state is missing. Please open a bug report.`);\n\t\t\tif (!hasEncounteredStartEvent) {\n\t\t\t\thasEncounteredStartEvent = true;\n\t\t\t\tconst state$2 = { ...runLog.state };\n\t\t\t\tconst event = {\n\t\t\t\t\trun_id: state$2.id,\n\t\t\t\t\tevent: `on_${state$2.type}_start`,\n\t\t\t\t\tname: rootName,\n\t\t\t\t\ttags: rootTags,\n\t\t\t\t\tmetadata: rootMetadata,\n\t\t\t\t\tdata: { input }\n\t\t\t\t};\n\t\t\t\tif (rootEventFilter.includeEvent(event, state$2.type)) yield event;\n\t\t\t}\n\t\t\tconst paths = log.ops.filter((op) => op.path.startsWith(\"/logs/\")).map((op) => op.path.split(\"/\")[2]);\n\t\t\tconst dedupedPaths = [...new Set(paths)];\n\t\t\tfor (const path of dedupedPaths) {\n\t\t\t\tlet eventType;\n\t\t\t\tlet data = {};\n\t\t\t\tconst logEntry = runLog.state.logs[path];\n\t\t\t\tif (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = \"stream\";\n\t\t\t\telse eventType = \"start\";\n\t\t\t\telse eventType = \"end\";\n\t\t\t\tif (eventType === \"start\") {\n\t\t\t\t\tif (logEntry.inputs !== void 0) data.input = logEntry.inputs;\n\t\t\t\t} else if (eventType === \"end\") {\n\t\t\t\t\tif (logEntry.inputs !== void 0) data.input = logEntry.inputs;\n\t\t\t\t\tdata.output = logEntry.final_output;\n\t\t\t\t} else if (eventType === \"stream\") {\n\t\t\t\t\tconst chunkCount = logEntry.streamed_output.length;\n\t\t\t\t\tif (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: \"${logEntry.name}\"`);\n\t\t\t\t\tdata = { chunk: logEntry.streamed_output[0] };\n\t\t\t\t\tlogEntry.streamed_output = [];\n\t\t\t\t}\n\t\t\t\tyield {\n\t\t\t\t\tevent: `on_${logEntry.type}_${eventType}`,\n\t\t\t\t\tname: logEntry.name,\n\t\t\t\t\trun_id: logEntry.id,\n\t\t\t\t\ttags: logEntry.tags,\n\t\t\t\t\tmetadata: logEntry.metadata,\n\t\t\t\t\tdata\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst { state: state$1 } = runLog;\n\t\t\tif (state$1.streamed_output.length > 0) {\n\t\t\t\tconst chunkCount = state$1.streamed_output.length;\n\t\t\t\tif (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: \"${state$1.name}\"`);\n\t\t\t\tconst data = { chunk: state$1.streamed_output[0] };\n\t\t\t\tstate$1.streamed_output = [];\n\t\t\t\tconst event = {\n\t\t\t\t\tevent: `on_${state$1.type}_stream`,\n\t\t\t\t\trun_id: state$1.id,\n\t\t\t\t\ttags: rootTags,\n\t\t\t\t\tmetadata: rootMetadata,\n\t\t\t\t\tname: rootName,\n\t\t\t\t\tdata\n\t\t\t\t};\n\t\t\t\tif (rootEventFilter.includeEvent(event, state$1.type)) yield event;\n\t\t\t}\n\t\t}\n\t\tconst state = runLog?.state;\n\t\tif (state !== void 0) {\n\t\t\tconst event = {\n\t\t\t\tevent: `on_${state.type}_end`,\n\t\t\t\tname: rootName,\n\t\t\t\trun_id: state.id,\n\t\t\t\ttags: rootTags,\n\t\t\t\tmetadata: rootMetadata,\n\t\t\t\tdata: { output: state.final_output }\n\t\t\t};\n\t\t\tif (rootEventFilter.includeEvent(event, state.type)) yield event;\n\t\t}\n\t}\n\tstatic isRunnable(thing) {\n\t\treturn isRunnableInterface(thing);\n\t}\n\t/**\n\t* Bind lifecycle listeners to a Runnable, returning a new Runnable.\n\t* The Run object contains information about the run, including its id,\n\t* type, input, output, error, startTime, endTime, and any tags or metadata\n\t* added to the run.\n\t*\n\t* @param {Object} params - The object containing the callback functions.\n\t* @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n\t* @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n\t* @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n\t*/\n\twithListeners({ onStart, onEnd, onError }) {\n\t\treturn new RunnableBinding({\n\t\t\tbound: this,\n\t\t\tconfig: {},\n\t\t\tconfigFactories: [(config) => ({ callbacks: [new RootListenersTracer({\n\t\t\t\tconfig,\n\t\t\t\tonStart,\n\t\t\t\tonEnd,\n\t\t\t\tonError\n\t\t\t})] })]\n\t\t});\n\t}\n\t/**\n\t* Convert a runnable to a tool. Return a new instance of `RunnableToolLike`\n\t* which contains the runnable, name, description and schema.\n\t*\n\t* @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.\n\t*\n\t* @param fields\n\t* @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.\n\t* @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.\n\t* @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.\n\t* @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.\n\t*/\n\tasTool(fields) {\n\t\treturn convertRunnableToTool(this, fields);\n\t}\n};\n/**\n* Wraps a runnable and applies partial config upon invocation.\n*\n* @example\n* ```typescript\n* import {\n* type RunnableConfig,\n* RunnableLambda,\n* } from \"@langchain/core/runnables\";\n*\n* const enhanceProfile = (\n* profile: Record,\n* config?: RunnableConfig\n* ) => {\n* if (config?.configurable?.role) {\n* return { ...profile, role: config.configurable.role };\n* }\n* return profile;\n* };\n*\n* const runnable = RunnableLambda.from(enhanceProfile);\n*\n* // Bind configuration to the runnable to set the user's role dynamically\n* const adminRunnable = runnable.withConfig({ configurable: { role: \"Admin\" } });\n* const userRunnable = runnable.withConfig({ configurable: { role: \"User\" } });\n*\n* const result1 = await adminRunnable.invoke({\n* name: \"Alice\",\n* email: \"alice@example.com\"\n* });\n*\n* // { name: \"Alice\", email: \"alice@example.com\", role: \"Admin\" }\n*\n* const result2 = await userRunnable.invoke({\n* name: \"Bob\",\n* email: \"bob@example.com\"\n* });\n*\n* // { name: \"Bob\", email: \"bob@example.com\", role: \"User\" }\n* ```\n*/\nvar RunnableBinding = class RunnableBinding extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableBinding\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\tbound;\n\tconfig;\n\tkwargs;\n\tconfigFactories;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.bound = fields.bound;\n\t\tthis.kwargs = fields.kwargs;\n\t\tthis.config = fields.config;\n\t\tthis.configFactories = fields.configFactories;\n\t}\n\tgetName(suffix) {\n\t\treturn this.bound.getName(suffix);\n\t}\n\tasync _mergeConfig(...options) {\n\t\tconst config = mergeConfigs(this.config, ...options);\n\t\treturn mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []);\n\t}\n\twithConfig(config) {\n\t\treturn new this.constructor({\n\t\t\tbound: this.bound,\n\t\t\tkwargs: this.kwargs,\n\t\t\tconfig: {\n\t\t\t\t...this.config,\n\t\t\t\t...config\n\t\t\t}\n\t\t});\n\t}\n\twithRetry(fields) {\n\t\treturn new RunnableRetry({\n\t\t\tbound: this.bound,\n\t\t\tkwargs: this.kwargs,\n\t\t\tconfig: this.config,\n\t\t\tmaxAttemptNumber: fields?.stopAfterAttempt,\n\t\t\t...fields\n\t\t});\n\t}\n\tasync invoke(input, options) {\n\t\treturn this.bound.invoke(input, await this._mergeConfig(options, this.kwargs));\n\t}\n\tasync batch(inputs, options, batchOptions) {\n\t\tconst mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs);\n\t\treturn this.bound.batch(inputs, mergedOptions, batchOptions);\n\t}\n\t/** @internal */\n\t_concatOutputChunks(first, second) {\n\t\treturn this.bound._concatOutputChunks(first, second);\n\t}\n\tasync *_streamIterator(input, options) {\n\t\tyield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs));\n\t}\n\tasync stream(input, options) {\n\t\treturn this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs));\n\t}\n\tasync *transform(generator, options) {\n\t\tyield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs));\n\t}\n\tstreamEvents(input, options, streamOptions) {\n\t\tconst outerThis = this;\n\t\tconst generator = async function* () {\n\t\t\tyield* outerThis.bound.streamEvents(input, {\n\t\t\t\t...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs),\n\t\t\t\tversion: options.version\n\t\t\t}, streamOptions);\n\t\t};\n\t\treturn IterableReadableStream.fromAsyncGenerator(generator());\n\t}\n\tstatic isRunnableBinding(thing) {\n\t\treturn thing.bound && Runnable.isRunnable(thing.bound);\n\t}\n\t/**\n\t* Bind lifecycle listeners to a Runnable, returning a new Runnable.\n\t* The Run object contains information about the run, including its id,\n\t* type, input, output, error, startTime, endTime, and any tags or metadata\n\t* added to the run.\n\t*\n\t* @param {Object} params - The object containing the callback functions.\n\t* @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n\t* @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n\t* @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n\t*/\n\twithListeners({ onStart, onEnd, onError }) {\n\t\treturn new RunnableBinding({\n\t\t\tbound: this.bound,\n\t\t\tkwargs: this.kwargs,\n\t\t\tconfig: this.config,\n\t\t\tconfigFactories: [(config) => ({ callbacks: [new RootListenersTracer({\n\t\t\t\tconfig,\n\t\t\t\tonStart,\n\t\t\t\tonEnd,\n\t\t\t\tonError\n\t\t\t})] })]\n\t\t});\n\t}\n};\n/**\n* A runnable that delegates calls to another runnable\n* with each element of the input sequence.\n* @example\n* ```typescript\n* import { RunnableEach, RunnableLambda } from \"@langchain/core/runnables\";\n*\n* const toUpperCase = (input: string): string => input.toUpperCase();\n* const addGreeting = (input: string): string => `Hello, ${input}!`;\n*\n* const upperCaseLambda = RunnableLambda.from(toUpperCase);\n* const greetingLambda = RunnableLambda.from(addGreeting);\n*\n* const chain = new RunnableEach({\n* bound: upperCaseLambda.pipe(greetingLambda),\n* });\n*\n* const result = await chain.invoke([\"alice\", \"bob\", \"carol\"])\n*\n* // [\"Hello, ALICE!\", \"Hello, BOB!\", \"Hello, CAROL!\"]\n* ```\n*/\nvar RunnableEach = class RunnableEach extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableEach\";\n\t}\n\tlc_serializable = true;\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tbound;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.bound = fields.bound;\n\t}\n\t/**\n\t* Invokes the runnable with the specified input and configuration.\n\t* @param input The input to invoke the runnable with.\n\t* @param config The configuration to invoke the runnable with.\n\t* @returns A promise that resolves to the output of the runnable.\n\t*/\n\tasync invoke(inputs, config) {\n\t\treturn this._callWithConfig(this._invoke.bind(this), inputs, config);\n\t}\n\t/**\n\t* A helper method that is used to invoke the runnable with the specified input and configuration.\n\t* @param input The input to invoke the runnable with.\n\t* @param config The configuration to invoke the runnable with.\n\t* @returns A promise that resolves to the output of the runnable.\n\t*/\n\tasync _invoke(inputs, config, runManager) {\n\t\treturn this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() }));\n\t}\n\t/**\n\t* Bind lifecycle listeners to a Runnable, returning a new Runnable.\n\t* The Run object contains information about the run, including its id,\n\t* type, input, output, error, startTime, endTime, and any tags or metadata\n\t* added to the run.\n\t*\n\t* @param {Object} params - The object containing the callback functions.\n\t* @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n\t* @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n\t* @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n\t*/\n\twithListeners({ onStart, onEnd, onError }) {\n\t\treturn new RunnableEach({ bound: this.bound.withListeners({\n\t\t\tonStart,\n\t\t\tonEnd,\n\t\t\tonError\n\t\t}) });\n\t}\n};\n/**\n* Base class for runnables that can be retried a\n* specified number of times.\n* @example\n* ```typescript\n* import {\n* RunnableLambda,\n* RunnableRetry,\n* } from \"@langchain/core/runnables\";\n*\n* // Simulate an API call that fails\n* const simulateApiCall = (input: string): string => {\n* console.log(`Attempting API call with input: ${input}`);\n* throw new Error(\"API call failed due to network issue\");\n* };\n*\n* const apiCallLambda = RunnableLambda.from(simulateApiCall);\n*\n* // Apply retry logic using the .withRetry() method\n* const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 });\n*\n* // Alternatively, create a RunnableRetry instance manually\n* const manualRetry = new RunnableRetry({\n* bound: apiCallLambda,\n* maxAttemptNumber: 3,\n* config: {},\n* });\n*\n* // Example invocation using the .withRetry() method\n* const res = await apiCallWithRetry\n* .invoke(\"Request 1\")\n* .catch((error) => {\n* console.error(\"Failed after multiple retries:\", error.message);\n* });\n*\n* // Example invocation using the manual retry instance\n* const res2 = await manualRetry\n* .invoke(\"Request 2\")\n* .catch((error) => {\n* console.error(\"Failed after multiple retries:\", error.message);\n* });\n* ```\n*/\nvar RunnableRetry = class extends RunnableBinding {\n\tstatic lc_name() {\n\t\treturn \"RunnableRetry\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tmaxAttemptNumber = 3;\n\tonFailedAttempt = () => {};\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;\n\t\tthis.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;\n\t}\n\t_patchConfigForRetry(attempt, config, runManager) {\n\t\tconst tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0;\n\t\treturn patchConfig(config, { callbacks: runManager?.getChild(tag) });\n\t}\n\tasync _invoke(input, config, runManager) {\n\t\treturn pRetry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {\n\t\t\tonFailedAttempt: (error) => this.onFailedAttempt(error, input),\n\t\t\tretries: Math.max(this.maxAttemptNumber - 1, 0),\n\t\t\trandomize: true\n\t\t});\n\t}\n\t/**\n\t* Method that invokes the runnable with the specified input, run manager,\n\t* and config. It handles the retry logic by catching any errors and\n\t* recursively invoking itself with the updated config for the next retry\n\t* attempt.\n\t* @param input The input for the runnable.\n\t* @param runManager The run manager for the runnable.\n\t* @param config The config for the runnable.\n\t* @returns A promise that resolves to the output of the runnable.\n\t*/\n\tasync invoke(input, config) {\n\t\treturn this._callWithConfig(this._invoke.bind(this), input, config);\n\t}\n\tasync _batch(inputs, configs, runManagers, batchOptions) {\n\t\tconst resultsMap = {};\n\t\ttry {\n\t\t\tawait pRetry(async (attemptNumber) => {\n\t\t\t\tconst remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error);\n\t\t\t\tconst remainingInputs = remainingIndexes.map((i) => inputs[i]);\n\t\t\t\tconst patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));\n\t\t\t\tconst results = await super.batch(remainingInputs, patchedConfigs, {\n\t\t\t\t\t...batchOptions,\n\t\t\t\t\treturnExceptions: true\n\t\t\t\t});\n\t\t\t\tlet firstException;\n\t\t\t\tfor (let i = 0; i < results.length; i += 1) {\n\t\t\t\t\tconst result = results[i];\n\t\t\t\t\tconst resultMapIndex = remainingIndexes[i];\n\t\t\t\t\tif (result instanceof Error) {\n\t\t\t\t\t\tif (firstException === void 0) {\n\t\t\t\t\t\t\tfirstException = result;\n\t\t\t\t\t\t\tfirstException.input = remainingInputs[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresultsMap[resultMapIndex.toString()] = result;\n\t\t\t\t}\n\t\t\t\tif (firstException) throw firstException;\n\t\t\t\treturn results;\n\t\t\t}, {\n\t\t\t\tonFailedAttempt: (error) => this.onFailedAttempt(error, error.input),\n\t\t\t\tretries: Math.max(this.maxAttemptNumber - 1, 0),\n\t\t\t\trandomize: true\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (batchOptions?.returnExceptions !== true) throw e;\n\t\t}\n\t\treturn Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]);\n\t}\n\tasync batch(inputs, options, batchOptions) {\n\t\treturn this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);\n\t}\n};\n/**\n* A sequence of runnables, where the output of each is the input of the next.\n* @example\n* ```typescript\n* const promptTemplate = PromptTemplate.fromTemplate(\n* \"Tell me a joke about {topic}\",\n* );\n* const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: \"gpt-4o-mini\" })]);\n* const result = await chain.invoke({ topic: \"bears\" });\n* ```\n*/\nvar RunnableSequence = class RunnableSequence extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableSequence\";\n\t}\n\tfirst;\n\tmiddle = [];\n\tlast;\n\tomitSequenceTags = false;\n\tlc_serializable = true;\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.first = fields.first;\n\t\tthis.middle = fields.middle ?? this.middle;\n\t\tthis.last = fields.last;\n\t\tthis.name = fields.name;\n\t\tthis.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags;\n\t}\n\tget steps() {\n\t\treturn [\n\t\t\tthis.first,\n\t\t\t...this.middle,\n\t\t\tthis.last\n\t\t];\n\t}\n\tasync invoke(input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), config.runId, void 0, void 0, void 0, config?.runName);\n\t\tdelete config.runId;\n\t\tlet nextStepInput = input;\n\t\tlet finalOutput;\n\t\ttry {\n\t\t\tconst initialSteps = [this.first, ...this.middle];\n\t\t\tfor (let i = 0; i < initialSteps.length; i += 1) {\n\t\t\t\tconst step = initialSteps[i];\n\t\t\t\tconst promise = step.invoke(nextStepInput, patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) }));\n\t\t\t\tnextStepInput = await raceWithSignal(promise, options?.signal);\n\t\t\t}\n\t\t\tif (options?.signal?.aborted) throw getAbortSignalError(options.signal);\n\t\t\tfinalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) }));\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(_coerceToDict(finalOutput, \"output\"));\n\t\treturn finalOutput;\n\t}\n\tasync batch(inputs, options, batchOptions) {\n\t\tconst configList = this._getOptionsList(options ?? {}, inputs.length);\n\t\tconst callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig));\n\t\tconst runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {\n\t\t\tconst handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], \"input\"), configList[i].runId, void 0, void 0, void 0, configList[i].runName);\n\t\t\tdelete configList[i].runId;\n\t\t\treturn handleStartRes;\n\t\t}));\n\t\tlet nextStepInputs = inputs;\n\t\ttry {\n\t\t\tfor (let i = 0; i < this.steps.length; i += 1) {\n\t\t\t\tconst step = this.steps[i];\n\t\t\t\tconst promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => {\n\t\t\t\t\tconst childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`);\n\t\t\t\t\treturn patchConfig(configList[j], { callbacks: childRunManager });\n\t\t\t\t}), batchOptions);\n\t\t\t\tnextStepInputs = await raceWithSignal(promise, configList[0]?.signal);\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));\n\t\t\tthrow e;\n\t\t}\n\t\tawait Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(nextStepInputs, \"output\"))));\n\t\treturn nextStepInputs;\n\t}\n\t/** @internal */\n\t_concatOutputChunks(first, second) {\n\t\treturn this.last._concatOutputChunks(first, second);\n\t}\n\tasync *_streamIterator(input, options) {\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(options);\n\t\tconst { runId,...otherOptions } = options ?? {};\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), runId, void 0, void 0, void 0, otherOptions?.runName);\n\t\tconst steps = [\n\t\t\tthis.first,\n\t\t\t...this.middle,\n\t\t\tthis.last\n\t\t];\n\t\tlet concatSupported = true;\n\t\tlet finalOutput;\n\t\tasync function* inputGenerator() {\n\t\t\tyield input;\n\t\t}\n\t\ttry {\n\t\t\tlet finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) }));\n\t\t\tfor (let i = 1; i < steps.length; i += 1) {\n\t\t\t\tconst step = steps[i];\n\t\t\t\tfinalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) }));\n\t\t\t}\n\t\t\tfor await (const chunk of finalGenerator) {\n\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\tyield chunk;\n\t\t\t\tif (concatSupported) if (finalOutput === void 0) finalOutput = chunk;\n\t\t\t\telse try {\n\t\t\t\t\tfinalOutput = this._concatOutputChunks(finalOutput, chunk);\n\t\t\t\t} catch {\n\t\t\t\t\tfinalOutput = void 0;\n\t\t\t\t\tconcatSupported = false;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(_coerceToDict(finalOutput, \"output\"));\n\t}\n\tgetGraph(config) {\n\t\tconst graph = new Graph();\n\t\tlet currentLastNode = null;\n\t\tthis.steps.forEach((step, index) => {\n\t\t\tconst stepGraph = step.getGraph(config);\n\t\t\tif (index !== 0) stepGraph.trimFirstNode();\n\t\t\tif (index !== this.steps.length - 1) stepGraph.trimLastNode();\n\t\t\tgraph.extend(stepGraph);\n\t\t\tconst stepFirstNode = stepGraph.firstNode();\n\t\t\tif (!stepFirstNode) throw new Error(`Runnable ${step} has no first node`);\n\t\t\tif (currentLastNode) graph.addEdge(currentLastNode, stepFirstNode);\n\t\t\tcurrentLastNode = stepGraph.lastNode();\n\t\t});\n\t\treturn graph;\n\t}\n\tpipe(coerceable) {\n\t\tif (RunnableSequence.isRunnableSequence(coerceable)) return new RunnableSequence({\n\t\t\tfirst: this.first,\n\t\t\tmiddle: this.middle.concat([\n\t\t\t\tthis.last,\n\t\t\t\tcoerceable.first,\n\t\t\t\t...coerceable.middle\n\t\t\t]),\n\t\t\tlast: coerceable.last,\n\t\t\tname: this.name ?? coerceable.name\n\t\t});\n\t\telse return new RunnableSequence({\n\t\t\tfirst: this.first,\n\t\t\tmiddle: [...this.middle, this.last],\n\t\t\tlast: _coerceToRunnable(coerceable),\n\t\t\tname: this.name\n\t\t});\n\t}\n\tstatic isRunnableSequence(thing) {\n\t\treturn Array.isArray(thing.middle) && Runnable.isRunnable(thing);\n\t}\n\tstatic from([first, ...runnables], nameOrFields) {\n\t\tlet extra = {};\n\t\tif (typeof nameOrFields === \"string\") extra.name = nameOrFields;\n\t\telse if (nameOrFields !== void 0) extra = nameOrFields;\n\t\treturn new RunnableSequence({\n\t\t\t...extra,\n\t\t\tfirst: _coerceToRunnable(first),\n\t\t\tmiddle: runnables.slice(0, -1).map(_coerceToRunnable),\n\t\t\tlast: _coerceToRunnable(runnables[runnables.length - 1])\n\t\t});\n\t}\n};\n/**\n* A runnable that runs a mapping of runnables in parallel,\n* and returns a mapping of their outputs.\n* @example\n* ```typescript\n* const mapChain = RunnableMap.from({\n* joke: PromptTemplate.fromTemplate(\"Tell me a joke about {topic}\").pipe(\n* new ChatAnthropic({}),\n* ),\n* poem: PromptTemplate.fromTemplate(\"write a 2-line poem about {topic}\").pipe(\n* new ChatAnthropic({}),\n* ),\n* });\n* const result = await mapChain.invoke({ topic: \"bear\" });\n* ```\n*/\nvar RunnableMap = class RunnableMap extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableMap\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\tsteps;\n\tgetStepsKeys() {\n\t\treturn Object.keys(this.steps);\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.steps = {};\n\t\tfor (const [key, value] of Object.entries(fields.steps)) this.steps[key] = _coerceToRunnable(value);\n\t}\n\tstatic from(steps) {\n\t\treturn new RunnableMap({ steps });\n\t}\n\tasync invoke(input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input }, config.runId, void 0, void 0, void 0, config?.runName);\n\t\tdelete config.runId;\n\t\tconst output = {};\n\t\ttry {\n\t\t\tconst promises = Object.entries(this.steps).map(async ([key, runnable]) => {\n\t\t\t\toutput[key] = await runnable.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) }));\n\t\t\t});\n\t\t\tawait raceWithSignal(Promise.all(promises), options?.signal);\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(output);\n\t\treturn output;\n\t}\n\tasync *_transform(generator, runManager, options) {\n\t\tconst steps = { ...this.steps };\n\t\tconst inputCopies = atee(generator, Object.keys(steps).length);\n\t\tconst tasks = new Map(Object.entries(steps).map(([key, runnable], i) => {\n\t\t\tconst gen = runnable.transform(inputCopies[i], patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) }));\n\t\t\treturn [key, gen.next().then((result) => ({\n\t\t\t\tkey,\n\t\t\t\tgen,\n\t\t\t\tresult\n\t\t\t}))];\n\t\t}));\n\t\twhile (tasks.size) {\n\t\t\tconst promise = Promise.race(tasks.values());\n\t\t\tconst { key, result, gen } = await raceWithSignal(promise, options?.signal);\n\t\t\ttasks.delete(key);\n\t\t\tif (!result.done) {\n\t\t\t\tyield { [key]: result.value };\n\t\t\t\ttasks.set(key, gen.next().then((result$1) => ({\n\t\t\t\t\tkey,\n\t\t\t\t\tgen,\n\t\t\t\t\tresult: result$1\n\t\t\t\t})));\n\t\t\t}\n\t\t}\n\t}\n\ttransform(generator, options) {\n\t\treturn this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n\t}\n\tasync stream(input, options) {\n\t\tasync function* generator() {\n\t\t\tyield input;\n\t\t}\n\t\tconst config = ensureConfig(options);\n\t\tconst wrappedGenerator = new AsyncGeneratorWithSetup({\n\t\t\tgenerator: this.transform(generator(), config),\n\t\t\tconfig\n\t\t});\n\t\tawait wrappedGenerator.setup;\n\t\treturn IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n\t}\n};\n/**\n* A runnable that wraps a traced LangSmith function.\n*/\nvar RunnableTraceable = class RunnableTraceable extends Runnable {\n\tlc_serializable = false;\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tfunc;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tif (!isTraceableFunction(fields.func)) throw new Error(\"RunnableTraceable requires a function that is wrapped in traceable higher-order function\");\n\t\tthis.func = fields.func;\n\t}\n\tasync invoke(input, options) {\n\t\tconst [config] = this._getOptionsList(options ?? {}, 1);\n\t\tconst callbacks = await getCallbackManagerForConfig(config);\n\t\tconst promise = this.func(patchConfig(config, { callbacks }), input);\n\t\treturn raceWithSignal(promise, config?.signal);\n\t}\n\tasync *_streamIterator(input, options) {\n\t\tconst [config] = this._getOptionsList(options ?? {}, 1);\n\t\tconst result = await this.invoke(input, options);\n\t\tif (isAsyncIterable(result)) {\n\t\t\tfor await (const item of result) {\n\t\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\t\tyield item;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (isIterator(result)) {\n\t\t\twhile (true) {\n\t\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\t\tconst state = result.next();\n\t\t\t\tif (state.done) break;\n\t\t\t\tyield state.value;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tyield result;\n\t}\n\tstatic from(func) {\n\t\treturn new RunnableTraceable({ func });\n\t}\n};\nfunction assertNonTraceableFunction(func) {\n\tif (isTraceableFunction(func)) throw new Error(\"RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.\");\n}\n/**\n* A runnable that wraps an arbitrary function that takes a single argument.\n* @example\n* ```typescript\n* import { RunnableLambda } from \"@langchain/core/runnables\";\n*\n* const add = (input: { x: number; y: number }) => input.x + input.y;\n*\n* const multiply = (input: { value: number; multiplier: number }) =>\n* input.value * input.multiplier;\n*\n* // Create runnables for the functions\n* const addLambda = RunnableLambda.from(add);\n* const multiplyLambda = RunnableLambda.from(multiply);\n*\n* // Chain the lambdas for a mathematical operation\n* const chainedLambda = addLambda.pipe((result) =>\n* multiplyLambda.invoke({ value: result, multiplier: 2 })\n* );\n*\n* // Example invocation of the chainedLambda\n* const result = await chainedLambda.invoke({ x: 2, y: 3 });\n*\n* // Will log \"10\" (since (2 + 3) * 2 = 10)\n* ```\n*/\nvar RunnableLambda = class RunnableLambda extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableLambda\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tfunc;\n\tconstructor(fields) {\n\t\tif (isTraceableFunction(fields.func)) return RunnableTraceable.from(fields.func);\n\t\tsuper(fields);\n\t\tassertNonTraceableFunction(fields.func);\n\t\tthis.func = fields.func;\n\t}\n\tstatic from(func) {\n\t\treturn new RunnableLambda({ func });\n\t}\n\tasync _invoke(input, config, runManager) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst childConfig = patchConfig(config, {\n\t\t\t\tcallbacks: runManager?.getChild(),\n\t\t\t\trecursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1\n\t\t\t});\n\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {\n\t\t\t\ttry {\n\t\t\t\t\tlet output = await this.func(input, { ...childConfig });\n\t\t\t\t\tif (output && Runnable.isRunnable(output)) {\n\t\t\t\t\t\tif (config?.recursionLimit === 0) throw new Error(\"Recursion limit reached.\");\n\t\t\t\t\t\toutput = await output.invoke(input, {\n\t\t\t\t\t\t\t...childConfig,\n\t\t\t\t\t\t\trecursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (isAsyncIterable(output)) {\n\t\t\t\t\t\tlet finalOutput;\n\t\t\t\t\t\tfor await (const chunk of consumeAsyncIterableInContext(childConfig, output)) {\n\t\t\t\t\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\t\t\t\t\tif (finalOutput === void 0) finalOutput = chunk;\n\t\t\t\t\t\t\telse try {\n\t\t\t\t\t\t\t\tfinalOutput = this._concatOutputChunks(finalOutput, chunk);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tfinalOutput = chunk;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutput = finalOutput;\n\t\t\t\t\t} else if (isIterableIterator(output)) {\n\t\t\t\t\t\tlet finalOutput;\n\t\t\t\t\t\tfor (const chunk of consumeIteratorInContext(childConfig, output)) {\n\t\t\t\t\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\t\t\t\t\tif (finalOutput === void 0) finalOutput = chunk;\n\t\t\t\t\t\t\telse try {\n\t\t\t\t\t\t\t\tfinalOutput = this._concatOutputChunks(finalOutput, chunk);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tfinalOutput = chunk;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutput = finalOutput;\n\t\t\t\t\t}\n\t\t\t\t\tresolve(output);\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\tasync invoke(input, options) {\n\t\treturn this._callWithConfig(this._invoke.bind(this), input, options);\n\t}\n\tasync *_transform(generator, runManager, config) {\n\t\tlet finalChunk;\n\t\tfor await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk;\n\t\telse try {\n\t\t\tfinalChunk = this._concatOutputChunks(finalChunk, chunk);\n\t\t} catch {\n\t\t\tfinalChunk = chunk;\n\t\t}\n\t\tconst childConfig = patchConfig(config, {\n\t\t\tcallbacks: runManager?.getChild(),\n\t\t\trecursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1\n\t\t});\n\t\tconst output = await new Promise((resolve, reject) => {\n\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst res = await this.func(finalChunk, {\n\t\t\t\t\t\t...childConfig,\n\t\t\t\t\t\tconfig: childConfig\n\t\t\t\t\t});\n\t\t\t\t\tresolve(res);\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (output && Runnable.isRunnable(output)) {\n\t\t\tif (config?.recursionLimit === 0) throw new Error(\"Recursion limit reached.\");\n\t\t\tconst stream = await output.stream(finalChunk, childConfig);\n\t\t\tfor await (const chunk of stream) yield chunk;\n\t\t} else if (isAsyncIterable(output)) for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) {\n\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\tyield chunk;\n\t\t}\n\t\telse if (isIterableIterator(output)) for (const chunk of consumeIteratorInContext(childConfig, output)) {\n\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\tyield chunk;\n\t\t}\n\t\telse yield output;\n\t}\n\ttransform(generator, options) {\n\t\treturn this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n\t}\n\tasync stream(input, options) {\n\t\tasync function* generator() {\n\t\t\tyield input;\n\t\t}\n\t\tconst config = ensureConfig(options);\n\t\tconst wrappedGenerator = new AsyncGeneratorWithSetup({\n\t\t\tgenerator: this.transform(generator(), config),\n\t\t\tconfig\n\t\t});\n\t\tawait wrappedGenerator.setup;\n\t\treturn IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n\t}\n};\n/**\n* A runnable that runs a mapping of runnables in parallel,\n* and returns a mapping of their outputs.\n* @example\n* ```typescript\n* import {\n* RunnableLambda,\n* RunnableParallel,\n* } from \"@langchain/core/runnables\";\n*\n* const addYears = (age: number): number => age + 5;\n* const yearsToFifty = (age: number): number => 50 - age;\n* const yearsToHundred = (age: number): number => 100 - age;\n*\n* const addYearsLambda = RunnableLambda.from(addYears);\n* const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty);\n* const milestoneHundredLambda = RunnableLambda.from(yearsToHundred);\n*\n* // Pipe will coerce objects into RunnableParallel by default, but we\n* // explicitly instantiate one here to demonstrate\n* const sequence = addYearsLambda.pipe(\n* RunnableParallel.from({\n* years_to_fifty: milestoneFiftyLambda,\n* years_to_hundred: milestoneHundredLambda,\n* })\n* );\n*\n* // Invoke the sequence with a single age input\n* const res = await sequence.invoke(25);\n*\n* // { years_to_fifty: 20, years_to_hundred: 70 }\n* ```\n*/\nvar RunnableParallel = class extends RunnableMap {};\n/**\n* A Runnable that can fallback to other Runnables if it fails.\n* External APIs (e.g., APIs for a language model) may at times experience\n* degraded performance or even downtime.\n*\n* In these cases, it can be useful to have a fallback Runnable that can be\n* used in place of the original Runnable (e.g., fallback to another LLM provider).\n*\n* Fallbacks can be defined at the level of a single Runnable, or at the level\n* of a chain of Runnables. Fallbacks are tried in order until one succeeds or\n* all fail.\n*\n* While you can instantiate a `RunnableWithFallbacks` directly, it is usually\n* more convenient to use the `withFallbacks` method on an existing Runnable.\n*\n* When streaming, fallbacks will only be called on failures during the initial\n* stream creation. Errors that occur after a stream starts will not fallback\n* to the next Runnable.\n*\n* @example\n* ```typescript\n* import {\n* RunnableLambda,\n* RunnableWithFallbacks,\n* } from \"@langchain/core/runnables\";\n*\n* const primaryOperation = (input: string): string => {\n* if (input !== \"safe\") {\n* throw new Error(\"Primary operation failed due to unsafe input\");\n* }\n* return `Processed: ${input}`;\n* };\n*\n* // Define a fallback operation that processes the input differently\n* const fallbackOperation = (input: string): string =>\n* `Fallback processed: ${input}`;\n*\n* const primaryRunnable = RunnableLambda.from(primaryOperation);\n* const fallbackRunnable = RunnableLambda.from(fallbackOperation);\n*\n* // Apply the fallback logic using the .withFallbacks() method\n* const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]);\n*\n* // Alternatively, create a RunnableWithFallbacks instance manually\n* const manualFallbackChain = new RunnableWithFallbacks({\n* runnable: primaryRunnable,\n* fallbacks: [fallbackRunnable],\n* });\n*\n* // Example invocation using .withFallbacks()\n* const res = await runnableWithFallback\n* .invoke(\"unsafe input\")\n* .catch((error) => {\n* console.error(\"Failed after all attempts:\", error.message);\n* });\n*\n* // \"Fallback processed: unsafe input\"\n*\n* // Example invocation using manual instantiation\n* const res = await manualFallbackChain\n* .invoke(\"safe\")\n* .catch((error) => {\n* console.error(\"Failed after all attempts:\", error.message);\n* });\n*\n* // \"Processed: safe\"\n* ```\n*/\nvar RunnableWithFallbacks = class extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableWithFallbacks\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\trunnable;\n\tfallbacks;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.runnable = fields.runnable;\n\t\tthis.fallbacks = fields.fallbacks;\n\t}\n\t*runnables() {\n\t\tyield this.runnable;\n\t\tfor (const fallback of this.fallbacks) yield fallback;\n\t}\n\tasync invoke(input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst { runId,...otherConfigFields } = config;\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), runId, void 0, void 0, void 0, otherConfigFields?.runName);\n\t\tconst childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() });\n\t\tconst res = await AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {\n\t\t\tlet firstError;\n\t\t\tfor (const runnable of this.runnables()) {\n\t\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\t\ttry {\n\t\t\t\t\tconst output = await runnable.invoke(input, childConfig);\n\t\t\t\t\tawait runManager?.handleChainEnd(_coerceToDict(output, \"output\"));\n\t\t\t\t\treturn output;\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (firstError === void 0) firstError = e;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (firstError === void 0) throw new Error(\"No error stored at end of fallback.\");\n\t\t\tawait runManager?.handleChainError(firstError);\n\t\t\tthrow firstError;\n\t\t});\n\t\treturn res;\n\t}\n\tasync *_streamIterator(input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst { runId,...otherConfigFields } = config;\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), runId, void 0, void 0, void 0, otherConfigFields?.runName);\n\t\tlet firstError;\n\t\tlet stream;\n\t\tfor (const runnable of this.runnables()) {\n\t\t\tconfig?.signal?.throwIfAborted();\n\t\t\tconst childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() });\n\t\t\ttry {\n\t\t\t\tconst originalStream = await runnable.stream(input, childConfig);\n\t\t\t\tstream = consumeAsyncIterableInContext(childConfig, originalStream);\n\t\t\t\tbreak;\n\t\t\t} catch (e) {\n\t\t\t\tif (firstError === void 0) firstError = e;\n\t\t\t}\n\t\t}\n\t\tif (stream === void 0) {\n\t\t\tconst error = firstError ?? /* @__PURE__ */ new Error(\"No error stored at end of fallback.\");\n\t\t\tawait runManager?.handleChainError(error);\n\t\t\tthrow error;\n\t\t}\n\t\tlet output;\n\t\ttry {\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tyield chunk;\n\t\t\t\ttry {\n\t\t\t\t\toutput = output === void 0 ? output : this._concatOutputChunks(output, chunk);\n\t\t\t\t} catch {\n\t\t\t\t\toutput = void 0;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(_coerceToDict(output, \"output\"));\n\t}\n\tasync batch(inputs, options, batchOptions) {\n\t\tif (batchOptions?.returnExceptions) throw new Error(\"Not implemented.\");\n\t\tconst configList = this._getOptionsList(options ?? {}, inputs.length);\n\t\tconst callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config)));\n\t\tconst runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {\n\t\t\tconst handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], \"input\"), configList[i].runId, void 0, void 0, void 0, configList[i].runName);\n\t\t\tdelete configList[i].runId;\n\t\t\treturn handleStartRes;\n\t\t}));\n\t\tlet firstError;\n\t\tfor (const runnable of this.runnables()) {\n\t\t\tconfigList[0].signal?.throwIfAborted();\n\t\t\ttry {\n\t\t\t\tconst outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions);\n\t\t\t\tawait Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], \"output\"))));\n\t\t\t\treturn outputs;\n\t\t\t} catch (e) {\n\t\t\t\tif (firstError === void 0) firstError = e;\n\t\t\t}\n\t\t}\n\t\tif (!firstError) throw new Error(\"No error stored at end of fallbacks.\");\n\t\tawait Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError)));\n\t\tthrow firstError;\n\t}\n};\nfunction _coerceToRunnable(coerceable) {\n\tif (typeof coerceable === \"function\") return new RunnableLambda({ func: coerceable });\n\telse if (Runnable.isRunnable(coerceable)) return coerceable;\n\telse if (!Array.isArray(coerceable) && typeof coerceable === \"object\") {\n\t\tconst runnables = {};\n\t\tfor (const [key, value] of Object.entries(coerceable)) runnables[key] = _coerceToRunnable(value);\n\t\treturn new RunnableMap({ steps: runnables });\n\t} else throw new Error(`Expected a Runnable, function or object.\\nInstead got an unsupported type.`);\n}\n/**\n* A runnable that assigns key-value pairs to inputs of type `Record`.\n* @example\n* ```typescript\n* import {\n* RunnableAssign,\n* RunnableLambda,\n* RunnableParallel,\n* } from \"@langchain/core/runnables\";\n*\n* const calculateAge = (x: { birthYear: number }): { age: number } => {\n* const currentYear = new Date().getFullYear();\n* return { age: currentYear - x.birthYear };\n* };\n*\n* const createGreeting = (x: { name: string }): { greeting: string } => {\n* return { greeting: `Hello, ${x.name}!` };\n* };\n*\n* const mapper = RunnableParallel.from({\n* age_step: RunnableLambda.from(calculateAge),\n* greeting_step: RunnableLambda.from(createGreeting),\n* });\n*\n* const runnableAssign = new RunnableAssign({ mapper });\n*\n* const res = await runnableAssign.invoke({ name: \"Alice\", birthYear: 1990 });\n*\n* // { name: \"Alice\", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: \"Hello, Alice!\" } }\n* ```\n*/\nvar RunnableAssign = class extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableAssign\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\tmapper;\n\tconstructor(fields) {\n\t\tif (fields instanceof RunnableMap) fields = { mapper: fields };\n\t\tsuper(fields);\n\t\tthis.mapper = fields.mapper;\n\t}\n\tasync invoke(input, options) {\n\t\tconst mapperResult = await this.mapper.invoke(input, options);\n\t\treturn {\n\t\t\t...input,\n\t\t\t...mapperResult\n\t\t};\n\t}\n\tasync *_transform(generator, runManager, options) {\n\t\tconst mapperKeys = this.mapper.getStepsKeys();\n\t\tconst [forPassthrough, forMapper] = atee(generator);\n\t\tconst mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() }));\n\t\tconst firstMapperChunkPromise = mapperOutput.next();\n\t\tfor await (const chunk of forPassthrough) {\n\t\t\tif (typeof chunk !== \"object\" || Array.isArray(chunk)) throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`);\n\t\t\tconst filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key)));\n\t\t\tif (Object.keys(filtered).length > 0) yield filtered;\n\t\t}\n\t\tyield (await firstMapperChunkPromise).value;\n\t\tfor await (const chunk of mapperOutput) yield chunk;\n\t}\n\ttransform(generator, options) {\n\t\treturn this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n\t}\n\tasync stream(input, options) {\n\t\tasync function* generator() {\n\t\t\tyield input;\n\t\t}\n\t\tconst config = ensureConfig(options);\n\t\tconst wrappedGenerator = new AsyncGeneratorWithSetup({\n\t\t\tgenerator: this.transform(generator(), config),\n\t\t\tconfig\n\t\t});\n\t\tawait wrappedGenerator.setup;\n\t\treturn IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n\t}\n};\n/**\n* A runnable that assigns key-value pairs to inputs of type `Record`.\n* Useful for streaming, can be automatically created and chained by calling `runnable.pick();`.\n* @example\n* ```typescript\n* import { RunnablePick } from \"@langchain/core/runnables\";\n*\n* const inputData = {\n* name: \"John\",\n* age: 30,\n* city: \"New York\",\n* country: \"USA\",\n* email: \"john.doe@example.com\",\n* phone: \"+1234567890\",\n* };\n*\n* const basicInfoRunnable = new RunnablePick([\"name\", \"city\"]);\n*\n* // Example invocation\n* const res = await basicInfoRunnable.invoke(inputData);\n*\n* // { name: 'John', city: 'New York' }\n* ```\n*/\nvar RunnablePick = class extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnablePick\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\tkeys;\n\tconstructor(fields) {\n\t\tif (typeof fields === \"string\" || Array.isArray(fields)) fields = { keys: fields };\n\t\tsuper(fields);\n\t\tthis.keys = fields.keys;\n\t}\n\tasync _pick(input) {\n\t\tif (typeof this.keys === \"string\") return input[this.keys];\n\t\telse {\n\t\t\tconst picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== void 0);\n\t\t\treturn picked.length === 0 ? void 0 : Object.fromEntries(picked);\n\t\t}\n\t}\n\tasync invoke(input, options) {\n\t\treturn this._callWithConfig(this._pick.bind(this), input, options);\n\t}\n\tasync *_transform(generator) {\n\t\tfor await (const chunk of generator) {\n\t\t\tconst picked = await this._pick(chunk);\n\t\t\tif (picked !== void 0) yield picked;\n\t\t}\n\t}\n\ttransform(generator, options) {\n\t\treturn this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n\t}\n\tasync stream(input, options) {\n\t\tasync function* generator() {\n\t\t\tyield input;\n\t\t}\n\t\tconst config = ensureConfig(options);\n\t\tconst wrappedGenerator = new AsyncGeneratorWithSetup({\n\t\t\tgenerator: this.transform(generator(), config),\n\t\t\tconfig\n\t\t});\n\t\tawait wrappedGenerator.setup;\n\t\treturn IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n\t}\n};\nvar RunnableToolLike = class extends RunnableBinding {\n\tname;\n\tdescription;\n\tschema;\n\tconstructor(fields) {\n\t\tconst sequence = RunnableSequence.from([RunnableLambda.from(async (input) => {\n\t\t\tlet toolInput;\n\t\t\tif (_isToolCall(input)) try {\n\t\t\t\ttoolInput = await interopParseAsync(this.schema, input.args);\n\t\t\t} catch {\n\t\t\t\tthrow new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args));\n\t\t\t}\n\t\t\telse toolInput = input;\n\t\t\treturn toolInput;\n\t\t}).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name });\n\t\tsuper({\n\t\t\tbound: sequence,\n\t\t\tconfig: fields.config ?? {}\n\t\t});\n\t\tthis.name = fields.name;\n\t\tthis.description = fields.description;\n\t\tthis.schema = fields.schema;\n\t}\n\tstatic lc_name() {\n\t\treturn \"RunnableToolLike\";\n\t}\n};\n/**\n* Given a runnable and a Zod schema, convert the runnable to a tool.\n*\n* @template RunInput The input type for the runnable.\n* @template RunOutput The output type for the runnable.\n*\n* @param {Runnable} runnable The runnable to convert to a tool.\n* @param fields\n* @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.\n* @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.\n* @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.\n* @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.\n*/\nfunction convertRunnableToTool(runnable, fields) {\n\tconst name = fields.name ?? runnable.getName();\n\tconst description = fields.description ?? getSchemaDescription(fields.schema);\n\tif (isSimpleStringZodSchema(fields.schema)) return new RunnableToolLike({\n\t\tname,\n\t\tdescription,\n\t\tschema: z.object({ input: z.string() }).transform((input) => input.input),\n\t\tbound: runnable\n\t});\n\treturn new RunnableToolLike({\n\t\tname,\n\t\tdescription,\n\t\tschema: fields.schema,\n\t\tbound: runnable\n\t});\n}\n\n//#endregion\nexport { Runnable, RunnableAssign, RunnableBinding, RunnableEach, RunnableLambda, RunnableMap, RunnableParallel, RunnablePick, RunnableRetry, RunnableSequence, RunnableToolLike, RunnableWithFallbacks, _coerceToDict, _coerceToRunnable };\n//# sourceMappingURL=base.js.map","import { isBaseMessageChunk } from \"./base.js\";\nimport { ToolMessage, ToolMessageChunk } from \"./tool.js\";\nimport { AIMessage, AIMessageChunk } from \"./ai.js\";\nimport { ChatMessage, ChatMessageChunk } from \"./chat.js\";\nimport { FunctionMessage, FunctionMessageChunk } from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk } from \"./human.js\";\nimport { SystemMessage, SystemMessageChunk } from \"./system.js\";\nimport { RemoveMessage } from \"./modifier.js\";\nimport { convertToChunk } from \"./utils.js\";\nimport { RunnableLambda } from \"../runnables/base.js\";\n\n//#region src/messages/transformers.ts\nconst _isMessageType = (msg, types) => {\n\tconst typesAsStrings = [...new Set(types?.map((t) => {\n\t\tif (typeof t === \"string\") return t;\n\t\tconst instantiatedMsgClass = new t({});\n\t\tif (!(\"getType\" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== \"function\") throw new Error(\"Invalid type provided.\");\n\t\treturn instantiatedMsgClass.getType();\n\t}))];\n\tconst msgType = msg.getType();\n\treturn typesAsStrings.some((t) => t === msgType);\n};\nfunction filterMessages(messagesOrOptions, options) {\n\tif (Array.isArray(messagesOrOptions)) return _filterMessages(messagesOrOptions, options);\n\treturn RunnableLambda.from((input) => {\n\t\treturn _filterMessages(input, messagesOrOptions);\n\t});\n}\nfunction _filterMessages(messages, options = {}) {\n\tconst { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options;\n\tconst filtered = [];\n\tfor (const msg of messages) {\n\t\tif (excludeNames && msg.name && excludeNames.includes(msg.name)) continue;\n\t\telse if (excludeTypes && _isMessageType(msg, excludeTypes)) continue;\n\t\telse if (excludeIds && msg.id && excludeIds.includes(msg.id)) continue;\n\t\tif (!(includeTypes || includeIds || includeNames)) filtered.push(msg);\n\t\telse if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) filtered.push(msg);\n\t\telse if (includeTypes && _isMessageType(msg, includeTypes)) filtered.push(msg);\n\t\telse if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) filtered.push(msg);\n\t}\n\treturn filtered;\n}\nfunction mergeMessageRuns(messages) {\n\tif (Array.isArray(messages)) return _mergeMessageRuns(messages);\n\treturn RunnableLambda.from(_mergeMessageRuns);\n}\nfunction _mergeMessageRuns(messages) {\n\tif (!messages.length) return [];\n\tconst merged = [];\n\tfor (const msg of messages) {\n\t\tconst curr = msg;\n\t\tconst last = merged.pop();\n\t\tif (!last) merged.push(curr);\n\t\telse if (curr.getType() === \"tool\" || !(curr.getType() === last.getType())) merged.push(last, curr);\n\t\telse {\n\t\t\tconst lastChunk = convertToChunk(last);\n\t\t\tconst currChunk = convertToChunk(curr);\n\t\t\tconst mergedChunks = lastChunk.concat(currChunk);\n\t\t\tif (typeof lastChunk.content === \"string\" && typeof currChunk.content === \"string\") mergedChunks.content = `${lastChunk.content}\\n${currChunk.content}`;\n\t\t\tmerged.push(_chunkToMsg(mergedChunks));\n\t\t}\n\t}\n\treturn merged;\n}\nfunction trimMessages(messagesOrOptions, options) {\n\tif (Array.isArray(messagesOrOptions)) {\n\t\tconst messages = messagesOrOptions;\n\t\tif (!options) throw new Error(\"Options parameter is required when providing messages.\");\n\t\treturn _trimMessagesHelper(messages, options);\n\t} else {\n\t\tconst trimmerOptions = messagesOrOptions;\n\t\treturn RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: \"trim_messages\" });\n\t}\n}\nasync function _trimMessagesHelper(messages, options) {\n\tconst { maxTokens, tokenCounter, strategy = \"last\", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options;\n\tif (startOn && strategy === \"first\") throw new Error(\"`startOn` should only be specified if `strategy` is 'last'.\");\n\tif (includeSystem && strategy === \"first\") throw new Error(\"`includeSystem` should only be specified if `strategy` is 'last'.\");\n\tlet listTokenCounter;\n\tif (\"getNumTokens\" in tokenCounter) listTokenCounter = async (msgs) => {\n\t\tconst tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content)));\n\t\treturn tokenCounts.reduce((sum, count) => sum + count, 0);\n\t};\n\telse listTokenCounter = async (msgs) => tokenCounter(msgs);\n\tlet textSplitterFunc = defaultTextSplitter;\n\tif (textSplitter) if (\"splitText\" in textSplitter) textSplitterFunc = textSplitter.splitText;\n\telse textSplitterFunc = async (text) => textSplitter(text);\n\tif (strategy === \"first\") return _firstMaxTokens(messages, {\n\t\tmaxTokens,\n\t\ttokenCounter: listTokenCounter,\n\t\ttextSplitter: textSplitterFunc,\n\t\tpartialStrategy: allowPartial ? \"first\" : void 0,\n\t\tendOn\n\t});\n\telse if (strategy === \"last\") return _lastMaxTokens(messages, {\n\t\tmaxTokens,\n\t\ttokenCounter: listTokenCounter,\n\t\ttextSplitter: textSplitterFunc,\n\t\tallowPartial,\n\t\tincludeSystem,\n\t\tstartOn,\n\t\tendOn\n\t});\n\telse throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`);\n}\nasync function _firstMaxTokens(messages, options) {\n\tconst { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options;\n\tlet messagesCopy = [...messages];\n\tlet idx = 0;\n\tfor (let i = 0; i < messagesCopy.length; i += 1) {\n\t\tconst remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy;\n\t\tif (await tokenCounter(remainingMessages) <= maxTokens) {\n\t\t\tidx = messagesCopy.length - i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (idx < messagesCopy.length && partialStrategy) {\n\t\tlet includedPartial = false;\n\t\tif (Array.isArray(messagesCopy[idx].content)) {\n\t\t\tconst excluded = messagesCopy[idx];\n\t\t\tif (typeof excluded.content === \"string\") throw new Error(\"Expected content to be an array.\");\n\t\t\tconst numBlock = excluded.content.length;\n\t\t\tconst reversedContent = partialStrategy === \"last\" ? [...excluded.content].reverse() : excluded.content;\n\t\t\tfor (let i = 1; i <= numBlock; i += 1) {\n\t\t\t\tconst partialContent = partialStrategy === \"first\" ? reversedContent.slice(0, i) : reversedContent.slice(-i);\n\t\t\t\tconst fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== \"type\" && !k.startsWith(\"lc_\")));\n\t\t\t\tconst updatedMessage = _switchTypeToMessage(excluded.getType(), {\n\t\t\t\t\t...fields,\n\t\t\t\t\tcontent: partialContent\n\t\t\t\t});\n\t\t\t\tconst slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage];\n\t\t\t\tif (await tokenCounter(slicedMessages) <= maxTokens) {\n\t\t\t\t\tmessagesCopy = slicedMessages;\n\t\t\t\t\tidx += 1;\n\t\t\t\t\tincludedPartial = true;\n\t\t\t\t} else break;\n\t\t\t}\n\t\t\tif (includedPartial && partialStrategy === \"last\") excluded.content = [...reversedContent].reverse();\n\t\t}\n\t\tif (!includedPartial) {\n\t\t\tconst excluded = messagesCopy[idx];\n\t\t\tlet text;\n\t\t\tif (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === \"string\" || block.type === \"text\")) {\n\t\t\t\tconst textBlock = excluded.content.find((block) => block.type === \"text\" && block.text);\n\t\t\t\ttext = textBlock?.text;\n\t\t\t} else if (typeof excluded.content === \"string\") text = excluded.content;\n\t\t\tif (text) {\n\t\t\t\tconst splitTexts = await textSplitter(text);\n\t\t\t\tconst numSplits = splitTexts.length;\n\t\t\t\tif (partialStrategy === \"last\") splitTexts.reverse();\n\t\t\t\tfor (let _ = 0; _ < numSplits - 1; _ += 1) {\n\t\t\t\t\tsplitTexts.pop();\n\t\t\t\t\texcluded.content = splitTexts.join(\"\");\n\t\t\t\t\tif (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) {\n\t\t\t\t\t\tif (partialStrategy === \"last\") excluded.content = [...splitTexts].reverse().join(\"\");\n\t\t\t\t\t\tmessagesCopy = [...messagesCopy.slice(0, idx), excluded];\n\t\t\t\t\t\tidx += 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (endOn) {\n\t\tconst endOnArr = Array.isArray(endOn) ? endOn : [endOn];\n\t\twhile (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) idx -= 1;\n\t}\n\treturn messagesCopy.slice(0, idx);\n}\nasync function _lastMaxTokens(messages, options) {\n\tconst { allowPartial = false, includeSystem = false, endOn, startOn,...rest } = options;\n\tlet messagesCopy = messages.map((message) => {\n\t\tconst fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== \"type\" && !k.startsWith(\"lc_\")));\n\t\treturn _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message));\n\t});\n\tif (endOn) {\n\t\tconst endOnArr = Array.isArray(endOn) ? endOn : [endOn];\n\t\twhile (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) messagesCopy = messagesCopy.slice(0, -1);\n\t}\n\tconst swappedSystem = includeSystem && messagesCopy[0]?.getType() === \"system\";\n\tlet reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse();\n\treversed_ = await _firstMaxTokens(reversed_, {\n\t\t...rest,\n\t\tpartialStrategy: allowPartial ? \"last\" : void 0,\n\t\tendOn: startOn\n\t});\n\tif (swappedSystem) return [reversed_[0], ...reversed_.slice(1).reverse()];\n\telse return reversed_.reverse();\n}\nconst _MSG_CHUNK_MAP = {\n\thuman: {\n\t\tmessage: HumanMessage,\n\t\tmessageChunk: HumanMessageChunk\n\t},\n\tai: {\n\t\tmessage: AIMessage,\n\t\tmessageChunk: AIMessageChunk\n\t},\n\tsystem: {\n\t\tmessage: SystemMessage,\n\t\tmessageChunk: SystemMessageChunk\n\t},\n\tdeveloper: {\n\t\tmessage: SystemMessage,\n\t\tmessageChunk: SystemMessageChunk\n\t},\n\ttool: {\n\t\tmessage: ToolMessage,\n\t\tmessageChunk: ToolMessageChunk\n\t},\n\tfunction: {\n\t\tmessage: FunctionMessage,\n\t\tmessageChunk: FunctionMessageChunk\n\t},\n\tgeneric: {\n\t\tmessage: ChatMessage,\n\t\tmessageChunk: ChatMessageChunk\n\t},\n\tremove: {\n\t\tmessage: RemoveMessage,\n\t\tmessageChunk: RemoveMessage\n\t}\n};\nfunction _switchTypeToMessage(messageType, fields, returnChunk) {\n\tlet chunk;\n\tlet msg;\n\tswitch (messageType) {\n\t\tcase \"human\":\n\t\t\tif (returnChunk) chunk = new HumanMessageChunk(fields);\n\t\t\telse msg = new HumanMessage(fields);\n\t\t\tbreak;\n\t\tcase \"ai\":\n\t\t\tif (returnChunk) {\n\t\t\t\tlet aiChunkFields = { ...fields };\n\t\t\t\tif (\"tool_calls\" in aiChunkFields) aiChunkFields = {\n\t\t\t\t\t...aiChunkFields,\n\t\t\t\t\ttool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n\t\t\t\t\t\t...tc,\n\t\t\t\t\t\ttype: \"tool_call_chunk\",\n\t\t\t\t\t\tindex: void 0,\n\t\t\t\t\t\targs: JSON.stringify(tc.args)\n\t\t\t\t\t}))\n\t\t\t\t};\n\t\t\t\tchunk = new AIMessageChunk(aiChunkFields);\n\t\t\t} else msg = new AIMessage(fields);\n\t\t\tbreak;\n\t\tcase \"system\":\n\t\t\tif (returnChunk) chunk = new SystemMessageChunk(fields);\n\t\t\telse msg = new SystemMessage(fields);\n\t\t\tbreak;\n\t\tcase \"developer\":\n\t\t\tif (returnChunk) chunk = new SystemMessageChunk({\n\t\t\t\t...fields,\n\t\t\t\tadditional_kwargs: {\n\t\t\t\t\t...fields.additional_kwargs,\n\t\t\t\t\t__openai_role__: \"developer\"\n\t\t\t\t}\n\t\t\t});\n\t\t\telse msg = new SystemMessage({\n\t\t\t\t...fields,\n\t\t\t\tadditional_kwargs: {\n\t\t\t\t\t...fields.additional_kwargs,\n\t\t\t\t\t__openai_role__: \"developer\"\n\t\t\t\t}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\tif (\"tool_call_id\" in fields) if (returnChunk) chunk = new ToolMessageChunk(fields);\n\t\t\telse msg = new ToolMessage(fields);\n\t\t\telse throw new Error(\"Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.\");\n\t\t\tbreak;\n\t\tcase \"function\":\n\t\t\tif (returnChunk) chunk = new FunctionMessageChunk(fields);\n\t\t\telse {\n\t\t\t\tif (!fields.name) throw new Error(\"FunctionMessage must have a 'name' field\");\n\t\t\t\tmsg = new FunctionMessage(fields);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"generic\":\n\t\t\tif (\"role\" in fields) if (returnChunk) chunk = new ChatMessageChunk(fields);\n\t\t\telse msg = new ChatMessage(fields);\n\t\t\telse throw new Error(\"Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.\");\n\t\t\tbreak;\n\t\tdefault: throw new Error(`Unrecognized message type ${messageType}`);\n\t}\n\tif (returnChunk && chunk) return chunk;\n\tif (msg) return msg;\n\tthrow new Error(`Unrecognized message type ${messageType}`);\n}\nfunction _chunkToMsg(chunk) {\n\tconst chunkType = chunk.getType();\n\tlet msg;\n\tconst fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => ![\"type\", \"tool_call_chunks\"].includes(k) && !k.startsWith(\"lc_\")));\n\tif (chunkType in _MSG_CHUNK_MAP) msg = _switchTypeToMessage(chunkType, fields);\n\tif (!msg) throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`);\n\treturn msg;\n}\n/**\n* The default text splitter function that splits text by newlines.\n*\n* @param {string} text\n* @returns A promise that resolves to an array of strings split by newlines.\n*/\nfunction defaultTextSplitter(text) {\n\tconst splits = text.split(\"\\n\");\n\treturn Promise.resolve([...splits.slice(0, -1).map((s) => `${s}\\n`), splits[splits.length - 1]]);\n}\n\n//#endregion\nexport { defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages };\n//# sourceMappingURL=transformers.js.map","//#region src/messages/content/tools.ts\nconst KNOWN_BLOCK_TYPES = [\n\t\"tool_call\",\n\t\"tool_call_chunk\",\n\t\"invalid_tool_call\",\n\t\"server_tool_call\",\n\t\"server_tool_call_chunk\",\n\t\"server_tool_call_result\"\n];\n\n//#endregion\nexport { KNOWN_BLOCK_TYPES };\n//# sourceMappingURL=tools.js.map","//#region src/messages/content/multimodal.ts\nconst KNOWN_BLOCK_TYPES = [\n\t\"image\",\n\t\"video\",\n\t\"audio\",\n\t\"text-plain\",\n\t\"file\"\n];\n\n//#endregion\nexport { KNOWN_BLOCK_TYPES };\n//# sourceMappingURL=multimodal.js.map","import { KNOWN_BLOCK_TYPES } from \"./tools.js\";\nimport { KNOWN_BLOCK_TYPES as KNOWN_BLOCK_TYPES$1 } from \"./multimodal.js\";\n\n//#region src/messages/content/index.ts\nconst KNOWN_BLOCK_TYPES$2 = [\n\t\"text\",\n\t\"reasoning\",\n\t...KNOWN_BLOCK_TYPES,\n\t...KNOWN_BLOCK_TYPES$1\n];\n\n//#endregion\nexport { KNOWN_BLOCK_TYPES$2 as KNOWN_BLOCK_TYPES };\n//# sourceMappingURL=index.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { convertToOpenAIImageBlock, convertToProviderContentBlock, isBase64ContentBlock, isDataContentBlock, isIDContentBlock, isPlainTextContentBlock, isURLContentBlock, parseBase64DataUrl, parseMimeType } from \"./content/data.js\";\nimport { isMessage } from \"./message.js\";\nimport { BaseMessage, BaseMessageChunk, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, isBaseMessage, isBaseMessageChunk, isOpenAIToolCallArray, mergeContent } from \"./base.js\";\nimport { mergeResponseMetadata, mergeUsageMetadata } from \"./metadata.js\";\nimport { ToolMessage, ToolMessageChunk, defaultToolCallParser, isDirectToolOutput, isToolMessage, isToolMessageChunk } from \"./tool.js\";\nimport { AIMessage, AIMessageChunk, isAIMessage, isAIMessageChunk } from \"./ai.js\";\nimport { ChatMessage, ChatMessageChunk, isChatMessage, isChatMessageChunk } from \"./chat.js\";\nimport { FunctionMessage, FunctionMessageChunk, isFunctionMessage, isFunctionMessageChunk } from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk, isHumanMessage, isHumanMessageChunk } from \"./human.js\";\nimport { SystemMessage, SystemMessageChunk, isSystemMessage, isSystemMessageChunk } from \"./system.js\";\nimport { RemoveMessage } from \"./modifier.js\";\nimport { coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from \"./utils.js\";\nimport { defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages } from \"./transformers.js\";\nimport { KNOWN_BLOCK_TYPES } from \"./content/index.js\";\n\n//#region src/messages/index.ts\nvar messages_exports = {};\n__export(messages_exports, {\n\tAIMessage: () => AIMessage,\n\tAIMessageChunk: () => AIMessageChunk,\n\tBaseMessage: () => BaseMessage,\n\tBaseMessageChunk: () => BaseMessageChunk,\n\tChatMessage: () => ChatMessage,\n\tChatMessageChunk: () => ChatMessageChunk,\n\tFunctionMessage: () => FunctionMessage,\n\tFunctionMessageChunk: () => FunctionMessageChunk,\n\tHumanMessage: () => HumanMessage,\n\tHumanMessageChunk: () => HumanMessageChunk,\n\tKNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES,\n\tRemoveMessage: () => RemoveMessage,\n\tSystemMessage: () => SystemMessage,\n\tSystemMessageChunk: () => SystemMessageChunk,\n\tToolMessage: () => ToolMessage,\n\tToolMessageChunk: () => ToolMessageChunk,\n\t_isMessageFieldWithRole: () => _isMessageFieldWithRole,\n\t_mergeDicts: () => _mergeDicts,\n\t_mergeLists: () => _mergeLists,\n\t_mergeObj: () => _mergeObj,\n\t_mergeStatus: () => _mergeStatus,\n\tcoerceMessageLikeToMessage: () => coerceMessageLikeToMessage,\n\tconvertToChunk: () => convertToChunk,\n\tconvertToOpenAIImageBlock: () => convertToOpenAIImageBlock,\n\tconvertToProviderContentBlock: () => convertToProviderContentBlock,\n\tdefaultTextSplitter: () => defaultTextSplitter,\n\tdefaultToolCallParser: () => defaultToolCallParser,\n\tfilterMessages: () => filterMessages,\n\tgetBufferString: () => getBufferString,\n\tiife: () => iife,\n\tisAIMessage: () => isAIMessage,\n\tisAIMessageChunk: () => isAIMessageChunk,\n\tisBase64ContentBlock: () => isBase64ContentBlock,\n\tisBaseMessage: () => isBaseMessage,\n\tisBaseMessageChunk: () => isBaseMessageChunk,\n\tisChatMessage: () => isChatMessage,\n\tisChatMessageChunk: () => isChatMessageChunk,\n\tisDataContentBlock: () => isDataContentBlock,\n\tisDirectToolOutput: () => isDirectToolOutput,\n\tisFunctionMessage: () => isFunctionMessage,\n\tisFunctionMessageChunk: () => isFunctionMessageChunk,\n\tisHumanMessage: () => isHumanMessage,\n\tisHumanMessageChunk: () => isHumanMessageChunk,\n\tisIDContentBlock: () => isIDContentBlock,\n\tisMessage: () => isMessage,\n\tisOpenAIToolCallArray: () => isOpenAIToolCallArray,\n\tisPlainTextContentBlock: () => isPlainTextContentBlock,\n\tisSystemMessage: () => isSystemMessage,\n\tisSystemMessageChunk: () => isSystemMessageChunk,\n\tisToolMessage: () => isToolMessage,\n\tisToolMessageChunk: () => isToolMessageChunk,\n\tisURLContentBlock: () => isURLContentBlock,\n\tmapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages,\n\tmapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage,\n\tmapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages,\n\tmergeContent: () => mergeContent,\n\tmergeMessageRuns: () => mergeMessageRuns,\n\tmergeResponseMetadata: () => mergeResponseMetadata,\n\tmergeUsageMetadata: () => mergeUsageMetadata,\n\tparseBase64DataUrl: () => parseBase64DataUrl,\n\tparseMimeType: () => parseMimeType,\n\ttrimMessages: () => trimMessages\n});\n\n//#endregion\nexport { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessage, FunctionMessageChunk, HumanMessage, HumanMessageChunk, KNOWN_BLOCK_TYPES, RemoveMessage, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, messages_exports, parseBase64DataUrl, parseMimeType, trimMessages };\n//# sourceMappingURL=index.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\nimport { Serializable } from \"./load/serializable.js\";\nimport { AIMessage } from \"./messages/ai.js\";\nimport { HumanMessage } from \"./messages/human.js\";\nimport \"./messages/index.js\";\n\n//#region src/chat_history.ts\nvar chat_history_exports = {};\n__export(chat_history_exports, {\n\tBaseChatMessageHistory: () => BaseChatMessageHistory,\n\tBaseListChatMessageHistory: () => BaseListChatMessageHistory,\n\tInMemoryChatMessageHistory: () => InMemoryChatMessageHistory\n});\n/**\n* Base class for all chat message histories. All chat message histories\n* should extend this class.\n*/\nvar BaseChatMessageHistory = class extends Serializable {\n\t/**\n\t* Add a list of messages.\n\t*\n\t* Implementations should override this method to handle bulk addition of messages\n\t* in an efficient manner to avoid unnecessary round-trips to the underlying store.\n\t*\n\t* @param messages - A list of BaseMessage objects to store.\n\t*/\n\tasync addMessages(messages) {\n\t\tfor (const message of messages) await this.addMessage(message);\n\t}\n};\n/**\n* Base class for all list chat message histories. All list chat message\n* histories should extend this class.\n*/\nvar BaseListChatMessageHistory = class extends Serializable {\n\t/**\n\t* This is a convenience method for adding a human message string to the store.\n\t* Please note that this is a convenience method. Code should favor the\n\t* bulk addMessages interface instead to save on round-trips to the underlying\n\t* persistence layer.\n\t* This method may be deprecated in a future release.\n\t*/\n\taddUserMessage(message) {\n\t\treturn this.addMessage(new HumanMessage(message));\n\t}\n\t/**\n\t* This is a convenience method for adding an AI message string to the store.\n\t* Please note that this is a convenience method. Code should favor the bulk\n\t* addMessages interface instead to save on round-trips to the underlying\n\t* persistence layer.\n\t* This method may be deprecated in a future release.\n\t*/\n\taddAIMessage(message) {\n\t\treturn this.addMessage(new AIMessage(message));\n\t}\n\t/**\n\t* Add a list of messages.\n\t*\n\t* Implementations should override this method to handle bulk addition of messages\n\t* in an efficient manner to avoid unnecessary round-trips to the underlying store.\n\t*\n\t* @param messages - A list of BaseMessage objects to store.\n\t*/\n\tasync addMessages(messages) {\n\t\tfor (const message of messages) await this.addMessage(message);\n\t}\n\t/**\n\t* Remove all messages from the store.\n\t*/\n\tclear() {\n\t\tthrow new Error(\"Not implemented.\");\n\t}\n};\n/**\n* Class for storing chat message history in-memory. It extends the\n* BaseListChatMessageHistory class and provides methods to get, add, and\n* clear messages.\n*/\nvar InMemoryChatMessageHistory = class extends BaseListChatMessageHistory {\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"stores\",\n\t\t\"message\",\n\t\t\"in_memory\"\n\t];\n\tmessages = [];\n\tconstructor(messages) {\n\t\tsuper(...arguments);\n\t\tthis.messages = messages ?? [];\n\t}\n\t/**\n\t* Method to get all the messages stored in the ChatMessageHistory\n\t* instance.\n\t* @returns Array of stored BaseMessage instances.\n\t*/\n\tasync getMessages() {\n\t\treturn this.messages;\n\t}\n\t/**\n\t* Method to add a new message to the ChatMessageHistory instance.\n\t* @param message The BaseMessage instance to add.\n\t* @returns A promise that resolves when the message has been added.\n\t*/\n\tasync addMessage(message) {\n\t\tthis.messages.push(message);\n\t}\n\t/**\n\t* Method to clear all the messages from the ChatMessageHistory instance.\n\t* @returns A promise that resolves when all messages have been cleared.\n\t*/\n\tasync clear() {\n\t\tthis.messages = [];\n\t}\n};\n\n//#endregion\nexport { BaseChatMessageHistory, BaseListChatMessageHistory, InMemoryChatMessageHistory, chat_history_exports };\n//# sourceMappingURL=chat_history.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\nimport { AsyncCaller } from \"./utils/async_caller.js\";\n\n//#region src/embeddings.ts\nvar embeddings_exports = {};\n__export(embeddings_exports, { Embeddings: () => Embeddings });\n/**\n* An abstract class that provides methods for embedding documents and\n* queries using LangChain.\n*/\nvar Embeddings = class {\n\t/**\n\t* The async caller should be used by subclasses to make any async calls,\n\t* which will thus benefit from the concurrency and retry logic.\n\t*/\n\tcaller;\n\tconstructor(params) {\n\t\tthis.caller = new AsyncCaller(params ?? {});\n\t}\n};\n\n//#endregion\nexport { Embeddings, embeddings_exports };\n//# sourceMappingURL=embeddings.js.map","//#region src/index.ts\nvar src_exports = {};\n\n//#endregion\nexport { src_exports };\n//# sourceMappingURL=index.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\n\n//#region src/memory.ts\nvar memory_exports = {};\n__export(memory_exports, {\n\tBaseMemory: () => BaseMemory,\n\tgetInputValue: () => getInputValue,\n\tgetOutputValue: () => getOutputValue,\n\tgetPromptInputKey: () => getPromptInputKey\n});\n/**\n* Abstract base class for memory in LangChain's Chains. Memory refers to\n* the state in Chains. It can be used to store information about past\n* executions of a Chain and inject that information into the inputs of\n* future executions of the Chain.\n*/\nvar BaseMemory = class {};\nconst getValue = (values, key) => {\n\tif (key !== void 0) return values[key];\n\tconst keys = Object.keys(values);\n\tif (keys.length === 1) return values[keys[0]];\n};\n/**\n* This function is used by memory classes to select the input value\n* to use for the memory. If there is only one input value, it is used.\n* If there are multiple input values, the inputKey must be specified.\n*/\nconst getInputValue = (inputValues, inputKey) => {\n\tconst value = getValue(inputValues, inputKey);\n\tif (!value) {\n\t\tconst keys = Object.keys(inputValues);\n\t\tthrow new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`);\n\t}\n\treturn value;\n};\n/**\n* This function is used by memory classes to select the output value\n* to use for the memory. If there is only one output value, it is used.\n* If there are multiple output values, the outputKey must be specified.\n* If no outputKey is specified, an error is thrown.\n*/\nconst getOutputValue = (outputValues, outputKey) => {\n\tconst value = getValue(outputValues, outputKey);\n\tif (!value && value !== \"\") {\n\t\tconst keys = Object.keys(outputValues);\n\t\tthrow new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`);\n\t}\n\treturn value;\n};\n/**\n* Function used by memory classes to get the key of the prompt input,\n* excluding any keys that are memory variables or the \"stop\" key. If\n* there is not exactly one prompt input key, an error is thrown.\n*/\nfunction getPromptInputKey(inputs, memoryVariables) {\n\tconst promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== \"stop\");\n\tif (promptInputKeys.length !== 1) throw new Error(`One input key expected, but got ${promptInputKeys.length}`);\n\treturn promptInputKeys[0];\n}\n\n//#endregion\nexport { BaseMemory, getInputValue, getOutputValue, getPromptInputKey, memory_exports };\n//# sourceMappingURL=memory.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\nimport { Serializable } from \"./load/serializable.js\";\nimport { HumanMessage } from \"./messages/human.js\";\nimport { getBufferString } from \"./messages/utils.js\";\n\n//#region src/prompt_values.ts\nvar prompt_values_exports = {};\n__export(prompt_values_exports, {\n\tBasePromptValue: () => BasePromptValue,\n\tChatPromptValue: () => ChatPromptValue,\n\tImagePromptValue: () => ImagePromptValue,\n\tStringPromptValue: () => StringPromptValue\n});\n/**\n* Base PromptValue class. All prompt values should extend this class.\n*/\nvar BasePromptValue = class extends Serializable {};\n/**\n* Represents a prompt value as a string. It extends the BasePromptValue\n* class and overrides the toString and toChatMessages methods.\n*/\nvar StringPromptValue = class extends BasePromptValue {\n\tstatic lc_name() {\n\t\treturn \"StringPromptValue\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"prompt_values\"];\n\tlc_serializable = true;\n\tvalue;\n\tconstructor(value) {\n\t\tsuper({ value });\n\t\tthis.value = value;\n\t}\n\ttoString() {\n\t\treturn this.value;\n\t}\n\ttoChatMessages() {\n\t\treturn [new HumanMessage(this.value)];\n\t}\n};\n/**\n* Class that represents a chat prompt value. It extends the\n* BasePromptValue and includes an array of BaseMessage instances.\n*/\nvar ChatPromptValue = class extends BasePromptValue {\n\tlc_namespace = [\"langchain_core\", \"prompt_values\"];\n\tlc_serializable = true;\n\tstatic lc_name() {\n\t\treturn \"ChatPromptValue\";\n\t}\n\tmessages;\n\tconstructor(fields) {\n\t\tif (Array.isArray(fields)) fields = { messages: fields };\n\t\tsuper(fields);\n\t\tthis.messages = fields.messages;\n\t}\n\ttoString() {\n\t\treturn getBufferString(this.messages);\n\t}\n\ttoChatMessages() {\n\t\treturn this.messages;\n\t}\n};\n/**\n* Class that represents an image prompt value. It extends the\n* BasePromptValue and includes an ImageURL instance.\n*/\nvar ImagePromptValue = class extends BasePromptValue {\n\tlc_namespace = [\"langchain_core\", \"prompt_values\"];\n\tlc_serializable = true;\n\tstatic lc_name() {\n\t\treturn \"ImagePromptValue\";\n\t}\n\timageUrl;\n\t/** @ignore */\n\tvalue;\n\tconstructor(fields) {\n\t\tif (!(\"imageUrl\" in fields)) fields = { imageUrl: fields };\n\t\tsuper(fields);\n\t\tthis.imageUrl = fields.imageUrl;\n\t}\n\ttoString() {\n\t\treturn this.imageUrl.url;\n\t}\n\ttoChatMessages() {\n\t\treturn [new HumanMessage({ content: [{\n\t\t\ttype: \"image_url\",\n\t\t\timage_url: {\n\t\t\t\tdetail: this.imageUrl.detail,\n\t\t\t\turl: this.imageUrl.url\n\t\t\t}\n\t\t}] })];\n\t}\n};\n\n//#endregion\nexport { BasePromptValue, ChatPromptValue, ImagePromptValue, StringPromptValue, prompt_values_exports };\n//# sourceMappingURL=prompt_values.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\nimport { Serializable } from \"./load/serializable.js\";\n\n//#region src/stores.ts\nvar stores_exports = {};\n__export(stores_exports, {\n\tBaseStore: () => BaseStore,\n\tInMemoryStore: () => InMemoryStore\n});\n/**\n* Abstract interface for a key-value store.\n*/\nvar BaseStore = class extends Serializable {};\n/**\n* In-memory implementation of the BaseStore using a dictionary. Used for\n* storing key-value pairs in memory.\n* @example\n* ```typescript\n* const store = new InMemoryStore();\n* await store.mset(\n* Array.from({ length: 5 }).map((_, index) => [\n* `message:id:${index}`,\n* index % 2 === 0\n* ? new AIMessage(\"ai stuff...\")\n* : new HumanMessage(\"human stuff...\"),\n* ]),\n* );\n*\n* const retrievedMessages = await store.mget([\"message:id:0\", \"message:id:1\"]);\n* await store.mdelete(await store.yieldKeys(\"message:id:\").toArray());\n* ```\n*/\nvar InMemoryStore = class extends BaseStore {\n\tlc_namespace = [\"langchain\", \"storage\"];\n\tstore = {};\n\t/**\n\t* Retrieves the values associated with the given keys from the store.\n\t* @param keys Keys to retrieve values for.\n\t* @returns Array of values associated with the given keys.\n\t*/\n\tasync mget(keys) {\n\t\treturn keys.map((key) => this.store[key]);\n\t}\n\t/**\n\t* Sets the values for the given keys in the store.\n\t* @param keyValuePairs Array of key-value pairs to set in the store.\n\t* @returns Promise that resolves when all key-value pairs have been set.\n\t*/\n\tasync mset(keyValuePairs) {\n\t\tfor (const [key, value] of keyValuePairs) this.store[key] = value;\n\t}\n\t/**\n\t* Deletes the given keys and their associated values from the store.\n\t* @param keys Keys to delete from the store.\n\t* @returns Promise that resolves when all keys have been deleted.\n\t*/\n\tasync mdelete(keys) {\n\t\tfor (const key of keys) delete this.store[key];\n\t}\n\t/**\n\t* Asynchronous generator that yields keys from the store. If a prefix is\n\t* provided, it only yields keys that start with the prefix.\n\t* @param prefix Optional prefix to filter keys.\n\t* @returns AsyncGenerator that yields keys from the store.\n\t*/\n\tasync *yieldKeys(prefix) {\n\t\tconst keys = Object.keys(this.store);\n\t\tfor (const key of keys) if (prefix === void 0 || key.startsWith(prefix)) yield key;\n\t}\n};\n\n//#endregion\nexport { BaseStore, InMemoryStore, stores_exports };\n//# sourceMappingURL=stores.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { CallbackManager, parseCallbackConfigArg } from \"../callbacks/manager.js\";\nimport { ensureConfig } from \"../runnables/config.js\";\nimport { Runnable } from \"../runnables/base.js\";\n\n//#region src/retrievers/index.ts\nvar retrievers_exports = {};\n__export(retrievers_exports, { BaseRetriever: () => BaseRetriever });\n/**\n* Abstract base class for a document retrieval system, designed to\n* process string queries and return the most relevant documents from a source.\n*\n* `BaseRetriever` provides common properties and methods for derived retrievers,\n* such as callbacks, tagging, and verbose logging. Custom retrieval systems\n* should extend this class and implement `_getRelevantDocuments` to define\n* the specific retrieval logic.\n*\n* @template Metadata - The type of metadata associated with each document,\n* defaulting to `Record`.\n*/\nvar BaseRetriever = class extends Runnable {\n\t/**\n\t* Optional callbacks to handle various events in the retrieval process.\n\t*/\n\tcallbacks;\n\t/**\n\t* Tags to label or categorize the retrieval operation.\n\t*/\n\ttags;\n\t/**\n\t* Metadata to provide additional context or information about the retrieval\n\t* operation.\n\t*/\n\tmetadata;\n\t/**\n\t* If set to `true`, enables verbose logging for the retrieval process.\n\t*/\n\tverbose;\n\t/**\n\t* Constructs a new `BaseRetriever` instance with optional configuration fields.\n\t*\n\t* @param fields - Optional input configuration that can include `callbacks`,\n\t* `tags`, `metadata`, and `verbose` settings for custom retriever behavior.\n\t*/\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.callbacks = fields?.callbacks;\n\t\tthis.tags = fields?.tags ?? [];\n\t\tthis.metadata = fields?.metadata ?? {};\n\t\tthis.verbose = fields?.verbose ?? false;\n\t}\n\t/**\n\t* TODO: This should be an abstract method, but we'd like to avoid breaking\n\t* changes to people currently using subclassed custom retrievers.\n\t* Change it on next major release.\n\t*/\n\t/**\n\t* Placeholder method for retrieving relevant documents based on a query.\n\t*\n\t* This method is intended to be implemented by subclasses and will be\n\t* converted to an abstract method in the next major release. Currently, it\n\t* throws an error if not implemented, ensuring that custom retrievers define\n\t* the specific retrieval logic.\n\t*\n\t* @param _query - The query string used to search for relevant documents.\n\t* @param _callbacks - (optional) Callback manager for managing callbacks\n\t* during retrieval.\n\t* @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query.\n\t* @throws {Error} Throws an error indicating the method is not implemented.\n\t*/\n\t_getRelevantDocuments(_query, _callbacks) {\n\t\tthrow new Error(\"Not implemented!\");\n\t}\n\t/**\n\t* Executes a retrieval operation.\n\t*\n\t* @param input - The query string used to search for relevant documents.\n\t* @param options - (optional) Configuration options for the retrieval run,\n\t* which may include callbacks, tags, and metadata.\n\t* @returns A promise that resolves to an array of `DocumentInterface` instances\n\t* representing the most relevant documents to the query.\n\t*/\n\tasync invoke(input, options) {\n\t\tconst parsedConfig = ensureConfig(parseCallbackConfigArg(options));\n\t\tconst callbackManager_ = await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose });\n\t\tconst runManager = await callbackManager_?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, void 0, void 0, void 0, parsedConfig.runName);\n\t\ttry {\n\t\t\tconst results = await this._getRelevantDocuments(input, runManager);\n\t\t\tawait runManager?.handleRetrieverEnd(results);\n\t\t\treturn results;\n\t\t} catch (error) {\n\t\t\tawait runManager?.handleRetrieverError(error);\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\n//#endregion\nexport { BaseRetriever, retrievers_exports };\n//# sourceMappingURL=index.js.map","import { __export } from \"./_virtual/rolldown_runtime.js\";\nimport { Serializable } from \"./load/serializable.js\";\nimport { BaseRetriever } from \"./retrievers/index.js\";\n\n//#region src/vectorstores.ts\nvar vectorstores_exports = {};\n__export(vectorstores_exports, {\n\tSaveableVectorStore: () => SaveableVectorStore,\n\tVectorStore: () => VectorStore,\n\tVectorStoreRetriever: () => VectorStoreRetriever\n});\n/**\n* Class for retrieving documents from a `VectorStore` based on vector similarity\n* or maximal marginal relevance (MMR).\n*\n* `VectorStoreRetriever` extends `BaseRetriever`, implementing methods for\n* adding documents to the underlying vector store and performing document\n* retrieval with optional configurations.\n*\n* @class VectorStoreRetriever\n* @extends BaseRetriever\n* @implements VectorStoreRetrieverInterface\n* @template V - Type of vector store implementing `VectorStoreInterface`.\n*/\nvar VectorStoreRetriever = class extends BaseRetriever {\n\tstatic lc_name() {\n\t\treturn \"VectorStoreRetriever\";\n\t}\n\tget lc_namespace() {\n\t\treturn [\"langchain_core\", \"vectorstores\"];\n\t}\n\t/**\n\t* The instance of `VectorStore` used for storing and retrieving document embeddings.\n\t* This vector store must implement the `VectorStoreInterface` to be compatible\n\t* with the retriever’s operations.\n\t*/\n\tvectorStore;\n\t/**\n\t* Specifies the number of documents to retrieve for each search query.\n\t* Defaults to 4 if not specified, providing a basic result count for similarity or MMR searches.\n\t*/\n\tk = 4;\n\t/**\n\t* Determines the type of search operation to perform on the vector store.\n\t*\n\t* - `\"similarity\"` (default): Conducts a similarity search based purely on vector similarity\n\t* to the query.\n\t* - `\"mmr\"`: Executes a maximal marginal relevance (MMR) search, balancing relevance and\n\t* diversity in the retrieved results.\n\t*/\n\tsearchType = \"similarity\";\n\t/**\n\t* Additional options specific to maximal marginal relevance (MMR) search, applicable\n\t* only if `searchType` is set to `\"mmr\"`.\n\t*\n\t* Includes:\n\t* - `fetchK`: The initial number of documents fetched before applying the MMR algorithm,\n\t* allowing for a larger selection from which to choose the most diverse results.\n\t* - `lambda`: A parameter between 0 and 1 to adjust the relevance-diversity balance,\n\t* where 0 prioritizes diversity and 1 prioritizes relevance.\n\t*/\n\tsearchKwargs;\n\t/**\n\t* Optional filter applied to search results, defined by the `FilterType` of the vector store.\n\t* Allows for refined, targeted results by restricting the returned documents based\n\t* on specified filter criteria.\n\t*/\n\tfilter;\n\t/**\n\t* Returns the type of vector store, as defined by the `vectorStore` instance.\n\t*\n\t* @returns {string} The vector store type.\n\t*/\n\t_vectorstoreType() {\n\t\treturn this.vectorStore._vectorstoreType();\n\t}\n\t/**\n\t* Initializes a new instance of `VectorStoreRetriever` with the specified configuration.\n\t*\n\t* This constructor configures the retriever to interact with a given `VectorStore`\n\t* and supports different retrieval strategies, including similarity search and maximal\n\t* marginal relevance (MMR) search. Various options allow customization of the number\n\t* of documents retrieved per query, filtering based on conditions, and fine-tuning\n\t* MMR-specific parameters.\n\t*\n\t* @param fields - Configuration options for setting up the retriever:\n\t*\n\t* - `vectorStore` (required): The `VectorStore` instance implementing `VectorStoreInterface`\n\t* that will be used to store and retrieve document embeddings. This is the core component\n\t* of the retriever, enabling vector-based similarity and MMR searches.\n\t*\n\t* - `k` (optional): Specifies the number of documents to retrieve per search query. If not\n\t* provided, defaults to 4. This count determines the number of most relevant documents returned\n\t* for each search operation, balancing performance with comprehensiveness.\n\t*\n\t* - `searchType` (optional): Defines the search approach used by the retriever, allowing for\n\t* flexibility between two methods:\n\t* - `\"similarity\"` (default): A similarity-based search, retrieving documents with high vector\n\t* similarity to the query. This type prioritizes relevance and is often used when diversity\n\t* among results is less critical.\n\t* - `\"mmr\"`: Maximal Marginal Relevance search, which combines relevance with diversity. MMR\n\t* is useful for scenarios where varied content is essential, as it selects results that\n\t* both match the query and introduce content diversity.\n\t*\n\t* - `filter` (optional): A filter of type `FilterType`, defined by the vector store, that allows\n\t* for refined and targeted search results. This filter applies specified conditions to limit\n\t* which documents are eligible for retrieval, offering control over the scope of results.\n\t*\n\t* - `searchKwargs` (optional, applicable only if `searchType` is `\"mmr\"`): Additional settings\n\t* for configuring MMR-specific behavior. These parameters allow further tuning of the MMR\n\t* search process:\n\t* - `fetchK`: The initial number of documents fetched from the vector store before the MMR\n\t* algorithm is applied. Fetching a larger set enables the algorithm to select a more\n\t* diverse subset of documents.\n\t* - `lambda`: A parameter controlling the relevance-diversity balance, where 0 emphasizes\n\t* diversity and 1 prioritizes relevance. Intermediate values provide a blend of the two,\n\t* allowing customization based on the importance of content variety relative to query relevance.\n\t*/\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.vectorStore = fields.vectorStore;\n\t\tthis.k = fields.k ?? this.k;\n\t\tthis.searchType = fields.searchType ?? this.searchType;\n\t\tthis.filter = fields.filter;\n\t\tif (fields.searchType === \"mmr\") this.searchKwargs = fields.searchKwargs;\n\t}\n\t/**\n\t* Retrieves relevant documents based on the specified query, using either\n\t* similarity or maximal marginal relevance (MMR) search.\n\t*\n\t* If `searchType` is set to `\"mmr\"`, performs an MMR search to balance\n\t* similarity and diversity among results. If `searchType` is `\"similarity\"`,\n\t* retrieves results purely based on similarity to the query.\n\t*\n\t* @param query - The query string used to find relevant documents.\n\t* @param runManager - Optional callback manager for tracking retrieval progress.\n\t* @returns A promise that resolves to an array of `DocumentInterface` instances\n\t* representing the most relevant documents to the query.\n\t* @throws {Error} Throws an error if MMR search is requested but not supported\n\t* by the vector store.\n\t* @protected\n\t*/\n\tasync _getRelevantDocuments(query, runManager) {\n\t\tif (this.searchType === \"mmr\") {\n\t\t\tif (typeof this.vectorStore.maxMarginalRelevanceSearch !== \"function\") throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);\n\t\t\treturn this.vectorStore.maxMarginalRelevanceSearch(query, {\n\t\t\t\tk: this.k,\n\t\t\t\tfilter: this.filter,\n\t\t\t\t...this.searchKwargs\n\t\t\t}, runManager?.getChild(\"vectorstore\"));\n\t\t}\n\t\treturn this.vectorStore.similaritySearch(query, this.k, this.filter, runManager?.getChild(\"vectorstore\"));\n\t}\n\t/**\n\t* Adds an array of documents to the vector store, embedding them as part of\n\t* the storage process.\n\t*\n\t* This method delegates document embedding and storage to the `addDocuments`\n\t* method of the underlying vector store.\n\t*\n\t* @param documents - An array of documents to embed and add to the vector store.\n\t* @param options - Optional settings to customize document addition.\n\t* @returns A promise that resolves to an array of document IDs or `void`,\n\t* depending on the vector store's implementation.\n\t*/\n\tasync addDocuments(documents, options) {\n\t\treturn this.vectorStore.addDocuments(documents, options);\n\t}\n};\n/**\n* Abstract class representing a vector storage system for performing\n* similarity searches on embedded documents.\n*\n* `VectorStore` provides methods for adding precomputed vectors or documents,\n* removing documents based on criteria, and performing similarity searches\n* with optional scoring. Subclasses are responsible for implementing specific\n* storage mechanisms and the exact behavior of certain abstract methods.\n*\n* @abstract\n* @extends Serializable\n* @implements VectorStoreInterface\n*/\nvar VectorStore = class extends Serializable {\n\t/**\n\t* Namespace within LangChain to uniquely identify this vector store's\n\t* location, based on the vector store type.\n\t*\n\t* @internal\n\t*/\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"vectorstores\",\n\t\tthis._vectorstoreType()\n\t];\n\t/**\n\t* Embeddings interface for generating vector embeddings from text queries,\n\t* enabling vector-based similarity searches.\n\t*/\n\tembeddings;\n\t/**\n\t* Initializes a new vector store with embeddings and database configuration.\n\t*\n\t* @param embeddings - Instance of `EmbeddingsInterface` used to embed queries.\n\t* @param dbConfig - Configuration settings for the database or storage system.\n\t*/\n\tconstructor(embeddings, dbConfig) {\n\t\tsuper(dbConfig);\n\t\tthis.embeddings = embeddings;\n\t}\n\t/**\n\t* Deletes documents from the vector store based on the specified parameters.\n\t*\n\t* @param _params - Flexible key-value pairs defining conditions for document deletion.\n\t* @returns A promise that resolves once the deletion is complete.\n\t*/\n\tasync delete(_params) {\n\t\tthrow new Error(\"Not implemented.\");\n\t}\n\t/**\n\t* Searches for documents similar to a text query by embedding the query and\n\t* performing a similarity search on the resulting vector.\n\t*\n\t* @param query - Text query for finding similar documents.\n\t* @param k - Number of similar results to return. Defaults to 4.\n\t* @param filter - Optional filter based on `FilterType`.\n\t* @param _callbacks - Optional callbacks for monitoring search progress\n\t* @returns A promise resolving to an array of `DocumentInterface` instances representing similar documents.\n\t*/\n\tasync similaritySearch(query, k = 4, filter = void 0, _callbacks = void 0) {\n\t\tconst results = await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter);\n\t\treturn results.map((result) => result[0]);\n\t}\n\t/**\n\t* Searches for documents similar to a text query by embedding the query,\n\t* and returns results with similarity scores.\n\t*\n\t* @param query - Text query for finding similar documents.\n\t* @param k - Number of similar results to return. Defaults to 4.\n\t* @param filter - Optional filter based on `FilterType`.\n\t* @param _callbacks - Optional callbacks for monitoring search progress\n\t* @returns A promise resolving to an array of tuples, each containing a\n\t* document and its similarity score.\n\t*/\n\tasync similaritySearchWithScore(query, k = 4, filter = void 0, _callbacks = void 0) {\n\t\treturn this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter);\n\t}\n\t/**\n\t* Creates a `VectorStore` instance from an array of text strings and optional\n\t* metadata, using the specified embeddings and database configuration.\n\t*\n\t* Subclasses must implement this method to define how text and metadata\n\t* are embedded and stored in the vector store. Throws an error if not overridden.\n\t*\n\t* @param _texts - Array of strings representing the text documents to be stored.\n\t* @param _metadatas - Metadata for the texts, either as an array (one for each text)\n\t* or a single object (applied to all texts).\n\t* @param _embeddings - Instance of `EmbeddingsInterface` to embed the texts.\n\t* @param _dbConfig - Database configuration settings.\n\t* @returns A promise that resolves to a new `VectorStore` instance.\n\t* @throws {Error} Throws an error if this method is not overridden by a subclass.\n\t*/\n\tstatic fromTexts(_texts, _metadatas, _embeddings, _dbConfig) {\n\t\tthrow new Error(\"the Langchain vectorstore implementation you are using forgot to override this, please report a bug\");\n\t}\n\t/**\n\t* Creates a `VectorStore` instance from an array of documents, using the specified\n\t* embeddings and database configuration.\n\t*\n\t* Subclasses must implement this method to define how documents are embedded\n\t* and stored. Throws an error if not overridden.\n\t*\n\t* @param _docs - Array of `DocumentInterface` instances representing the documents to be stored.\n\t* @param _embeddings - Instance of `EmbeddingsInterface` to embed the documents.\n\t* @param _dbConfig - Database configuration settings.\n\t* @returns A promise that resolves to a new `VectorStore` instance.\n\t* @throws {Error} Throws an error if this method is not overridden by a subclass.\n\t*/\n\tstatic fromDocuments(_docs, _embeddings, _dbConfig) {\n\t\tthrow new Error(\"the Langchain vectorstore implementation you are using forgot to override this, please report a bug\");\n\t}\n\t/**\n\t* Creates a `VectorStoreRetriever` instance with flexible configuration options.\n\t*\n\t* @param kOrFields\n\t* - If a number is provided, it sets the `k` parameter (number of items to retrieve).\n\t* - If an object is provided, it should contain various configuration options.\n\t* @param filter\n\t* - Optional filter criteria to limit the items retrieved based on the specified filter type.\n\t* @param callbacks\n\t* - Optional callbacks that may be triggered at specific stages of the retrieval process.\n\t* @param tags\n\t* - Tags to categorize or label the `VectorStoreRetriever`. Defaults to an empty array if not provided.\n\t* @param metadata\n\t* - Additional metadata as key-value pairs to add contextual information for the retrieval process.\n\t* @param verbose\n\t* - If `true`, enables detailed logging for the retrieval process. Defaults to `false`.\n\t*\n\t* @returns\n\t* - A configured `VectorStoreRetriever` instance based on the provided parameters.\n\t*\n\t* @example\n\t* Basic usage with a `k` value:\n\t* ```typescript\n\t* const retriever = myVectorStore.asRetriever(5);\n\t* ```\n\t*\n\t* Usage with a configuration object:\n\t* ```typescript\n\t* const retriever = myVectorStore.asRetriever({\n\t* k: 10,\n\t* filter: myFilter,\n\t* tags: ['example', 'test'],\n\t* verbose: true,\n\t* searchType: 'mmr',\n\t* searchKwargs: { alpha: 0.5 },\n\t* });\n\t* ```\n\t*/\n\tasRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) {\n\t\tif (typeof kOrFields === \"number\") return new VectorStoreRetriever({\n\t\t\tvectorStore: this,\n\t\t\tk: kOrFields,\n\t\t\tfilter,\n\t\t\ttags: [...tags ?? [], this._vectorstoreType()],\n\t\t\tmetadata,\n\t\t\tverbose,\n\t\t\tcallbacks\n\t\t});\n\t\telse {\n\t\t\tconst params = {\n\t\t\t\tvectorStore: this,\n\t\t\t\tk: kOrFields?.k,\n\t\t\t\tfilter: kOrFields?.filter,\n\t\t\t\ttags: [...kOrFields?.tags ?? [], this._vectorstoreType()],\n\t\t\t\tmetadata: kOrFields?.metadata,\n\t\t\t\tverbose: kOrFields?.verbose,\n\t\t\t\tcallbacks: kOrFields?.callbacks,\n\t\t\t\tsearchType: kOrFields?.searchType\n\t\t\t};\n\t\t\tif (kOrFields?.searchType === \"mmr\") return new VectorStoreRetriever({\n\t\t\t\t...params,\n\t\t\t\tsearchKwargs: kOrFields.searchKwargs\n\t\t\t});\n\t\t\treturn new VectorStoreRetriever({ ...params });\n\t\t}\n\t}\n};\n/**\n* Abstract class extending `VectorStore` that defines a contract for saving\n* and loading vector store instances.\n*\n* The `SaveableVectorStore` class allows vector store implementations to\n* persist their data and retrieve it when needed.The format for saving and\n* loading data is left to the implementing subclass.\n*\n* Subclasses must implement the `save` method to handle their custom\n* serialization logic, while the `load` method enables reconstruction of a\n* vector store from saved data, requiring compatible embeddings through the\n* `EmbeddingsInterface`.\n*\n* @abstract\n* @extends VectorStore\n*/\nvar SaveableVectorStore = class extends VectorStore {\n\t/**\n\t* Loads a vector store instance from the specified directory, using the\n\t* provided embeddings to ensure compatibility.\n\t*\n\t* This static method reconstructs a `SaveableVectorStore` from previously\n\t* saved data. Implementations should interpret the saved data format to\n\t* recreate the vector store instance.\n\t*\n\t* @param _directory - The directory path from which the vector store\n\t* data will be loaded.\n\t* @param _embeddings - An instance of `EmbeddingsInterface` to align\n\t* the embeddings with the loaded vector data.\n\t* @returns A promise that resolves to a `SaveableVectorStore` instance\n\t* constructed from the saved data.\n\t*/\n\tstatic load(_directory, _embeddings) {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n};\n\n//#endregion\nexport { SaveableVectorStore, VectorStore, VectorStoreRetriever, vectorstores_exports };\n//# sourceMappingURL=vectorstores.js.map","\n\n//#region src/utils/js-sha256/hash.ts\nvar HEX_CHARS = \"0123456789abcdef\".split(\"\");\nvar EXTRA = [\n\t-2147483648,\n\t8388608,\n\t32768,\n\t128\n];\nvar SHIFT = [\n\t24,\n\t16,\n\t8,\n\t0\n];\nvar K = [\n\t1116352408,\n\t1899447441,\n\t3049323471,\n\t3921009573,\n\t961987163,\n\t1508970993,\n\t2453635748,\n\t2870763221,\n\t3624381080,\n\t310598401,\n\t607225278,\n\t1426881987,\n\t1925078388,\n\t2162078206,\n\t2614888103,\n\t3248222580,\n\t3835390401,\n\t4022224774,\n\t264347078,\n\t604807628,\n\t770255983,\n\t1249150122,\n\t1555081692,\n\t1996064986,\n\t2554220882,\n\t2821834349,\n\t2952996808,\n\t3210313671,\n\t3336571891,\n\t3584528711,\n\t113926993,\n\t338241895,\n\t666307205,\n\t773529912,\n\t1294757372,\n\t1396182291,\n\t1695183700,\n\t1986661051,\n\t2177026350,\n\t2456956037,\n\t2730485921,\n\t2820302411,\n\t3259730800,\n\t3345764771,\n\t3516065817,\n\t3600352804,\n\t4094571909,\n\t275423344,\n\t430227734,\n\t506948616,\n\t659060556,\n\t883997877,\n\t958139571,\n\t1322822218,\n\t1537002063,\n\t1747873779,\n\t1955562222,\n\t2024104815,\n\t2227730452,\n\t2361852424,\n\t2428436474,\n\t2756734187,\n\t3204031479,\n\t3329325298\n];\nvar blocks = [];\nfunction Sha256(is224, sharedMemory) {\n\tif (sharedMemory) {\n\t\tblocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n\t\tthis.blocks = blocks;\n\t} else this.blocks = [\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0\n\t];\n\tif (is224) {\n\t\tthis.h0 = 3238371032;\n\t\tthis.h1 = 914150663;\n\t\tthis.h2 = 812702999;\n\t\tthis.h3 = 4144912697;\n\t\tthis.h4 = 4290775857;\n\t\tthis.h5 = 1750603025;\n\t\tthis.h6 = 1694076839;\n\t\tthis.h7 = 3204075428;\n\t} else {\n\t\tthis.h0 = 1779033703;\n\t\tthis.h1 = 3144134277;\n\t\tthis.h2 = 1013904242;\n\t\tthis.h3 = 2773480762;\n\t\tthis.h4 = 1359893119;\n\t\tthis.h5 = 2600822924;\n\t\tthis.h6 = 528734635;\n\t\tthis.h7 = 1541459225;\n\t}\n\tthis.block = this.start = this.bytes = this.hBytes = 0;\n\tthis.finalized = this.hashed = false;\n\tthis.first = true;\n\tthis.is224 = is224;\n}\nSha256.prototype.update = function(message) {\n\tif (this.finalized) return;\n\tvar notString, type = typeof message;\n\tif (type !== \"string\") {\n\t\tif (type === \"object\") {\n\t\t\tif (message === null) throw new Error(ERROR);\n\t\t\telse if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message);\n\t\t\telse if (!Array.isArray(message)) {\n\t\t\t\tif (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) throw new Error(ERROR);\n\t\t\t}\n\t\t} else throw new Error(ERROR);\n\t\tnotString = true;\n\t}\n\tvar code, index = 0, i, length = message.length, blocks$1 = this.blocks;\n\twhile (index < length) {\n\t\tif (this.hashed) {\n\t\t\tthis.hashed = false;\n\t\t\tblocks$1[0] = this.block;\n\t\t\tthis.block = blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0;\n\t\t}\n\t\tif (notString) for (i = this.start; index < length && i < 64; ++index) blocks$1[i >>> 2] |= message[index] << SHIFT[i++ & 3];\n\t\telse for (i = this.start; index < length && i < 64; ++index) {\n\t\t\tcode = message.charCodeAt(index);\n\t\t\tif (code < 128) blocks$1[i >>> 2] |= code << SHIFT[i++ & 3];\n\t\t\telse if (code < 2048) {\n\t\t\t\tblocks$1[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3];\n\t\t\t\tblocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3];\n\t\t\t} else if (code < 55296 || code >= 57344) {\n\t\t\t\tblocks$1[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3];\n\t\t\t\tblocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3];\n\t\t\t\tblocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3];\n\t\t\t} else {\n\t\t\t\tcode = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023);\n\t\t\t\tblocks$1[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3];\n\t\t\t\tblocks$1[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3];\n\t\t\t\tblocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3];\n\t\t\t\tblocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3];\n\t\t\t}\n\t\t}\n\t\tthis.lastByteIndex = i;\n\t\tthis.bytes += i - this.start;\n\t\tif (i >= 64) {\n\t\t\tthis.block = blocks$1[16];\n\t\t\tthis.start = i - 64;\n\t\t\tthis.hash();\n\t\t\tthis.hashed = true;\n\t\t} else this.start = i;\n\t}\n\tif (this.bytes > 4294967295) {\n\t\tthis.hBytes += this.bytes / 4294967296 << 0;\n\t\tthis.bytes = this.bytes % 4294967296;\n\t}\n\treturn this;\n};\nSha256.prototype.finalize = function() {\n\tif (this.finalized) return;\n\tthis.finalized = true;\n\tvar blocks$1 = this.blocks, i = this.lastByteIndex;\n\tblocks$1[16] = this.block;\n\tblocks$1[i >>> 2] |= EXTRA[i & 3];\n\tthis.block = blocks$1[16];\n\tif (i >= 56) {\n\t\tif (!this.hashed) this.hash();\n\t\tblocks$1[0] = this.block;\n\t\tblocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0;\n\t}\n\tblocks$1[14] = this.hBytes << 3 | this.bytes >>> 29;\n\tblocks$1[15] = this.bytes << 3;\n\tthis.hash();\n};\nSha256.prototype.hash = function() {\n\tvar a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks$1 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc;\n\tfor (j = 16; j < 64; ++j) {\n\t\tt1 = blocks$1[j - 15];\n\t\ts0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3;\n\t\tt1 = blocks$1[j - 2];\n\t\ts1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;\n\t\tblocks$1[j] = blocks$1[j - 16] + s0 + blocks$1[j - 7] + s1 << 0;\n\t}\n\tbc = b & c;\n\tfor (j = 0; j < 64; j += 4) {\n\t\tif (this.first) {\n\t\t\tif (this.is224) {\n\t\t\t\tab = 300032;\n\t\t\t\tt1 = blocks$1[0] - 1413257819;\n\t\t\t\th = t1 - 150054599 << 0;\n\t\t\t\td = t1 + 24177077 << 0;\n\t\t\t} else {\n\t\t\t\tab = 704751109;\n\t\t\t\tt1 = blocks$1[0] - 210244248;\n\t\t\t\th = t1 - 1521486534 << 0;\n\t\t\t\td = t1 + 143694565 << 0;\n\t\t\t}\n\t\t\tthis.first = false;\n\t\t} else {\n\t\t\ts0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);\n\t\t\ts1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);\n\t\t\tab = a & b;\n\t\t\tmaj = ab ^ a & c ^ bc;\n\t\t\tch = e & f ^ ~e & g;\n\t\t\tt1 = h + s1 + ch + K[j] + blocks$1[j];\n\t\t\tt2 = s0 + maj;\n\t\t\th = d + t1 << 0;\n\t\t\td = t1 + t2 << 0;\n\t\t}\n\t\ts0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10);\n\t\ts1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7);\n\t\tda = d & a;\n\t\tmaj = da ^ d & b ^ ab;\n\t\tch = g & h ^ ~g & e;\n\t\tt1 = f + s1 + ch + K[j + 1] + blocks$1[j + 1];\n\t\tt2 = s0 + maj;\n\t\tg = c + t1 << 0;\n\t\tc = t1 + t2 << 0;\n\t\ts0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10);\n\t\ts1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7);\n\t\tcd = c & d;\n\t\tmaj = cd ^ c & a ^ da;\n\t\tch = f & g ^ ~f & h;\n\t\tt1 = e + s1 + ch + K[j + 2] + blocks$1[j + 2];\n\t\tt2 = s0 + maj;\n\t\tf = b + t1 << 0;\n\t\tb = t1 + t2 << 0;\n\t\ts0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10);\n\t\ts1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7);\n\t\tbc = b & c;\n\t\tmaj = bc ^ b & d ^ cd;\n\t\tch = f & g ^ ~f & h;\n\t\tt1 = e + s1 + ch + K[j + 3] + blocks$1[j + 3];\n\t\tt2 = s0 + maj;\n\t\te = a + t1 << 0;\n\t\ta = t1 + t2 << 0;\n\t\tthis.chromeBugWorkAround = true;\n\t}\n\tthis.h0 = this.h0 + a << 0;\n\tthis.h1 = this.h1 + b << 0;\n\tthis.h2 = this.h2 + c << 0;\n\tthis.h3 = this.h3 + d << 0;\n\tthis.h4 = this.h4 + e << 0;\n\tthis.h5 = this.h5 + f << 0;\n\tthis.h6 = this.h6 + g << 0;\n\tthis.h7 = this.h7 + h << 0;\n};\nSha256.prototype.hex = function() {\n\tthis.finalize();\n\tvar h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;\n\tvar hex = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15];\n\tif (!this.is224) hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15];\n\treturn hex;\n};\nSha256.prototype.toString = Sha256.prototype.hex;\nSha256.prototype.digest = function() {\n\tthis.finalize();\n\tvar h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;\n\tvar arr = [\n\t\th0 >>> 24 & 255,\n\t\th0 >>> 16 & 255,\n\t\th0 >>> 8 & 255,\n\t\th0 & 255,\n\t\th1 >>> 24 & 255,\n\t\th1 >>> 16 & 255,\n\t\th1 >>> 8 & 255,\n\t\th1 & 255,\n\t\th2 >>> 24 & 255,\n\t\th2 >>> 16 & 255,\n\t\th2 >>> 8 & 255,\n\t\th2 & 255,\n\t\th3 >>> 24 & 255,\n\t\th3 >>> 16 & 255,\n\t\th3 >>> 8 & 255,\n\t\th3 & 255,\n\t\th4 >>> 24 & 255,\n\t\th4 >>> 16 & 255,\n\t\th4 >>> 8 & 255,\n\t\th4 & 255,\n\t\th5 >>> 24 & 255,\n\t\th5 >>> 16 & 255,\n\t\th5 >>> 8 & 255,\n\t\th5 & 255,\n\t\th6 >>> 24 & 255,\n\t\th6 >>> 16 & 255,\n\t\th6 >>> 8 & 255,\n\t\th6 & 255\n\t];\n\tif (!this.is224) arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255);\n\treturn arr;\n};\nSha256.prototype.array = Sha256.prototype.digest;\nSha256.prototype.arrayBuffer = function() {\n\tthis.finalize();\n\tvar buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32);\n\tvar dataView = new DataView(buffer);\n\tdataView.setUint32(0, this.h0);\n\tdataView.setUint32(4, this.h1);\n\tdataView.setUint32(8, this.h2);\n\tdataView.setUint32(12, this.h3);\n\tdataView.setUint32(16, this.h4);\n\tdataView.setUint32(20, this.h5);\n\tdataView.setUint32(24, this.h6);\n\tif (!this.is224) dataView.setUint32(28, this.h7);\n\treturn buffer;\n};\nconst sha256 = (...strings) => {\n\treturn new Sha256(false, true).update(strings.join(\"\")).hex();\n};\n\n//#endregion\nexport { sha256 };\n//# sourceMappingURL=hash.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { sha256 } from \"./js-sha256/hash.js\";\n\n//#region src/utils/hash.ts\nvar hash_exports = {};\n__export(hash_exports, { sha256: () => sha256 });\n\n//#endregion\nexport { hash_exports, sha256 };\n//# sourceMappingURL=hash.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { mapStoredMessageToChatMessage } from \"../messages/utils.js\";\nimport { sha256 } from \"../utils/js-sha256/hash.js\";\nimport \"../utils/hash.js\";\n\n//#region src/caches/base.ts\nvar base_exports = {};\n__export(base_exports, {\n\tBaseCache: () => BaseCache,\n\tInMemoryCache: () => InMemoryCache,\n\tdefaultHashKeyEncoder: () => defaultHashKeyEncoder,\n\tdeserializeStoredGeneration: () => deserializeStoredGeneration,\n\tserializeGeneration: () => serializeGeneration\n});\nconst defaultHashKeyEncoder = (...strings) => sha256(strings.join(\"_\"));\nfunction deserializeStoredGeneration(storedGeneration) {\n\tif (storedGeneration.message !== void 0) return {\n\t\ttext: storedGeneration.text,\n\t\tmessage: mapStoredMessageToChatMessage(storedGeneration.message)\n\t};\n\telse return { text: storedGeneration.text };\n}\nfunction serializeGeneration(generation) {\n\tconst serializedValue = { text: generation.text };\n\tif (generation.message !== void 0) serializedValue.message = generation.message.toDict();\n\treturn serializedValue;\n}\n/**\n* Base class for all caches. All caches should extend this class.\n*/\nvar BaseCache = class {\n\tkeyEncoder = defaultHashKeyEncoder;\n\t/**\n\t* Sets a custom key encoder function for the cache.\n\t* This function should take a prompt and an LLM key and return a string\n\t* that will be used as the cache key.\n\t* @param keyEncoderFn The custom key encoder function.\n\t*/\n\tmakeDefaultKeyEncoder(keyEncoderFn) {\n\t\tthis.keyEncoder = keyEncoderFn;\n\t}\n};\nconst GLOBAL_MAP = /* @__PURE__ */ new Map();\n/**\n* A cache for storing LLM generations that stores data in memory.\n*/\nvar InMemoryCache = class InMemoryCache extends BaseCache {\n\tcache;\n\tconstructor(map) {\n\t\tsuper();\n\t\tthis.cache = map ?? /* @__PURE__ */ new Map();\n\t}\n\t/**\n\t* Retrieves data from the cache using a prompt and an LLM key. If the\n\t* data is not found, it returns null.\n\t* @param prompt The prompt used to find the data.\n\t* @param llmKey The LLM key used to find the data.\n\t* @returns The data corresponding to the prompt and LLM key, or null if not found.\n\t*/\n\tlookup(prompt, llmKey) {\n\t\treturn Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null);\n\t}\n\t/**\n\t* Updates the cache with new data using a prompt and an LLM key.\n\t* @param prompt The prompt used to store the data.\n\t* @param llmKey The LLM key used to store the data.\n\t* @param value The data to be stored.\n\t*/\n\tasync update(prompt, llmKey, value) {\n\t\tthis.cache.set(this.keyEncoder(prompt, llmKey), value);\n\t}\n\t/**\n\t* Returns a global instance of InMemoryCache using a predefined global\n\t* map as the initial cache.\n\t* @returns A global instance of InMemoryCache.\n\t*/\n\tstatic global() {\n\t\treturn new InMemoryCache(GLOBAL_MAP);\n\t}\n};\n\n//#endregion\nexport { BaseCache, InMemoryCache, base_exports, defaultHashKeyEncoder, deserializeStoredGeneration, serializeGeneration };\n//# sourceMappingURL=base.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\n\n//#region src/document_loaders/base.ts\nvar base_exports = {};\n__export(base_exports, { BaseDocumentLoader: () => BaseDocumentLoader });\n/**\n* Abstract class that provides a default implementation for the\n* loadAndSplit() method from the DocumentLoader interface. The load()\n* method is left abstract and needs to be implemented by subclasses.\n*/\nvar BaseDocumentLoader = class {};\n\n//#endregion\nexport { BaseDocumentLoader, base_exports };\n//# sourceMappingURL=base.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BaseDocumentLoader } from \"./base.js\";\nimport { Client } from \"langsmith\";\n\n//#region src/document_loaders/langsmith.ts\nvar langsmith_exports = {};\n__export(langsmith_exports, { LangSmithLoader: () => LangSmithLoader });\n/**\n* Document loader integration with LangSmith.\n*\n* ## [Constructor args](https://api.js.langchain.com/interfaces/_langchain_core.document_loaders_langsmith.LangSmithLoaderFields.html)\n*\n*
\n* Load\n*\n* ```typescript\n* import { LangSmithLoader } from '@langchain/core/document_loaders/langsmith';\n* import { Client } from 'langsmith';\n*\n* const langSmithClient = new Client({\n* apiKey: process.env.LANGSMITH_API_KEY,\n* })\n*\n* const loader = new LangSmithLoader({\n* datasetId: \"9a3b36f7-b308-40a5-9b46-6613853b6330\",\n* limit: 1,\n* });\n*\n* const docs = await loader.load();\n* ```\n*\n* ```txt\n* [\n* {\n* pageContent: '{\\n \"input_key_str\": \"string\",\\n \"input_key_bool\": true\\n}',\n* metadata: {\n* id: '8523d9e9-c123-4b23-9b46-21021nds289e',\n* created_at: '2024-08-19T17:09:14.806441+00:00',\n* modified_at: '2024-08-19T17:09:14.806441+00:00',\n* name: '#8517 @ brace-test-dataset',\n* dataset_id: '9a3b36f7-b308-40a5-9b46-6613853b6330',\n* source_run_id: null,\n* metadata: [Object],\n* inputs: [Object],\n* outputs: [Object]\n* }\n* }\n* ]\n* ```\n*
\n*/\nvar LangSmithLoader = class extends BaseDocumentLoader {\n\tdatasetId;\n\tdatasetName;\n\texampleIds;\n\tasOf;\n\tsplits;\n\tinlineS3Urls;\n\toffset;\n\tlimit;\n\tmetadata;\n\tfilter;\n\tcontentKey;\n\tformatContent;\n\tclient;\n\tconstructor(fields) {\n\t\tsuper();\n\t\tif (fields.client && fields.clientConfig) throw new Error(\"client and clientConfig cannot both be provided.\");\n\t\tthis.client = fields.client ?? new Client(fields?.clientConfig);\n\t\tthis.contentKey = fields.contentKey ? fields.contentKey.split(\".\") : [];\n\t\tthis.formatContent = fields.formatContent ?? _stringify;\n\t\tthis.datasetId = fields.datasetId;\n\t\tthis.datasetName = fields.datasetName;\n\t\tthis.exampleIds = fields.exampleIds;\n\t\tthis.asOf = fields.asOf;\n\t\tthis.splits = fields.splits;\n\t\tthis.inlineS3Urls = fields.inlineS3Urls;\n\t\tthis.offset = fields.offset;\n\t\tthis.limit = fields.limit;\n\t\tthis.metadata = fields.metadata;\n\t\tthis.filter = fields.filter;\n\t}\n\tasync load() {\n\t\tconst documents = [];\n\t\tfor await (const example of this.client.listExamples({\n\t\t\tdatasetId: this.datasetId,\n\t\t\tdatasetName: this.datasetName,\n\t\t\texampleIds: this.exampleIds,\n\t\t\tasOf: this.asOf,\n\t\t\tsplits: this.splits,\n\t\t\tinlineS3Urls: this.inlineS3Urls,\n\t\t\toffset: this.offset,\n\t\t\tlimit: this.limit,\n\t\t\tmetadata: this.metadata,\n\t\t\tfilter: this.filter\n\t\t})) {\n\t\t\tlet content = example.inputs;\n\t\t\tfor (const key of this.contentKey) content = content[key];\n\t\t\tconst contentStr = this.formatContent(content);\n\t\t\tconst metadata = example;\n\t\t\t[\"created_at\", \"modified_at\"].forEach((k) => {\n\t\t\t\tif (k in metadata) {\n\t\t\t\t\tif (typeof metadata[k] === \"object\") metadata[k] = metadata[k].toString();\n\t\t\t\t}\n\t\t\t});\n\t\t\tdocuments.push({\n\t\t\t\tpageContent: contentStr,\n\t\t\t\tmetadata\n\t\t\t});\n\t\t}\n\t\treturn documents;\n\t}\n};\nfunction _stringify(x) {\n\tif (typeof x === \"string\") return x;\n\telse try {\n\t\treturn JSON.stringify(x, null, 2);\n\t} catch {\n\t\treturn String(x);\n\t}\n}\n\n//#endregion\nexport { LangSmithLoader, langsmith_exports };\n//# sourceMappingURL=langsmith.js.map","//#region src/documents/document.ts\n/**\n* Interface for interacting with a document.\n*/\nvar Document = class {\n\tpageContent;\n\tmetadata;\n\t/**\n\t* An optional identifier for the document.\n\t*\n\t* Ideally this should be unique across the document collection and formatted\n\t* as a UUID, but this will not be enforced.\n\t*/\n\tid;\n\tconstructor(fields) {\n\t\tthis.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : \"\";\n\t\tthis.metadata = fields.metadata ?? {};\n\t\tthis.id = fields.id;\n\t}\n};\n\n//#endregion\nexport { Document };\n//# sourceMappingURL=document.js.map","import { Runnable } from \"../runnables/base.js\";\n\n//#region src/documents/transformers.ts\n/**\n* Abstract base class for document transformation systems.\n*\n* A document transformation system takes an array of Documents and returns an\n* array of transformed Documents. These arrays do not necessarily have to have\n* the same length.\n*\n* One example of this is a text splitter that splits a large document into\n* many smaller documents.\n*/\nvar BaseDocumentTransformer = class extends Runnable {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"documents\",\n\t\t\"transformers\"\n\t];\n\t/**\n\t* Method to invoke the document transformation. This method calls the\n\t* transformDocuments method with the provided input.\n\t* @param input The input documents to be transformed.\n\t* @param _options Optional configuration object to customize the behavior of callbacks.\n\t* @returns A Promise that resolves to the transformed documents.\n\t*/\n\tinvoke(input, _options) {\n\t\treturn this.transformDocuments(input);\n\t}\n};\n/**\n* Class for document transformers that return exactly one transformed document\n* for each input document.\n*/\nvar MappingDocumentTransformer = class extends BaseDocumentTransformer {\n\tasync transformDocuments(documents) {\n\t\tconst newDocuments = [];\n\t\tfor (const document of documents) {\n\t\t\tconst transformedDocument = await this._transformDocument(document);\n\t\t\tnewDocuments.push(transformedDocument);\n\t\t}\n\t\treturn newDocuments;\n\t}\n};\n\n//#endregion\nexport { BaseDocumentTransformer, MappingDocumentTransformer };\n//# sourceMappingURL=transformers.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { Document } from \"./document.js\";\nimport { BaseDocumentTransformer, MappingDocumentTransformer } from \"./transformers.js\";\n\n//#region src/documents/index.ts\nvar documents_exports = {};\n__export(documents_exports, {\n\tBaseDocumentTransformer: () => BaseDocumentTransformer,\n\tDocument: () => Document,\n\tMappingDocumentTransformer: () => MappingDocumentTransformer\n});\n\n//#endregion\nexport { BaseDocumentTransformer, Document, MappingDocumentTransformer, documents_exports };\n//# sourceMappingURL=index.js.map","import { Serializable } from \"../load/serializable.js\";\n\n//#region src/example_selectors/base.ts\n/**\n* Base class for example selectors.\n*/\nvar BaseExampleSelector = class extends Serializable {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"example_selectors\",\n\t\t\"base\"\n\t];\n};\n\n//#endregion\nexport { BaseExampleSelector };\n//# sourceMappingURL=base.js.map","//#region src/example_selectors/conditional.ts\n/**\n* Abstract class that defines the interface for selecting a prompt for a\n* given language model.\n*/\nvar BasePromptSelector = class {\n\t/**\n\t* Asynchronous version of `getPrompt` that also accepts an options object\n\t* for partial variables.\n\t* @param llm The language model for which to get a prompt.\n\t* @param options Optional object for partial variables.\n\t* @returns A Promise that resolves to a prompt template.\n\t*/\n\tasync getPromptAsync(llm, options) {\n\t\tconst prompt = this.getPrompt(llm);\n\t\treturn prompt.partial(options?.partialVariables ?? {});\n\t}\n};\n/**\n* Concrete implementation of `BasePromptSelector` that selects a prompt\n* based on a set of conditions. It has a default prompt that it returns\n* if none of the conditions are met.\n*/\nvar ConditionalPromptSelector = class extends BasePromptSelector {\n\tdefaultPrompt;\n\tconditionals;\n\tconstructor(default_prompt, conditionals = []) {\n\t\tsuper();\n\t\tthis.defaultPrompt = default_prompt;\n\t\tthis.conditionals = conditionals;\n\t}\n\t/**\n\t* Method that selects a prompt based on a set of conditions. If none of\n\t* the conditions are met, it returns the default prompt.\n\t* @param llm The language model for which to get a prompt.\n\t* @returns A prompt template.\n\t*/\n\tgetPrompt(llm) {\n\t\tfor (const [condition, prompt] of this.conditionals) if (condition(llm)) return prompt;\n\t\treturn this.defaultPrompt;\n\t}\n};\n/**\n* Type guard function that checks if a given language model is of type\n* `BaseLLM`.\n*/\nfunction isLLM(llm) {\n\treturn llm._modelType() === \"base_llm\";\n}\n/**\n* Type guard function that checks if a given language model is of type\n* `BaseChatModel`.\n*/\nfunction isChatModel(llm) {\n\treturn llm._modelType() === \"base_chat_model\";\n}\n\n//#endregion\nexport { BasePromptSelector, ConditionalPromptSelector, isChatModel, isLLM };\n//# sourceMappingURL=conditional.js.map","import { BaseExampleSelector } from \"./base.js\";\n\n//#region src/example_selectors/length_based.ts\n/**\n* Calculates the length of a text based on the number of words and lines.\n*/\nfunction getLengthBased(text) {\n\treturn text.split(/\\n| /).length;\n}\n/**\n* A specialized example selector that selects examples based on their\n* length, ensuring that the total length of the selected examples does\n* not exceed a specified maximum length.\n* @example\n* ```typescript\n* const exampleSelector = new LengthBasedExampleSelector(\n* [\n* { input: \"happy\", output: \"sad\" },\n* { input: \"tall\", output: \"short\" },\n* { input: \"energetic\", output: \"lethargic\" },\n* { input: \"sunny\", output: \"gloomy\" },\n* { input: \"windy\", output: \"calm\" },\n* ],\n* {\n* examplePrompt: new PromptTemplate({\n* inputVariables: [\"input\", \"output\"],\n* template: \"Input: {input}\\nOutput: {output}\",\n* }),\n* maxLength: 25,\n* },\n* );\n* const dynamicPrompt = new FewShotPromptTemplate({\n* exampleSelector,\n* examplePrompt: new PromptTemplate({\n* inputVariables: [\"input\", \"output\"],\n* template: \"Input: {input}\\nOutput: {output}\",\n* }),\n* prefix: \"Give the antonym of every input\",\n* suffix: \"Input: {adjective}\\nOutput:\",\n* inputVariables: [\"adjective\"],\n* });\n* console.log(dynamicPrompt.format({ adjective: \"big\" }));\n* console.log(\n* dynamicPrompt.format({\n* adjective:\n* \"big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else\",\n* }),\n* );\n* ```\n*/\nvar LengthBasedExampleSelector = class LengthBasedExampleSelector extends BaseExampleSelector {\n\texamples = [];\n\texamplePrompt;\n\tgetTextLength = getLengthBased;\n\tmaxLength = 2048;\n\texampleTextLengths = [];\n\tconstructor(data) {\n\t\tsuper(data);\n\t\tthis.examplePrompt = data.examplePrompt;\n\t\tthis.maxLength = data.maxLength ?? 2048;\n\t\tthis.getTextLength = data.getTextLength ?? getLengthBased;\n\t}\n\t/**\n\t* Adds an example to the list of examples and calculates its length.\n\t* @param example The example to be added.\n\t* @returns Promise that resolves when the example has been added and its length calculated.\n\t*/\n\tasync addExample(example) {\n\t\tthis.examples.push(example);\n\t\tconst stringExample = await this.examplePrompt.format(example);\n\t\tthis.exampleTextLengths.push(this.getTextLength(stringExample));\n\t}\n\t/**\n\t* Calculates the lengths of the examples.\n\t* @param v Array of lengths of the examples.\n\t* @param values Instance of LengthBasedExampleSelector.\n\t* @returns Promise that resolves with an array of lengths of the examples.\n\t*/\n\tasync calculateExampleTextLengths(v, values) {\n\t\tif (v.length > 0) return v;\n\t\tconst { examples, examplePrompt } = values;\n\t\tconst stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg)));\n\t\treturn stringExamples.map((eg) => this.getTextLength(eg));\n\t}\n\t/**\n\t* Selects examples until the total length of the selected examples\n\t* reaches the maxLength.\n\t* @param inputVariables The input variables for the examples.\n\t* @returns Promise that resolves with an array of selected examples.\n\t*/\n\tasync selectExamples(inputVariables) {\n\t\tconst inputs = Object.values(inputVariables).join(\" \");\n\t\tlet remainingLength = this.maxLength - this.getTextLength(inputs);\n\t\tlet i = 0;\n\t\tconst examples = [];\n\t\twhile (remainingLength > 0 && i < this.examples.length) {\n\t\t\tconst newLength = remainingLength - this.exampleTextLengths[i];\n\t\t\tif (newLength < 0) break;\n\t\t\telse {\n\t\t\t\texamples.push(this.examples[i]);\n\t\t\t\tremainingLength = newLength;\n\t\t\t}\n\t\t\ti += 1;\n\t\t}\n\t\treturn examples;\n\t}\n\t/**\n\t* Creates a new instance of LengthBasedExampleSelector and adds a list of\n\t* examples to it.\n\t* @param examples Array of examples to be added.\n\t* @param args Input parameters for the LengthBasedExampleSelector.\n\t* @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added.\n\t*/\n\tstatic async fromExamples(examples, args) {\n\t\tconst selector = new LengthBasedExampleSelector(args);\n\t\tawait Promise.all(examples.map((eg) => selector.addExample(eg)));\n\t\treturn selector;\n\t}\n};\n\n//#endregion\nexport { LengthBasedExampleSelector };\n//# sourceMappingURL=length_based.js.map","import { Document } from \"../documents/document.js\";\nimport { BaseExampleSelector } from \"./base.js\";\n\n//#region src/example_selectors/semantic_similarity.ts\nfunction sortedValues(values) {\n\treturn Object.keys(values).sort().map((key) => values[key]);\n}\n/**\n* Class that selects examples based on semantic similarity. It extends\n* the BaseExampleSelector class.\n* @example\n* ```typescript\n* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n* [\n* { input: \"happy\", output: \"sad\" },\n* { input: \"tall\", output: \"short\" },\n* { input: \"energetic\", output: \"lethargic\" },\n* { input: \"sunny\", output: \"gloomy\" },\n* { input: \"windy\", output: \"calm\" },\n* ],\n* new OpenAIEmbeddings(),\n* HNSWLib,\n* { k: 1 },\n* );\n* const dynamicPrompt = new FewShotPromptTemplate({\n* exampleSelector,\n* examplePrompt: PromptTemplate.fromTemplate(\n* \"Input: {input}\\nOutput: {output}\",\n* ),\n* prefix: \"Give the antonym of every input\",\n* suffix: \"Input: {adjective}\\nOutput:\",\n* inputVariables: [\"adjective\"],\n* });\n* console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n* ```\n*/\nvar SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector extends BaseExampleSelector {\n\tvectorStoreRetriever;\n\texampleKeys;\n\tinputKeys;\n\tconstructor(data) {\n\t\tsuper(data);\n\t\tthis.exampleKeys = data.exampleKeys;\n\t\tthis.inputKeys = data.inputKeys;\n\t\tif (data.vectorStore !== void 0) this.vectorStoreRetriever = data.vectorStore.asRetriever({\n\t\t\tk: data.k ?? 4,\n\t\t\tfilter: data.filter\n\t\t});\n\t\telse if (data.vectorStoreRetriever) this.vectorStoreRetriever = data.vectorStoreRetriever;\n\t\telse throw new Error(`You must specify one of \"vectorStore\" and \"vectorStoreRetriever\".`);\n\t}\n\t/**\n\t* Method that adds a new example to the vectorStore. The example is\n\t* converted to a string and added to the vectorStore as a document.\n\t* @param example The example to be added to the vectorStore.\n\t* @returns Promise that resolves when the example has been added to the vectorStore.\n\t*/\n\tasync addExample(example) {\n\t\tconst inputKeys = this.inputKeys ?? Object.keys(example);\n\t\tconst stringExample = sortedValues(inputKeys.reduce((acc, key) => ({\n\t\t\t...acc,\n\t\t\t[key]: example[key]\n\t\t}), {})).join(\" \");\n\t\tawait this.vectorStoreRetriever.addDocuments([new Document({\n\t\t\tpageContent: stringExample,\n\t\t\tmetadata: example\n\t\t})]);\n\t}\n\t/**\n\t* Method that selects which examples to use based on semantic similarity.\n\t* It performs a similarity search in the vectorStore using the input\n\t* variables and returns the examples with the highest similarity.\n\t* @param inputVariables The input variables used for the similarity search.\n\t* @returns Promise that resolves with an array of the selected examples.\n\t*/\n\tasync selectExamples(inputVariables) {\n\t\tconst inputKeys = this.inputKeys ?? Object.keys(inputVariables);\n\t\tconst query = sortedValues(inputKeys.reduce((acc, key) => ({\n\t\t\t...acc,\n\t\t\t[key]: inputVariables[key]\n\t\t}), {})).join(\" \");\n\t\tconst exampleDocs = await this.vectorStoreRetriever.invoke(query);\n\t\tconst examples = exampleDocs.map((doc) => doc.metadata);\n\t\tif (this.exampleKeys) return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({\n\t\t\t...acc,\n\t\t\t[key]: example[key]\n\t\t}), {}));\n\t\treturn examples;\n\t}\n\t/**\n\t* Static method that creates a new instance of\n\t* SemanticSimilarityExampleSelector. It takes a list of examples, an\n\t* instance of Embeddings, a VectorStore class, and an options object as\n\t* parameters. It converts the examples to strings, creates a VectorStore\n\t* from the strings and the embeddings, and returns a new\n\t* SemanticSimilarityExampleSelector with the created VectorStore and the\n\t* options provided.\n\t* @param examples The list of examples to be used.\n\t* @param embeddings The instance of Embeddings to be used.\n\t* @param vectorStoreCls The VectorStore class to be used.\n\t* @param options The options object for the SemanticSimilarityExampleSelector.\n\t* @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector.\n\t*/\n\tstatic async fromExamples(examples, embeddings, vectorStoreCls, options = {}) {\n\t\tconst inputKeys = options.inputKeys ?? null;\n\t\tconst stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({\n\t\t\t...acc,\n\t\t\t[key]: example[key]\n\t\t}), {}) : example).join(\" \"));\n\t\tconst vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options);\n\t\treturn new SemanticSimilarityExampleSelector({\n\t\t\tvectorStore,\n\t\t\tk: options.k ?? 4,\n\t\t\texampleKeys: options.exampleKeys,\n\t\t\tinputKeys: options.inputKeys\n\t\t});\n\t}\n};\n\n//#endregion\nexport { SemanticSimilarityExampleSelector };\n//# sourceMappingURL=semantic_similarity.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BaseExampleSelector } from \"./base.js\";\nimport { BasePromptSelector, ConditionalPromptSelector, isChatModel, isLLM } from \"./conditional.js\";\nimport { LengthBasedExampleSelector } from \"./length_based.js\";\nimport { SemanticSimilarityExampleSelector } from \"./semantic_similarity.js\";\n\n//#region src/example_selectors/index.ts\nvar example_selectors_exports = {};\n__export(example_selectors_exports, {\n\tBaseExampleSelector: () => BaseExampleSelector,\n\tBasePromptSelector: () => BasePromptSelector,\n\tConditionalPromptSelector: () => ConditionalPromptSelector,\n\tLengthBasedExampleSelector: () => LengthBasedExampleSelector,\n\tSemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector,\n\tisChatModel: () => isChatModel,\n\tisLLM: () => isLLM\n});\n\n//#endregion\nexport { BaseExampleSelector, BasePromptSelector, ConditionalPromptSelector, LengthBasedExampleSelector, SemanticSimilarityExampleSelector, example_selectors_exports, isChatModel, isLLM };\n//# sourceMappingURL=index.js.map","import { Serializable } from \"../load/serializable.js\";\n\n//#region src/indexing/record_manager.ts\nconst UUIDV5_NAMESPACE = \"10f90ea3-90a4-4962-bf75-83a0f3c1c62a\";\nvar RecordManager = class extends Serializable {\n\tlc_namespace = [\"langchain\", \"recordmanagers\"];\n};\n\n//#endregion\nexport { RecordManager, UUIDV5_NAMESPACE };\n//# sourceMappingURL=record_manager.js.map","import { sha256 } from \"../utils/js-sha256/hash.js\";\nimport \"../utils/hash.js\";\nimport { Document } from \"../documents/document.js\";\nimport { UUIDV5_NAMESPACE } from \"./record_manager.js\";\nimport { v5 } from \"uuid\";\n\n//#region src/indexing/base.ts\n/**\n* HashedDocument is a Document with hashes calculated.\n* Hashes are calculated based on page content and metadata.\n* It is used for indexing.\n*/\nvar _HashedDocument = class {\n\tuid;\n\thash_;\n\tcontentHash;\n\tmetadataHash;\n\tpageContent;\n\tmetadata;\n\tkeyEncoder = sha256;\n\tconstructor(fields) {\n\t\tthis.uid = fields.uid;\n\t\tthis.pageContent = fields.pageContent;\n\t\tthis.metadata = fields.metadata;\n\t}\n\tmakeDefaultKeyEncoder(keyEncoderFn) {\n\t\tthis.keyEncoder = keyEncoderFn;\n\t}\n\tcalculateHashes() {\n\t\tconst forbiddenKeys = [\n\t\t\t\"hash_\",\n\t\t\t\"content_hash\",\n\t\t\t\"metadata_hash\"\n\t\t];\n\t\tfor (const key of forbiddenKeys) if (key in this.metadata) throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(\", \")}]`);\n\t\tconst contentHash = this._hashStringToUUID(this.pageContent);\n\t\ttry {\n\t\t\tconst metadataHash = this._hashNestedDictToUUID(this.metadata);\n\t\t\tthis.contentHash = contentHash;\n\t\t\tthis.metadataHash = metadataHash;\n\t\t} catch (e) {\n\t\t\tthrow new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`);\n\t\t}\n\t\tthis.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash);\n\t\tif (!this.uid) this.uid = this.hash_;\n\t}\n\ttoDocument() {\n\t\treturn new Document({\n\t\t\tpageContent: this.pageContent,\n\t\t\tmetadata: this.metadata\n\t\t});\n\t}\n\tstatic fromDocument(document, uid) {\n\t\tconst doc = new this({\n\t\t\tpageContent: document.pageContent,\n\t\t\tmetadata: document.metadata,\n\t\t\tuid: uid || document.uid\n\t\t});\n\t\tdoc.calculateHashes();\n\t\treturn doc;\n\t}\n\t_hashStringToUUID(inputString) {\n\t\tconst hash_value = this.keyEncoder(inputString);\n\t\treturn v5(hash_value, UUIDV5_NAMESPACE);\n\t}\n\t_hashNestedDictToUUID(data) {\n\t\tconst serialized_data = JSON.stringify(data, Object.keys(data).sort());\n\t\tconst hash_value = this.keyEncoder(serialized_data);\n\t\treturn v5(hash_value, UUIDV5_NAMESPACE);\n\t}\n};\nfunction _batch(size, iterable) {\n\tconst batches = [];\n\tlet currentBatch = [];\n\titerable.forEach((item) => {\n\t\tcurrentBatch.push(item);\n\t\tif (currentBatch.length >= size) {\n\t\t\tbatches.push(currentBatch);\n\t\t\tcurrentBatch = [];\n\t\t}\n\t});\n\tif (currentBatch.length > 0) batches.push(currentBatch);\n\treturn batches;\n}\nfunction _deduplicateInOrder(hashedDocuments) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst deduplicated = [];\n\tfor (const hashedDoc of hashedDocuments) {\n\t\tif (!hashedDoc.hash_) throw new Error(\"Hashed document does not have a hash\");\n\t\tif (!seen.has(hashedDoc.hash_)) {\n\t\t\tseen.add(hashedDoc.hash_);\n\t\t\tdeduplicated.push(hashedDoc);\n\t\t}\n\t}\n\treturn deduplicated;\n}\nfunction _getSourceIdAssigner(sourceIdKey) {\n\tif (sourceIdKey === null) return (_doc) => null;\n\telse if (typeof sourceIdKey === \"string\") return (doc) => doc.metadata[sourceIdKey];\n\telse if (typeof sourceIdKey === \"function\") return sourceIdKey;\n\telse throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`);\n}\nconst _isBaseDocumentLoader = (arg) => {\n\tif (\"load\" in arg && typeof arg.load === \"function\" && \"loadAndSplit\" in arg && typeof arg.loadAndSplit === \"function\") return true;\n\treturn false;\n};\n/**\n* Index data from the doc source into the vector store.\n*\n* Indexing functionality uses a manager to keep track of which documents\n* are in the vector store.\n*\n* This allows us to keep track of which documents were updated, and which\n* documents were deleted, which documents should be skipped.\n*\n* For the time being, documents are indexed using their hashes, and users\n* are not able to specify the uid of the document.\n*\n* @param {IndexArgs} args\n* @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents.\n* @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents.\n* @param {VectorStore} args.vectorStore The vector store to use for storing the documents.\n* @param {IndexOptions | undefined} args.options Options for indexing.\n* @returns {Promise}\n*/\nasync function index(args) {\n\tconst { docsSource, recordManager, vectorStore, options } = args;\n\tconst { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1e3, forceUpdate = false } = options ?? {};\n\tif (cleanup === \"incremental\" && !sourceIdKey) throw new Error(\"sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.\");\n\tconst docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource;\n\tconst sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null);\n\tconst indexStartDt = await recordManager.getTime();\n\tlet numAdded = 0;\n\tlet numDeleted = 0;\n\tlet numUpdated = 0;\n\tlet numSkipped = 0;\n\tconst batches = _batch(batchSize ?? 100, docs);\n\tfor (const batch of batches) {\n\t\tconst hashedDocs = _deduplicateInOrder(batch.map((doc) => _HashedDocument.fromDocument(doc)));\n\t\tconst sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc));\n\t\tif (cleanup === \"incremental\") hashedDocs.forEach((_hashedDoc, index$1) => {\n\t\t\tconst source = sourceIds[index$1];\n\t\t\tif (source === null) throw new Error(\"sourceIdKey must be provided when cleanup is incremental\");\n\t\t});\n\t\tconst batchExists = await recordManager.exists(hashedDocs.map((doc) => doc.uid));\n\t\tconst uids = [];\n\t\tconst docsToIndex = [];\n\t\tconst docsToUpdate = [];\n\t\tconst seenDocs = /* @__PURE__ */ new Set();\n\t\thashedDocs.forEach((hashedDoc, i) => {\n\t\t\tconst docExists = batchExists[i];\n\t\t\tif (docExists) if (forceUpdate) seenDocs.add(hashedDoc.uid);\n\t\t\telse {\n\t\t\t\tdocsToUpdate.push(hashedDoc.uid);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tuids.push(hashedDoc.uid);\n\t\t\tdocsToIndex.push(hashedDoc.toDocument());\n\t\t});\n\t\tif (docsToUpdate.length > 0) {\n\t\t\tawait recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt });\n\t\t\tnumSkipped += docsToUpdate.length;\n\t\t}\n\t\tif (docsToIndex.length > 0) {\n\t\t\tawait vectorStore.addDocuments(docsToIndex, { ids: uids });\n\t\t\tnumAdded += docsToIndex.length - seenDocs.size;\n\t\t\tnumUpdated += seenDocs.size;\n\t\t}\n\t\tawait recordManager.update(hashedDocs.map((doc) => doc.uid), {\n\t\t\ttimeAtLeast: indexStartDt,\n\t\t\tgroupIds: sourceIds\n\t\t});\n\t\tif (cleanup === \"incremental\") {\n\t\t\tsourceIds.forEach((sourceId) => {\n\t\t\t\tif (!sourceId) throw new Error(\"Source id cannot be null\");\n\t\t\t});\n\t\t\tconst uidsToDelete = await recordManager.listKeys({\n\t\t\t\tbefore: indexStartDt,\n\t\t\t\tgroupIds: sourceIds\n\t\t\t});\n\t\t\tif (uidsToDelete.length > 0) {\n\t\t\t\tawait vectorStore.delete({ ids: uidsToDelete });\n\t\t\t\tawait recordManager.deleteKeys(uidsToDelete);\n\t\t\t\tnumDeleted += uidsToDelete.length;\n\t\t\t}\n\t\t}\n\t}\n\tif (cleanup === \"full\") {\n\t\tlet uidsToDelete = await recordManager.listKeys({\n\t\t\tbefore: indexStartDt,\n\t\t\tlimit: cleanupBatchSize\n\t\t});\n\t\twhile (uidsToDelete.length > 0) {\n\t\t\tawait vectorStore.delete({ ids: uidsToDelete });\n\t\t\tawait recordManager.deleteKeys(uidsToDelete);\n\t\t\tnumDeleted += uidsToDelete.length;\n\t\t\tuidsToDelete = await recordManager.listKeys({\n\t\t\t\tbefore: indexStartDt,\n\t\t\t\tlimit: cleanupBatchSize\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\tnumAdded,\n\t\tnumDeleted,\n\t\tnumUpdated,\n\t\tnumSkipped\n\t};\n}\n\n//#endregion\nexport { _HashedDocument, _batch, _deduplicateInOrder, _getSourceIdAssigner, _isBaseDocumentLoader, index };\n//# sourceMappingURL=base.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { RecordManager, UUIDV5_NAMESPACE } from \"./record_manager.js\";\nimport { _HashedDocument, _batch, _deduplicateInOrder, _getSourceIdAssigner, _isBaseDocumentLoader, index } from \"./base.js\";\n\n//#region src/indexing/index.ts\nvar indexing_exports = {};\n__export(indexing_exports, {\n\tRecordManager: () => RecordManager,\n\tUUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE,\n\t_HashedDocument: () => _HashedDocument,\n\t_batch: () => _batch,\n\t_deduplicateInOrder: () => _deduplicateInOrder,\n\t_getSourceIdAssigner: () => _getSourceIdAssigner,\n\t_isBaseDocumentLoader: () => _isBaseDocumentLoader,\n\tindex: () => index\n});\n\n//#endregion\nexport { RecordManager, UUIDV5_NAMESPACE, _HashedDocument, _batch, _deduplicateInOrder, _getSourceIdAssigner, _isBaseDocumentLoader, index, indexing_exports };\n//# sourceMappingURL=index.js.map","import base64 from 'base64-js';\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\n\n// src/utils.ts\nfunction never(_) {\n}\nfunction bytePairMerge(piece, ranks) {\n let parts = Array.from(\n { length: piece.length },\n (_, i) => ({ start: i, end: i + 1 })\n );\n while (parts.length > 1) {\n let minRank = null;\n for (let i = 0; i < parts.length - 1; i++) {\n const slice = piece.slice(parts[i].start, parts[i + 1].end);\n const rank = ranks.get(slice.join(\",\"));\n if (rank == null)\n continue;\n if (minRank == null || rank < minRank[0]) {\n minRank = [rank, i];\n }\n }\n if (minRank != null) {\n const i = minRank[1];\n parts[i] = { start: parts[i].start, end: parts[i + 1].end };\n parts.splice(i + 1, 1);\n } else {\n break;\n }\n }\n return parts;\n}\nfunction bytePairEncode(piece, ranks) {\n if (piece.length === 1)\n return [ranks.get(piece.join(\",\"))];\n return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(\",\"))).filter((x) => x != null);\n}\nfunction escapeRegex(str) {\n return str.replace(/[\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n}\nvar _Tiktoken = class {\n /** @internal */\n specialTokens;\n /** @internal */\n inverseSpecialTokens;\n /** @internal */\n patStr;\n /** @internal */\n textEncoder = new TextEncoder();\n /** @internal */\n textDecoder = new TextDecoder(\"utf-8\");\n /** @internal */\n rankMap = /* @__PURE__ */ new Map();\n /** @internal */\n textMap = /* @__PURE__ */ new Map();\n constructor(ranks, extendedSpecialTokens) {\n this.patStr = ranks.pat_str;\n const uncompressed = ranks.bpe_ranks.split(\"\\n\").filter(Boolean).reduce((memo, x) => {\n const [_, offsetStr, ...tokens] = x.split(\" \");\n const offset = Number.parseInt(offsetStr, 10);\n tokens.forEach((token, i) => memo[token] = offset + i);\n return memo;\n }, {});\n for (const [token, rank] of Object.entries(uncompressed)) {\n const bytes = base64.toByteArray(token);\n this.rankMap.set(bytes.join(\",\"), rank);\n this.textMap.set(rank, bytes);\n }\n this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens };\n this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => {\n memo[rank] = this.textEncoder.encode(text);\n return memo;\n }, {});\n }\n encode(text, allowedSpecial = [], disallowedSpecial = \"all\") {\n const regexes = new RegExp(this.patStr, \"ug\");\n const specialRegex = _Tiktoken.specialTokenRegex(\n Object.keys(this.specialTokens)\n );\n const ret = [];\n const allowedSpecialSet = new Set(\n allowedSpecial === \"all\" ? Object.keys(this.specialTokens) : allowedSpecial\n );\n const disallowedSpecialSet = new Set(\n disallowedSpecial === \"all\" ? Object.keys(this.specialTokens).filter(\n (x) => !allowedSpecialSet.has(x)\n ) : disallowedSpecial\n );\n if (disallowedSpecialSet.size > 0) {\n const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([\n ...disallowedSpecialSet\n ]);\n const specialMatch = text.match(disallowedSpecialRegex);\n if (specialMatch != null) {\n throw new Error(\n `The text contains a special token that is not allowed: ${specialMatch[0]}`\n );\n }\n }\n let start = 0;\n while (true) {\n let nextSpecial = null;\n let startFind = start;\n while (true) {\n specialRegex.lastIndex = startFind;\n nextSpecial = specialRegex.exec(text);\n if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0]))\n break;\n startFind = nextSpecial.index + 1;\n }\n const end = nextSpecial?.index ?? text.length;\n for (const match of text.substring(start, end).matchAll(regexes)) {\n const piece = this.textEncoder.encode(match[0]);\n const token2 = this.rankMap.get(piece.join(\",\"));\n if (token2 != null) {\n ret.push(token2);\n continue;\n }\n ret.push(...bytePairEncode(piece, this.rankMap));\n }\n if (nextSpecial == null)\n break;\n let token = this.specialTokens[nextSpecial[0]];\n ret.push(token);\n start = nextSpecial.index + nextSpecial[0].length;\n }\n return ret;\n }\n decode(tokens) {\n const res = [];\n let length = 0;\n for (let i2 = 0; i2 < tokens.length; ++i2) {\n const token = tokens[i2];\n const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token];\n if (bytes != null) {\n res.push(bytes);\n length += bytes.length;\n }\n }\n const mergedArray = new Uint8Array(length);\n let i = 0;\n for (const bytes of res) {\n mergedArray.set(bytes, i);\n i += bytes.length;\n }\n return this.textDecoder.decode(mergedArray);\n }\n};\nvar Tiktoken = _Tiktoken;\n__publicField(Tiktoken, \"specialTokenRegex\", (tokens) => {\n return new RegExp(tokens.map((i) => escapeRegex(i)).join(\"|\"), \"g\");\n});\nfunction getEncodingNameForModel(model) {\n switch (model) {\n case \"gpt2\": {\n return \"gpt2\";\n }\n case \"code-cushman-001\":\n case \"code-cushman-002\":\n case \"code-davinci-001\":\n case \"code-davinci-002\":\n case \"cushman-codex\":\n case \"davinci-codex\":\n case \"davinci-002\":\n case \"text-davinci-002\":\n case \"text-davinci-003\": {\n return \"p50k_base\";\n }\n case \"code-davinci-edit-001\":\n case \"text-davinci-edit-001\": {\n return \"p50k_edit\";\n }\n case \"ada\":\n case \"babbage\":\n case \"babbage-002\":\n case \"code-search-ada-code-001\":\n case \"code-search-babbage-code-001\":\n case \"curie\":\n case \"davinci\":\n case \"text-ada-001\":\n case \"text-babbage-001\":\n case \"text-curie-001\":\n case \"text-davinci-001\":\n case \"text-search-ada-doc-001\":\n case \"text-search-babbage-doc-001\":\n case \"text-search-curie-doc-001\":\n case \"text-search-davinci-doc-001\":\n case \"text-similarity-ada-001\":\n case \"text-similarity-babbage-001\":\n case \"text-similarity-curie-001\":\n case \"text-similarity-davinci-001\": {\n return \"r50k_base\";\n }\n case \"gpt-3.5-turbo-instruct-0914\":\n case \"gpt-3.5-turbo-instruct\":\n case \"gpt-3.5-turbo-16k-0613\":\n case \"gpt-3.5-turbo-16k\":\n case \"gpt-3.5-turbo-0613\":\n case \"gpt-3.5-turbo-0301\":\n case \"gpt-3.5-turbo\":\n case \"gpt-4-32k-0613\":\n case \"gpt-4-32k-0314\":\n case \"gpt-4-32k\":\n case \"gpt-4-0613\":\n case \"gpt-4-0314\":\n case \"gpt-4\":\n case \"gpt-3.5-turbo-1106\":\n case \"gpt-35-turbo\":\n case \"gpt-4-1106-preview\":\n case \"gpt-4-vision-preview\":\n case \"gpt-3.5-turbo-0125\":\n case \"gpt-4-turbo\":\n case \"gpt-4-turbo-2024-04-09\":\n case \"gpt-4-turbo-preview\":\n case \"gpt-4-0125-preview\":\n case \"text-embedding-ada-002\":\n case \"text-embedding-3-small\":\n case \"text-embedding-3-large\": {\n return \"cl100k_base\";\n }\n case \"gpt-4o\":\n case \"gpt-4o-2024-05-13\":\n case \"gpt-4o-2024-08-06\":\n case \"gpt-4o-2024-11-20\":\n case \"gpt-4o-mini-2024-07-18\":\n case \"gpt-4o-mini\":\n case \"gpt-4o-search-preview\":\n case \"gpt-4o-search-preview-2025-03-11\":\n case \"gpt-4o-mini-search-preview\":\n case \"gpt-4o-mini-search-preview-2025-03-11\":\n case \"gpt-4o-audio-preview\":\n case \"gpt-4o-audio-preview-2024-12-17\":\n case \"gpt-4o-audio-preview-2024-10-01\":\n case \"gpt-4o-mini-audio-preview\":\n case \"gpt-4o-mini-audio-preview-2024-12-17\":\n case \"o1\":\n case \"o1-2024-12-17\":\n case \"o1-mini\":\n case \"o1-mini-2024-09-12\":\n case \"o1-preview\":\n case \"o1-preview-2024-09-12\":\n case \"o1-pro\":\n case \"o1-pro-2025-03-19\":\n case \"o3\":\n case \"o3-2025-04-16\":\n case \"o3-mini\":\n case \"o3-mini-2025-01-31\":\n case \"o4-mini\":\n case \"o4-mini-2025-04-16\":\n case \"chatgpt-4o-latest\":\n case \"gpt-4o-realtime\":\n case \"gpt-4o-realtime-preview-2024-10-01\":\n case \"gpt-4o-realtime-preview-2024-12-17\":\n case \"gpt-4o-mini-realtime-preview\":\n case \"gpt-4o-mini-realtime-preview-2024-12-17\":\n case \"gpt-4.1\":\n case \"gpt-4.1-2025-04-14\":\n case \"gpt-4.1-mini\":\n case \"gpt-4.1-mini-2025-04-14\":\n case \"gpt-4.1-nano\":\n case \"gpt-4.1-nano-2025-04-14\":\n case \"gpt-4.5-preview\":\n case \"gpt-4.5-preview-2025-02-27\":\n case \"gpt-5\":\n case \"gpt-5-2025-08-07\":\n case \"gpt-5-nano\":\n case \"gpt-5-nano-2025-08-07\":\n case \"gpt-5-mini\":\n case \"gpt-5-mini-2025-08-07\":\n case \"gpt-5-chat-latest\": {\n return \"o200k_base\";\n }\n default:\n throw new Error(\"Unknown model\");\n }\n}\n\nexport { Tiktoken, getEncodingNameForModel, never };\n","export { Tiktoken, getEncodingNameForModel } from './chunk-VL2OQCWN.js';\n","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { AsyncCaller } from \"./async_caller.js\";\nimport { Tiktoken, getEncodingNameForModel } from \"js-tiktoken/lite\";\n\n//#region src/utils/tiktoken.ts\nvar tiktoken_exports = {};\n__export(tiktoken_exports, {\n\tencodingForModel: () => encodingForModel,\n\tgetEncoding: () => getEncoding\n});\nconst cache = {};\nconst caller = /* @__PURE__ */ new AsyncCaller({});\nasync function getEncoding(encoding) {\n\tif (!(encoding in cache)) cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => {\n\t\tdelete cache[encoding];\n\t\tthrow e;\n\t});\n\treturn await cache[encoding];\n}\nasync function encodingForModel(model) {\n\treturn getEncoding(getEncodingNameForModel(model));\n}\n\n//#endregion\nexport { encodingForModel, getEncoding, tiktoken_exports };\n//# sourceMappingURL=tiktoken.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { AsyncCaller } from \"../utils/async_caller.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { ChatPromptValue, StringPromptValue } from \"../prompt_values.js\";\nimport { InMemoryCache } from \"../caches/base.js\";\nimport { encodingForModel } from \"../utils/tiktoken.js\";\n\n//#region src/language_models/base.ts\nvar base_exports = {};\n__export(base_exports, {\n\tBaseLangChain: () => BaseLangChain,\n\tBaseLanguageModel: () => BaseLanguageModel,\n\tcalculateMaxTokens: () => calculateMaxTokens,\n\tgetEmbeddingContextSize: () => getEmbeddingContextSize,\n\tgetModelContextSize: () => getModelContextSize,\n\tgetModelNameForTiktoken: () => getModelNameForTiktoken,\n\tisOpenAITool: () => isOpenAITool\n});\nconst getModelNameForTiktoken = (modelName) => {\n\tif (modelName.startsWith(\"gpt-3.5-turbo-16k\")) return \"gpt-3.5-turbo-16k\";\n\tif (modelName.startsWith(\"gpt-3.5-turbo-\")) return \"gpt-3.5-turbo\";\n\tif (modelName.startsWith(\"gpt-4-32k\")) return \"gpt-4-32k\";\n\tif (modelName.startsWith(\"gpt-4-\")) return \"gpt-4\";\n\tif (modelName.startsWith(\"gpt-4o\")) return \"gpt-4o\";\n\treturn modelName;\n};\nconst getEmbeddingContextSize = (modelName) => {\n\tswitch (modelName) {\n\t\tcase \"text-embedding-ada-002\": return 8191;\n\t\tdefault: return 2046;\n\t}\n};\nconst getModelContextSize = (modelName) => {\n\tswitch (getModelNameForTiktoken(modelName)) {\n\t\tcase \"gpt-3.5-turbo-16k\": return 16384;\n\t\tcase \"gpt-3.5-turbo\": return 4096;\n\t\tcase \"gpt-4-32k\": return 32768;\n\t\tcase \"gpt-4\": return 8192;\n\t\tcase \"text-davinci-003\": return 4097;\n\t\tcase \"text-curie-001\": return 2048;\n\t\tcase \"text-babbage-001\": return 2048;\n\t\tcase \"text-ada-001\": return 2048;\n\t\tcase \"code-davinci-002\": return 8e3;\n\t\tcase \"code-cushman-001\": return 2048;\n\t\tdefault: return 4097;\n\t}\n};\n/**\n* Whether or not the input matches the OpenAI tool definition.\n* @param {unknown} tool The input to check.\n* @returns {boolean} Whether the input is an OpenAI tool definition.\n*/\nfunction isOpenAITool(tool) {\n\tif (typeof tool !== \"object\" || !tool) return false;\n\tif (\"type\" in tool && tool.type === \"function\" && \"function\" in tool && typeof tool.function === \"object\" && tool.function && \"name\" in tool.function && \"parameters\" in tool.function) return true;\n\treturn false;\n}\nconst calculateMaxTokens = async ({ prompt, modelName }) => {\n\tlet numTokens;\n\ttry {\n\t\tnumTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length;\n\t} catch {\n\t\tconsole.warn(\"Failed to calculate number of tokens, falling back to approximate count\");\n\t\tnumTokens = Math.ceil(prompt.length / 4);\n\t}\n\tconst maxTokens = getModelContextSize(modelName);\n\treturn maxTokens - numTokens;\n};\nconst getVerbosity = () => false;\n/**\n* Base class for language models, chains, tools.\n*/\nvar BaseLangChain = class extends Runnable {\n\t/**\n\t* Whether to print out response text.\n\t*/\n\tverbose;\n\tcallbacks;\n\ttags;\n\tmetadata;\n\tget lc_attributes() {\n\t\treturn {\n\t\t\tcallbacks: void 0,\n\t\t\tverbose: void 0\n\t\t};\n\t}\n\tconstructor(params) {\n\t\tsuper(params);\n\t\tthis.verbose = params.verbose ?? getVerbosity();\n\t\tthis.callbacks = params.callbacks;\n\t\tthis.tags = params.tags ?? [];\n\t\tthis.metadata = params.metadata ?? {};\n\t}\n};\n/**\n* Base class for language models.\n*/\nvar BaseLanguageModel = class extends BaseLangChain {\n\t/**\n\t* Keys that the language model accepts as call options.\n\t*/\n\tget callKeys() {\n\t\treturn [\n\t\t\t\"stop\",\n\t\t\t\"timeout\",\n\t\t\t\"signal\",\n\t\t\t\"tags\",\n\t\t\t\"metadata\",\n\t\t\t\"callbacks\"\n\t\t];\n\t}\n\t/**\n\t* The async caller should be used by subclasses to make any async calls,\n\t* which will thus benefit from the concurrency and retry logic.\n\t*/\n\tcaller;\n\tcache;\n\tconstructor({ callbacks, callbackManager,...params }) {\n\t\tconst { cache,...rest } = params;\n\t\tsuper({\n\t\t\tcallbacks: callbacks ?? callbackManager,\n\t\t\t...rest\n\t\t});\n\t\tif (typeof cache === \"object\") this.cache = cache;\n\t\telse if (cache) this.cache = InMemoryCache.global();\n\t\telse this.cache = void 0;\n\t\tthis.caller = new AsyncCaller(params ?? {});\n\t}\n\t_encoding;\n\t/**\n\t* Get the number of tokens in the content.\n\t* @param content The content to get the number of tokens for.\n\t* @returns The number of tokens in the content.\n\t*/\n\tasync getNumTokens(content) {\n\t\tlet textContent;\n\t\tif (typeof content === \"string\") textContent = content;\n\t\telse\n /**\n\t\t* Content is an array of ContentBlock\n\t\t*\n\t\t* ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content.\n\t\t* We need to find a better way to do this.\n\t\t* @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116\n\t\t*/\n\t\ttextContent = content.map((item) => {\n\t\t\tif (typeof item === \"string\") return item;\n\t\t\tif (item.type === \"text\" && \"text\" in item) return item.text;\n\t\t\treturn \"\";\n\t\t}).join(\"\");\n\t\tlet numTokens = Math.ceil(textContent.length / 4);\n\t\tif (!this._encoding) try {\n\t\t\tthis._encoding = await encodingForModel(\"modelName\" in this ? getModelNameForTiktoken(this.modelName) : \"gpt2\");\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Failed to calculate number of tokens, falling back to approximate count\", error);\n\t\t}\n\t\tif (this._encoding) try {\n\t\t\tnumTokens = this._encoding.encode(textContent).length;\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"Failed to calculate number of tokens, falling back to approximate count\", error);\n\t\t}\n\t\treturn numTokens;\n\t}\n\tstatic _convertInputToPromptValue(input) {\n\t\tif (typeof input === \"string\") return new StringPromptValue(input);\n\t\telse if (Array.isArray(input)) return new ChatPromptValue(input.map(coerceMessageLikeToMessage));\n\t\telse return input;\n\t}\n\t/**\n\t* Get the identifying parameters of the LLM.\n\t*/\n\t_identifyingParams() {\n\t\treturn {};\n\t}\n\t/**\n\t* Create a unique cache key for a specific call to a specific language model.\n\t* @param callOptions Call options for the model\n\t* @returns A unique cache key.\n\t*/\n\t_getSerializedCacheKeyParametersForCall({ config,...callOptions }) {\n\t\tconst params = {\n\t\t\t...this._identifyingParams(),\n\t\t\t...callOptions,\n\t\t\t_type: this._llmType(),\n\t\t\t_model: this._modelType()\n\t\t};\n\t\tconst filteredEntries = Object.entries(params).filter(([_, value]) => value !== void 0);\n\t\tconst serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(\",\");\n\t\treturn serializedEntries;\n\t}\n\t/**\n\t* @deprecated\n\t* Return a json-like object representing this LLM.\n\t*/\n\tserialize() {\n\t\treturn {\n\t\t\t...this._identifyingParams(),\n\t\t\t_type: this._llmType(),\n\t\t\t_model: this._modelType()\n\t\t};\n\t}\n\t/**\n\t* @deprecated\n\t* Load an LLM from a json-like object describing it.\n\t*/\n\tstatic async deserialize(_data) {\n\t\tthrow new Error(\"Use .toJSON() instead\");\n\t}\n};\n\n//#endregion\nexport { BaseLangChain, BaseLanguageModel, base_exports, calculateMaxTokens, getEmbeddingContextSize, getModelContextSize, getModelNameForTiktoken, isOpenAITool };\n//# sourceMappingURL=base.js.map","import { ensureConfig } from \"./config.js\";\nimport { concat } from \"../utils/stream.js\";\nimport { Runnable, RunnableAssign, RunnableMap } from \"./base.js\";\n\n//#region src/runnables/passthrough.ts\n/**\n* A runnable to passthrough inputs unchanged or with additional keys.\n*\n* This runnable behaves almost like the identity function, except that it\n* can be configured to add additional keys to the output, if the input is\n* an object.\n*\n* The example below demonstrates how to use `RunnablePassthrough to\n* passthrough the input from the `.invoke()`\n*\n* @example\n* ```typescript\n* const chain = RunnableSequence.from([\n* {\n* question: new RunnablePassthrough(),\n* context: async () => loadContextFromStore(),\n* },\n* prompt,\n* llm,\n* outputParser,\n* ]);\n* const response = await chain.invoke(\n* \"I can pass a single string instead of an object since I'm using `RunnablePassthrough`.\"\n* );\n* ```\n*/\nvar RunnablePassthrough = class extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnablePassthrough\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\tfunc;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tif (fields) this.func = fields.func;\n\t}\n\tasync invoke(input, options) {\n\t\tconst config = ensureConfig(options);\n\t\tif (this.func) await this.func(input, config);\n\t\treturn this._callWithConfig((input$1) => Promise.resolve(input$1), input, config);\n\t}\n\tasync *transform(generator, options) {\n\t\tconst config = ensureConfig(options);\n\t\tlet finalOutput;\n\t\tlet finalOutputSupported = true;\n\t\tfor await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) {\n\t\t\tyield chunk;\n\t\t\tif (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk;\n\t\t\telse try {\n\t\t\t\tfinalOutput = concat(finalOutput, chunk);\n\t\t\t} catch {\n\t\t\t\tfinalOutput = void 0;\n\t\t\t\tfinalOutputSupported = false;\n\t\t\t}\n\t\t}\n\t\tif (this.func && finalOutput !== void 0) await this.func(finalOutput, config);\n\t}\n\t/**\n\t* A runnable that assigns key-value pairs to the input.\n\t*\n\t* The example below shows how you could use it with an inline function.\n\t*\n\t* @example\n\t* ```typescript\n\t* const prompt =\n\t* PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}\n\t* Question: {question}\n\t* SQL Query:`);\n\t*\n\t* // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`\n\t* // call (in this example it's the question), along with any inputs passed to the `.assign()` method.\n\t* // In this case, we're passing the schema.\n\t* const sqlQueryGeneratorChain = RunnableSequence.from([\n\t* RunnablePassthrough.assign({\n\t* schema: async () => db.getTableInfo(),\n\t* }),\n\t* prompt,\n\t* new ChatOpenAI({ model: \"gpt-4o-mini\" }).withConfig({ stop: [\"\\nSQLResult:\"] }),\n\t* new StringOutputParser(),\n\t* ]);\n\t* const result = await sqlQueryGeneratorChain.invoke({\n\t* question: \"How many employees are there?\",\n\t* });\n\t* ```\n\t*/\n\tstatic assign(mapping) {\n\t\treturn new RunnableAssign(new RunnableMap({ steps: mapping }));\n\t}\n};\n\n//#endregion\nexport { RunnablePassthrough };\n//# sourceMappingURL=passthrough.js.map","//#region src/language_models/utils.ts\nconst iife = (fn) => fn();\nfunction castStandardMessageContent(message) {\n\tconst Cls = message.constructor;\n\treturn new Cls({\n\t\t...message,\n\t\tcontent: message.contentBlocks,\n\t\tresponse_metadata: {\n\t\t\t...message.response_metadata,\n\t\t\toutput_version: \"v1\"\n\t\t}\n\t});\n}\n\n//#endregion\nexport { castStandardMessageContent, iife };\n//# sourceMappingURL=utils.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { convertToOpenAIImageBlock, isBase64ContentBlock, isURLContentBlock } from \"../messages/content/data.js\";\nimport { isBaseMessage } from \"../messages/base.js\";\nimport { AIMessage, AIMessageChunk, isAIMessage, isAIMessageChunk } from \"../messages/ai.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\nimport { callbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { CallbackManager } from \"../callbacks/manager.js\";\nimport { concat } from \"../utils/stream.js\";\nimport { RUN_KEY } from \"../outputs.js\";\nimport { getSchemaDescription, isInteropZodSchema } from \"../utils/types/zod.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\nimport { RunnableLambda, RunnableSequence } from \"../runnables/base.js\";\nimport \"../messages/index.js\";\nimport { BaseLanguageModel } from \"./base.js\";\nimport { RunnablePassthrough } from \"../runnables/passthrough.js\";\nimport { castStandardMessageContent, iife } from \"./utils.js\";\n\n//#region src/language_models/chat_models.ts\nvar chat_models_exports = {};\n__export(chat_models_exports, {\n\tBaseChatModel: () => BaseChatModel,\n\tSimpleChatModel: () => SimpleChatModel\n});\nfunction _formatForTracing(messages) {\n\tconst messagesToTrace = [];\n\tfor (const message of messages) {\n\t\tlet messageToTrace = message;\n\t\tif (Array.isArray(message.content)) for (let idx = 0; idx < message.content.length; idx++) {\n\t\t\tconst block = message.content[idx];\n\t\t\tif (isURLContentBlock(block) || isBase64ContentBlock(block)) {\n\t\t\t\tif (messageToTrace === message) messageToTrace = new message.constructor({\n\t\t\t\t\t...messageToTrace,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t...message.content.slice(0, idx),\n\t\t\t\t\t\tconvertToOpenAIImageBlock(block),\n\t\t\t\t\t\t...message.content.slice(idx + 1)\n\t\t\t\t\t]\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tmessagesToTrace.push(messageToTrace);\n\t}\n\treturn messagesToTrace;\n}\n/**\n* Base class for chat models. It extends the BaseLanguageModel class and\n* provides methods for generating chat based on input messages.\n*/\nvar BaseChatModel = class BaseChatModel extends BaseLanguageModel {\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"chat_models\",\n\t\tthis._llmType()\n\t];\n\tdisableStreaming = false;\n\toutputVersion;\n\tget callKeys() {\n\t\treturn [...super.callKeys, \"outputVersion\"];\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.outputVersion = iife(() => {\n\t\t\tconst outputVersion = fields.outputVersion ?? getEnvironmentVariable(\"LC_OUTPUT_VERSION\");\n\t\t\tif (outputVersion && [\"v0\", \"v1\"].includes(outputVersion)) return outputVersion;\n\t\t\treturn \"v0\";\n\t\t});\n\t}\n\t_separateRunnableConfigFromCallOptionsCompat(options) {\n\t\tconst [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options);\n\t\tcallOptions.signal = runnableConfig.signal;\n\t\treturn [runnableConfig, callOptions];\n\t}\n\t/**\n\t* Invokes the chat model with a single input.\n\t* @param input The input for the language model.\n\t* @param options The call options.\n\t* @returns A Promise that resolves to a BaseMessageChunk.\n\t*/\n\tasync invoke(input, options) {\n\t\tconst promptValue = BaseChatModel._convertInputToPromptValue(input);\n\t\tconst result = await this.generatePrompt([promptValue], options, options?.callbacks);\n\t\tconst chatGeneration = result.generations[0][0];\n\t\treturn chatGeneration.message;\n\t}\n\tasync *_streamResponseChunks(_messages, _options, _runManager) {\n\t\tthrow new Error(\"Not implemented.\");\n\t}\n\tasync *_streamIterator(input, options) {\n\t\tif (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) yield this.invoke(input, options);\n\t\telse {\n\t\t\tconst prompt = BaseChatModel._convertInputToPromptValue(input);\n\t\t\tconst messages = prompt.toChatMessages();\n\t\t\tconst [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options);\n\t\t\tconst inheritableMetadata = {\n\t\t\t\t...runnableConfig.metadata,\n\t\t\t\t...this.getLsParams(callOptions)\n\t\t\t};\n\t\t\tconst callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });\n\t\t\tconst extra = {\n\t\t\t\toptions: callOptions,\n\t\t\t\tinvocation_params: this?.invocationParams(callOptions),\n\t\t\t\tbatch_size: 1\n\t\t\t};\n\t\t\tconst outputVersion = callOptions.outputVersion ?? this.outputVersion;\n\t\t\tconst runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName);\n\t\t\tlet generationChunk;\n\t\t\tlet llmOutput;\n\t\t\ttry {\n\t\t\t\tfor await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) {\n\t\t\t\t\tif (chunk.message.id == null) {\n\t\t\t\t\t\tconst runId = runManagers?.at(0)?.runId;\n\t\t\t\t\t\tif (runId != null) chunk.message._updateId(`run-${runId}`);\n\t\t\t\t\t}\n\t\t\t\t\tchunk.message.response_metadata = {\n\t\t\t\t\t\t...chunk.generationInfo,\n\t\t\t\t\t\t...chunk.message.response_metadata\n\t\t\t\t\t};\n\t\t\t\t\tif (outputVersion === \"v1\") yield castStandardMessageContent(chunk.message);\n\t\t\t\t\telse yield chunk.message;\n\t\t\t\t\tif (!generationChunk) generationChunk = chunk;\n\t\t\t\t\telse generationChunk = generationChunk.concat(chunk);\n\t\t\t\t\tif (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: {\n\t\t\t\t\t\tpromptTokens: chunk.message.usage_metadata.input_tokens,\n\t\t\t\t\t\tcompletionTokens: chunk.message.usage_metadata.output_tokens,\n\t\t\t\t\t\ttotalTokens: chunk.message.usage_metadata.total_tokens\n\t\t\t\t\t} };\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tawait Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err)));\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tawait Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({\n\t\t\t\tgenerations: [[generationChunk]],\n\t\t\t\tllmOutput\n\t\t\t})));\n\t\t}\n\t}\n\tgetLsParams(options) {\n\t\tconst providerName = this.getName().startsWith(\"Chat\") ? this.getName().replace(\"Chat\", \"\") : this.getName();\n\t\treturn {\n\t\t\tls_model_type: \"chat\",\n\t\t\tls_stop: options.stop,\n\t\t\tls_provider: providerName\n\t\t};\n\t}\n\t/** @ignore */\n\tasync _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) {\n\t\tconst baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));\n\t\tlet runManagers;\n\t\tif (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) runManagers = startedRunManagers;\n\t\telse {\n\t\t\tconst inheritableMetadata = {\n\t\t\t\t...handledOptions.metadata,\n\t\t\t\t...this.getLsParams(parsedOptions)\n\t\t\t};\n\t\t\tconst callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });\n\t\t\tconst extra = {\n\t\t\t\toptions: parsedOptions,\n\t\t\t\tinvocation_params: this?.invocationParams(parsedOptions),\n\t\t\t\tbatch_size: 1\n\t\t\t};\n\t\t\trunManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName);\n\t\t}\n\t\tconst outputVersion = parsedOptions.outputVersion ?? this.outputVersion;\n\t\tconst generations = [];\n\t\tconst llmOutputs = [];\n\t\tconst hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming);\n\t\tif (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) try {\n\t\t\tconst stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]);\n\t\t\tlet aggregated;\n\t\t\tlet llmOutput;\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tif (chunk.message.id == null) {\n\t\t\t\t\tconst runId = runManagers?.at(0)?.runId;\n\t\t\t\t\tif (runId != null) chunk.message._updateId(`run-${runId}`);\n\t\t\t\t}\n\t\t\t\tif (aggregated === void 0) aggregated = chunk;\n\t\t\t\telse aggregated = concat(aggregated, chunk);\n\t\t\t\tif (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: {\n\t\t\t\t\tpromptTokens: chunk.message.usage_metadata.input_tokens,\n\t\t\t\t\tcompletionTokens: chunk.message.usage_metadata.output_tokens,\n\t\t\t\t\ttotalTokens: chunk.message.usage_metadata.total_tokens\n\t\t\t\t} };\n\t\t\t}\n\t\t\tif (aggregated === void 0) throw new Error(\"Received empty response from chat model call.\");\n\t\t\tgenerations.push([aggregated]);\n\t\t\tawait runManagers?.[0].handleLLMEnd({\n\t\t\t\tgenerations,\n\t\t\t\tllmOutput\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tawait runManagers?.[0].handleLLMError(e);\n\t\t\tthrow e;\n\t\t}\n\t\telse {\n\t\t\tconst results = await Promise.allSettled(baseMessages.map(async (messageList, i) => {\n\t\t\t\tconst generateResults = await this._generate(messageList, {\n\t\t\t\t\t...parsedOptions,\n\t\t\t\t\tpromptIndex: i\n\t\t\t\t}, runManagers?.[i]);\n\t\t\t\tif (outputVersion === \"v1\") for (const generation of generateResults.generations) generation.message = castStandardMessageContent(generation.message);\n\t\t\t\treturn generateResults;\n\t\t\t}));\n\t\t\tawait Promise.all(results.map(async (pResult, i) => {\n\t\t\t\tif (pResult.status === \"fulfilled\") {\n\t\t\t\t\tconst result = pResult.value;\n\t\t\t\t\tfor (const generation of result.generations) {\n\t\t\t\t\t\tif (generation.message.id == null) {\n\t\t\t\t\t\t\tconst runId = runManagers?.at(0)?.runId;\n\t\t\t\t\t\t\tif (runId != null) generation.message._updateId(`run-${runId}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgeneration.message.response_metadata = {\n\t\t\t\t\t\t\t...generation.generationInfo,\n\t\t\t\t\t\t\t...generation.message.response_metadata\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (result.generations.length === 1) result.generations[0].message.response_metadata = {\n\t\t\t\t\t\t...result.llmOutput,\n\t\t\t\t\t\t...result.generations[0].message.response_metadata\n\t\t\t\t\t};\n\t\t\t\t\tgenerations[i] = result.generations;\n\t\t\t\t\tllmOutputs[i] = result.llmOutput;\n\t\t\t\t\treturn runManagers?.[i]?.handleLLMEnd({\n\t\t\t\t\t\tgenerations: [result.generations],\n\t\t\t\t\t\tllmOutput: result.llmOutput\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait runManagers?.[i]?.handleLLMError(pResult.reason);\n\t\t\t\t\treturn Promise.reject(pResult.reason);\n\t\t\t\t}\n\t\t\t}));\n\t\t}\n\t\tconst output = {\n\t\t\tgenerations,\n\t\t\tllmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0\n\t\t};\n\t\tObject.defineProperty(output, RUN_KEY, {\n\t\t\tvalue: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0,\n\t\t\tconfigurable: true\n\t\t});\n\t\treturn output;\n\t}\n\tasync _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions }) {\n\t\tconst baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));\n\t\tconst inheritableMetadata = {\n\t\t\t...handledOptions.metadata,\n\t\t\t...this.getLsParams(parsedOptions)\n\t\t};\n\t\tconst callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });\n\t\tconst extra = {\n\t\t\toptions: parsedOptions,\n\t\t\tinvocation_params: this?.invocationParams(parsedOptions),\n\t\t\tbatch_size: 1\n\t\t};\n\t\tconst runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName);\n\t\tconst missingPromptIndices = [];\n\t\tconst results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => {\n\t\t\tconst prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString();\n\t\t\tconst result = await cache.lookup(prompt, llmStringKey);\n\t\t\tif (result == null) missingPromptIndices.push(index);\n\t\t\treturn result;\n\t\t}));\n\t\tconst cachedResults = results.map((result, index) => ({\n\t\t\tresult,\n\t\t\trunManager: runManagers?.[index]\n\t\t})).filter(({ result }) => result.status === \"fulfilled\" && result.value != null || result.status === \"rejected\");\n\t\tconst outputVersion = parsedOptions.outputVersion ?? this.outputVersion;\n\t\tconst generations = [];\n\t\tawait Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => {\n\t\t\tif (promiseResult.status === \"fulfilled\") {\n\t\t\t\tconst result = promiseResult.value;\n\t\t\t\tgenerations[i] = result.map((result$1) => {\n\t\t\t\t\tif (\"message\" in result$1 && isBaseMessage(result$1.message) && isAIMessage(result$1.message)) {\n\t\t\t\t\t\tresult$1.message.usage_metadata = {\n\t\t\t\t\t\t\tinput_tokens: 0,\n\t\t\t\t\t\t\toutput_tokens: 0,\n\t\t\t\t\t\t\ttotal_tokens: 0\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (outputVersion === \"v1\") result$1.message = castStandardMessageContent(result$1.message);\n\t\t\t\t\t}\n\t\t\t\t\tresult$1.generationInfo = {\n\t\t\t\t\t\t...result$1.generationInfo,\n\t\t\t\t\t\ttokenUsage: {}\n\t\t\t\t\t};\n\t\t\t\t\treturn result$1;\n\t\t\t\t});\n\t\t\t\tif (result.length) await runManager?.handleLLMNewToken(result[0].text);\n\t\t\t\treturn runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true });\n\t\t\t} else {\n\t\t\t\tawait runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true });\n\t\t\t\treturn Promise.reject(promiseResult.reason);\n\t\t\t}\n\t\t}));\n\t\tconst output = {\n\t\t\tgenerations,\n\t\t\tmissingPromptIndices,\n\t\t\tstartedRunManagers: runManagers\n\t\t};\n\t\tObject.defineProperty(output, RUN_KEY, {\n\t\t\tvalue: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0,\n\t\t\tconfigurable: true\n\t\t});\n\t\treturn output;\n\t}\n\t/**\n\t* Generates chat based on the input messages.\n\t* @param messages An array of arrays of BaseMessage instances.\n\t* @param options The call options or an array of stop sequences.\n\t* @param callbacks The callbacks for the language model.\n\t* @returns A Promise that resolves to an LLMResult.\n\t*/\n\tasync generate(messages, options, callbacks) {\n\t\tlet parsedOptions;\n\t\tif (Array.isArray(options)) parsedOptions = { stop: options };\n\t\telse parsedOptions = options;\n\t\tconst baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));\n\t\tconst [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions);\n\t\trunnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;\n\t\tif (!this.cache) return this._generateUncached(baseMessages, callOptions, runnableConfig);\n\t\tconst { cache } = this;\n\t\tconst llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions);\n\t\tconst { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({\n\t\t\tmessages: baseMessages,\n\t\t\tcache,\n\t\t\tllmStringKey,\n\t\t\tparsedOptions: callOptions,\n\t\t\thandledOptions: runnableConfig\n\t\t});\n\t\tlet llmOutput = {};\n\t\tif (missingPromptIndices.length > 0) {\n\t\t\tconst results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0);\n\t\t\tawait Promise.all(results.generations.map(async (generation, index) => {\n\t\t\t\tconst promptIndex = missingPromptIndices[index];\n\t\t\t\tgenerations[promptIndex] = generation;\n\t\t\t\tconst prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString();\n\t\t\t\treturn cache.update(prompt, llmStringKey, generation);\n\t\t\t}));\n\t\t\tllmOutput = results.llmOutput ?? {};\n\t\t}\n\t\treturn {\n\t\t\tgenerations,\n\t\t\tllmOutput\n\t\t};\n\t}\n\t/**\n\t* Get the parameters used to invoke the model\n\t*/\n\tinvocationParams(_options) {\n\t\treturn {};\n\t}\n\t_modelType() {\n\t\treturn \"base_chat_model\";\n\t}\n\t/**\n\t* Generates a prompt based on the input prompt values.\n\t* @param promptValues An array of BasePromptValue instances.\n\t* @param options The call options or an array of stop sequences.\n\t* @param callbacks The callbacks for the language model.\n\t* @returns A Promise that resolves to an LLMResult.\n\t*/\n\tasync generatePrompt(promptValues, options, callbacks) {\n\t\tconst promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages());\n\t\treturn this.generate(promptMessages, options, callbacks);\n\t}\n\twithStructuredOutput(outputSchema, config) {\n\t\tif (typeof this.bindTools !== \"function\") throw new Error(`Chat model must implement \".bindTools()\" to use withStructuredOutput.`);\n\t\tif (config?.strict) throw new Error(`\"strict\" mode is not supported for this model by default.`);\n\t\tconst schema = outputSchema;\n\t\tconst name = config?.name;\n\t\tconst description = getSchemaDescription(schema) ?? \"A function available to call.\";\n\t\tconst method = config?.method;\n\t\tconst includeRaw = config?.includeRaw;\n\t\tif (method === \"jsonMode\") throw new Error(`Base withStructuredOutput implementation only supports \"functionCalling\" as a method.`);\n\t\tlet functionName = name ?? \"extract\";\n\t\tlet tools;\n\t\tif (isInteropZodSchema(schema)) tools = [{\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: functionName,\n\t\t\t\tdescription,\n\t\t\t\tparameters: toJsonSchema(schema)\n\t\t\t}\n\t\t}];\n\t\telse {\n\t\t\tif (\"name\" in schema) functionName = schema.name;\n\t\t\ttools = [{\n\t\t\t\ttype: \"function\",\n\t\t\t\tfunction: {\n\t\t\t\t\tname: functionName,\n\t\t\t\t\tdescription,\n\t\t\t\t\tparameters: schema\n\t\t\t\t}\n\t\t\t}];\n\t\t}\n\t\tconst llm = this.bindTools(tools);\n\t\tconst outputParser = RunnableLambda.from((input) => {\n\t\t\tif (!AIMessageChunk.isInstance(input)) throw new Error(\"Input is not an AIMessageChunk.\");\n\t\t\tif (!input.tool_calls || input.tool_calls.length === 0) throw new Error(\"No tool calls found in the response.\");\n\t\t\tconst toolCall = input.tool_calls.find((tc) => tc.name === functionName);\n\t\t\tif (!toolCall) throw new Error(`No tool call found with name ${functionName}.`);\n\t\t\treturn toolCall.args;\n\t\t});\n\t\tif (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: \"StructuredOutput\" });\n\t\tconst parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });\n\t\tconst parserNone = RunnablePassthrough.assign({ parsed: () => null });\n\t\tconst parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });\n\t\treturn RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: \"StructuredOutputRunnable\" });\n\t}\n};\n/**\n* An abstract class that extends BaseChatModel and provides a simple\n* implementation of _generate.\n*/\nvar SimpleChatModel = class extends BaseChatModel {\n\tasync _generate(messages, options, runManager) {\n\t\tconst text = await this._call(messages, options, runManager);\n\t\tconst message = new AIMessage(text);\n\t\tif (typeof message.content !== \"string\") throw new Error(\"Cannot generate with a simple chat model when output is not a string.\");\n\t\treturn { generations: [{\n\t\t\ttext: message.content,\n\t\t\tmessage\n\t\t}] };\n\t}\n};\n\n//#endregion\nexport { BaseChatModel, SimpleChatModel, chat_models_exports };\n//# sourceMappingURL=chat_models.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { callbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { CallbackManager } from \"../callbacks/manager.js\";\nimport { concat } from \"../utils/stream.js\";\nimport { GenerationChunk, RUN_KEY } from \"../outputs.js\";\nimport { BaseLanguageModel } from \"./base.js\";\n\n//#region src/language_models/llms.ts\nvar llms_exports = {};\n__export(llms_exports, {\n\tBaseLLM: () => BaseLLM,\n\tLLM: () => LLM\n});\n/**\n* LLM Wrapper. Takes in a prompt (or prompts) and returns a string.\n*/\nvar BaseLLM = class BaseLLM extends BaseLanguageModel {\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"llms\",\n\t\tthis._llmType()\n\t];\n\t/**\n\t* This method takes an input and options, and returns a string. It\n\t* converts the input to a prompt value and generates a result based on\n\t* the prompt.\n\t* @param input Input for the LLM.\n\t* @param options Options for the LLM call.\n\t* @returns A string result based on the prompt.\n\t*/\n\tasync invoke(input, options) {\n\t\tconst promptValue = BaseLLM._convertInputToPromptValue(input);\n\t\tconst result = await this.generatePrompt([promptValue], options, options?.callbacks);\n\t\treturn result.generations[0][0].text;\n\t}\n\tasync *_streamResponseChunks(_input, _options, _runManager) {\n\t\tthrow new Error(\"Not implemented.\");\n\t}\n\t_separateRunnableConfigFromCallOptionsCompat(options) {\n\t\tconst [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options);\n\t\tcallOptions.signal = runnableConfig.signal;\n\t\treturn [runnableConfig, callOptions];\n\t}\n\tasync *_streamIterator(input, options) {\n\t\tif (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) yield this.invoke(input, options);\n\t\telse {\n\t\t\tconst prompt = BaseLLM._convertInputToPromptValue(input);\n\t\t\tconst [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options);\n\t\t\tconst callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose });\n\t\t\tconst extra = {\n\t\t\t\toptions: callOptions,\n\t\t\t\tinvocation_params: this?.invocationParams(callOptions),\n\t\t\t\tbatch_size: 1\n\t\t\t};\n\t\t\tconst runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName);\n\t\t\tlet generation = new GenerationChunk({ text: \"\" });\n\t\t\ttry {\n\t\t\t\tfor await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) {\n\t\t\t\t\tif (!generation) generation = chunk;\n\t\t\t\t\telse generation = generation.concat(chunk);\n\t\t\t\t\tif (typeof chunk.text === \"string\") yield chunk.text;\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tawait Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err)));\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tawait Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] })));\n\t\t}\n\t}\n\t/**\n\t* This method takes prompt values, options, and callbacks, and generates\n\t* a result based on the prompts.\n\t* @param promptValues Prompt values for the LLM.\n\t* @param options Options for the LLM call.\n\t* @param callbacks Callbacks for the LLM call.\n\t* @returns An LLMResult based on the prompts.\n\t*/\n\tasync generatePrompt(promptValues, options, callbacks) {\n\t\tconst prompts = promptValues.map((promptValue) => promptValue.toString());\n\t\treturn this.generate(prompts, options, callbacks);\n\t}\n\t/**\n\t* Get the parameters used to invoke the model\n\t*/\n\tinvocationParams(_options) {\n\t\treturn {};\n\t}\n\t_flattenLLMResult(llmResult) {\n\t\tconst llmResults = [];\n\t\tfor (let i = 0; i < llmResult.generations.length; i += 1) {\n\t\t\tconst genList = llmResult.generations[i];\n\t\t\tif (i === 0) llmResults.push({\n\t\t\t\tgenerations: [genList],\n\t\t\t\tllmOutput: llmResult.llmOutput\n\t\t\t});\n\t\t\telse {\n\t\t\t\tconst llmOutput = llmResult.llmOutput ? {\n\t\t\t\t\t...llmResult.llmOutput,\n\t\t\t\t\ttokenUsage: {}\n\t\t\t\t} : void 0;\n\t\t\t\tllmResults.push({\n\t\t\t\t\tgenerations: [genList],\n\t\t\t\t\tllmOutput\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn llmResults;\n\t}\n\t/** @ignore */\n\tasync _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) {\n\t\tlet runManagers;\n\t\tif (startedRunManagers !== void 0 && startedRunManagers.length === prompts.length) runManagers = startedRunManagers;\n\t\telse {\n\t\t\tconst callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose });\n\t\t\tconst extra = {\n\t\t\t\toptions: parsedOptions,\n\t\t\t\tinvocation_params: this?.invocationParams(parsedOptions),\n\t\t\t\tbatch_size: prompts.length\n\t\t\t};\n\t\t\trunManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions?.runName);\n\t\t}\n\t\tconst hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming);\n\t\tlet output;\n\t\tif (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks) try {\n\t\t\tconst stream = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]);\n\t\t\tlet aggregated;\n\t\t\tfor await (const chunk of stream) if (aggregated === void 0) aggregated = chunk;\n\t\t\telse aggregated = concat(aggregated, chunk);\n\t\t\tif (aggregated === void 0) throw new Error(\"Received empty response from chat model call.\");\n\t\t\toutput = {\n\t\t\t\tgenerations: [[aggregated]],\n\t\t\t\tllmOutput: {}\n\t\t\t};\n\t\t\tawait runManagers?.[0].handleLLMEnd(output);\n\t\t} catch (e) {\n\t\t\tawait runManagers?.[0].handleLLMError(e);\n\t\t\tthrow e;\n\t\t}\n\t\telse {\n\t\t\ttry {\n\t\t\t\toutput = await this._generate(prompts, parsedOptions, runManagers?.[0]);\n\t\t\t} catch (err) {\n\t\t\t\tawait Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err)));\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tconst flattenedOutputs = this._flattenLLMResult(output);\n\t\t\tawait Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i])));\n\t\t}\n\t\tconst runIds = runManagers?.map((manager) => manager.runId) || void 0;\n\t\tObject.defineProperty(output, RUN_KEY, {\n\t\t\tvalue: runIds ? { runIds } : void 0,\n\t\t\tconfigurable: true\n\t\t});\n\t\treturn output;\n\t}\n\tasync _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, runId }) {\n\t\tconst callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose });\n\t\tconst extra = {\n\t\t\toptions: parsedOptions,\n\t\t\tinvocation_params: this?.invocationParams(parsedOptions),\n\t\t\tbatch_size: prompts.length\n\t\t};\n\t\tconst runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, void 0, extra, void 0, void 0, handledOptions?.runName);\n\t\tconst missingPromptIndices = [];\n\t\tconst results = await Promise.allSettled(prompts.map(async (prompt, index) => {\n\t\t\tconst result = await cache.lookup(prompt, llmStringKey);\n\t\t\tif (result == null) missingPromptIndices.push(index);\n\t\t\treturn result;\n\t\t}));\n\t\tconst cachedResults = results.map((result, index) => ({\n\t\t\tresult,\n\t\t\trunManager: runManagers?.[index]\n\t\t})).filter(({ result }) => result.status === \"fulfilled\" && result.value != null || result.status === \"rejected\");\n\t\tconst generations = [];\n\t\tawait Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => {\n\t\t\tif (promiseResult.status === \"fulfilled\") {\n\t\t\t\tconst result = promiseResult.value;\n\t\t\t\tgenerations[i] = result.map((result$1) => {\n\t\t\t\t\tresult$1.generationInfo = {\n\t\t\t\t\t\t...result$1.generationInfo,\n\t\t\t\t\t\ttokenUsage: {}\n\t\t\t\t\t};\n\t\t\t\t\treturn result$1;\n\t\t\t\t});\n\t\t\t\tif (result.length) await runManager?.handleLLMNewToken(result[0].text);\n\t\t\t\treturn runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true });\n\t\t\t} else {\n\t\t\t\tawait runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true });\n\t\t\t\treturn Promise.reject(promiseResult.reason);\n\t\t\t}\n\t\t}));\n\t\tconst output = {\n\t\t\tgenerations,\n\t\t\tmissingPromptIndices,\n\t\t\tstartedRunManagers: runManagers\n\t\t};\n\t\tObject.defineProperty(output, RUN_KEY, {\n\t\t\tvalue: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0,\n\t\t\tconfigurable: true\n\t\t});\n\t\treturn output;\n\t}\n\t/**\n\t* Run the LLM on the given prompts and input, handling caching.\n\t*/\n\tasync generate(prompts, options, callbacks) {\n\t\tif (!Array.isArray(prompts)) throw new Error(\"Argument 'prompts' is expected to be a string[]\");\n\t\tlet parsedOptions;\n\t\tif (Array.isArray(options)) parsedOptions = { stop: options };\n\t\telse parsedOptions = options;\n\t\tconst [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions);\n\t\trunnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;\n\t\tif (!this.cache) return this._generateUncached(prompts, callOptions, runnableConfig);\n\t\tconst { cache } = this;\n\t\tconst llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions);\n\t\tconst { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({\n\t\t\tprompts,\n\t\t\tcache,\n\t\t\tllmStringKey,\n\t\t\tparsedOptions: callOptions,\n\t\t\thandledOptions: runnableConfig,\n\t\t\trunId: runnableConfig.runId\n\t\t});\n\t\tlet llmOutput = {};\n\t\tif (missingPromptIndices.length > 0) {\n\t\t\tconst results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0);\n\t\t\tawait Promise.all(results.generations.map(async (generation, index) => {\n\t\t\t\tconst promptIndex = missingPromptIndices[index];\n\t\t\t\tgenerations[promptIndex] = generation;\n\t\t\t\treturn cache.update(prompts[promptIndex], llmStringKey, generation);\n\t\t\t}));\n\t\t\tllmOutput = results.llmOutput ?? {};\n\t\t}\n\t\treturn {\n\t\t\tgenerations,\n\t\t\tllmOutput\n\t\t};\n\t}\n\t/**\n\t* Get the identifying parameters of the LLM.\n\t*/\n\t_identifyingParams() {\n\t\treturn {};\n\t}\n\t_modelType() {\n\t\treturn \"base_llm\";\n\t}\n};\n/**\n* LLM class that provides a simpler interface to subclass than {@link BaseLLM}.\n*\n* Requires only implementing a simpler {@link _call} method instead of {@link _generate}.\n*\n* @augments BaseLLM\n*/\nvar LLM = class extends BaseLLM {\n\tasync _generate(prompts, options, runManager) {\n\t\tconst generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, {\n\t\t\t...options,\n\t\t\tpromptIndex\n\t\t}, runManager).then((text) => [{ text }])));\n\t\treturn { generations };\n\t}\n};\n\n//#endregion\nexport { BaseLLM, LLM, llms_exports };\n//# sourceMappingURL=llms.js.map","import { ensureConfig } from \"./config.js\";\nimport { Runnable } from \"./base.js\";\n\n//#region src/runnables/router.ts\n/**\n* A runnable that routes to a set of runnables based on Input['key'].\n* Returns the output of the selected runnable.\n* @example\n* ```typescript\n* import { RouterRunnable, RunnableLambda } from \"@langchain/core/runnables\";\n*\n* const router = new RouterRunnable({\n* runnables: {\n* toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()),\n* reverseText: RunnableLambda.from((text: string) =>\n* text.split(\"\").reverse().join(\"\")\n* ),\n* },\n* });\n*\n* // Invoke the 'reverseText' runnable\n* const result1 = router.invoke({ key: \"reverseText\", input: \"Hello World\" });\n*\n* // \"dlroW olleH\"\n*\n* // Invoke the 'toUpperCase' runnable\n* const result2 = router.invoke({ key: \"toUpperCase\", input: \"Hello World\" });\n*\n* // \"HELLO WORLD\"\n* ```\n*/\nvar RouterRunnable = class extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RouterRunnable\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\trunnables;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.runnables = fields.runnables;\n\t}\n\tasync invoke(input, options) {\n\t\tconst { key, input: actualInput } = input;\n\t\tconst runnable = this.runnables[key];\n\t\tif (runnable === void 0) throw new Error(`No runnable associated with key \"${key}\".`);\n\t\treturn runnable.invoke(actualInput, ensureConfig(options));\n\t}\n\tasync batch(inputs, options, batchOptions) {\n\t\tconst keys = inputs.map((input) => input.key);\n\t\tconst actualInputs = inputs.map((input) => input.input);\n\t\tconst missingKey = keys.find((key) => this.runnables[key] === void 0);\n\t\tif (missingKey !== void 0) throw new Error(`One or more keys do not have a corresponding runnable.`);\n\t\tconst runnables = keys.map((key) => this.runnables[key]);\n\t\tconst optionsList = this._getOptionsList(options ?? {}, inputs.length);\n\t\tconst maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;\n\t\tconst batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length;\n\t\tconst batchResults = [];\n\t\tfor (let i = 0; i < actualInputs.length; i += batchSize) {\n\t\t\tconst batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i$1) => runnables[i$1].invoke(actualInput, optionsList[i$1]));\n\t\t\tconst batchResult = await Promise.all(batchPromises);\n\t\t\tbatchResults.push(batchResult);\n\t\t}\n\t\treturn batchResults.flat();\n\t}\n\tasync stream(input, options) {\n\t\tconst { key, input: actualInput } = input;\n\t\tconst runnable = this.runnables[key];\n\t\tif (runnable === void 0) throw new Error(`No runnable associated with key \"${key}\".`);\n\t\treturn runnable.stream(actualInput, options);\n\t}\n};\n\n//#endregion\nexport { RouterRunnable };\n//# sourceMappingURL=router.js.map","import { getCallbackManagerForConfig, patchConfig } from \"./config.js\";\nimport { concat } from \"../utils/stream.js\";\nimport { Runnable, _coerceToDict, _coerceToRunnable } from \"./base.js\";\n\n//#region src/runnables/branch.ts\n/**\n* Class that represents a runnable branch. The RunnableBranch is\n* initialized with an array of branches and a default branch. When invoked,\n* it evaluates the condition of each branch in order and executes the\n* corresponding branch if the condition is true. If none of the conditions\n* are true, it executes the default branch.\n* @example\n* ```typescript\n* const branch = RunnableBranch.from([\n* [\n* (x: { topic: string; question: string }) =>\n* x.topic.toLowerCase().includes(\"anthropic\"),\n* anthropicChain,\n* ],\n* [\n* (x: { topic: string; question: string }) =>\n* x.topic.toLowerCase().includes(\"langchain\"),\n* langChainChain,\n* ],\n* generalChain,\n* ]);\n*\n* const fullChain = RunnableSequence.from([\n* {\n* topic: classificationChain,\n* question: (input: { question: string }) => input.question,\n* },\n* branch,\n* ]);\n*\n* const result = await fullChain.invoke({\n* question: \"how do I use LangChain?\",\n* });\n* ```\n*/\nvar RunnableBranch = class extends Runnable {\n\tstatic lc_name() {\n\t\treturn \"RunnableBranch\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"runnables\"];\n\tlc_serializable = true;\n\tdefault;\n\tbranches;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.branches = fields.branches;\n\t\tthis.default = fields.default;\n\t}\n\t/**\n\t* Convenience method for instantiating a RunnableBranch from\n\t* RunnableLikes (objects, functions, or Runnables).\n\t*\n\t* Each item in the input except for the last one should be a\n\t* tuple with two items. The first is a \"condition\" RunnableLike that\n\t* returns \"true\" if the second RunnableLike in the tuple should run.\n\t*\n\t* The final item in the input should be a RunnableLike that acts as a\n\t* default branch if no other branches match.\n\t*\n\t* @example\n\t* ```ts\n\t* import { RunnableBranch } from \"@langchain/core/runnables\";\n\t*\n\t* const branch = RunnableBranch.from([\n\t* [(x: number) => x > 0, (x: number) => x + 1],\n\t* [(x: number) => x < 0, (x: number) => x - 1],\n\t* (x: number) => x\n\t* ]);\n\t* ```\n\t* @param branches An array where the every item except the last is a tuple of [condition, runnable]\n\t* pairs. The last item is a default runnable which is invoked if no other condition matches.\n\t* @returns A new RunnableBranch.\n\t*/\n\tstatic from(branches) {\n\t\tif (branches.length < 1) throw new Error(\"RunnableBranch requires at least one branch\");\n\t\tconst branchLikes = branches.slice(0, -1);\n\t\tconst coercedBranches = branchLikes.map(([condition, runnable]) => [_coerceToRunnable(condition), _coerceToRunnable(runnable)]);\n\t\tconst defaultBranch = _coerceToRunnable(branches[branches.length - 1]);\n\t\treturn new this({\n\t\t\tbranches: coercedBranches,\n\t\t\tdefault: defaultBranch\n\t\t});\n\t}\n\tasync _invoke(input, config, runManager) {\n\t\tlet result;\n\t\tfor (let i = 0; i < this.branches.length; i += 1) {\n\t\t\tconst [condition, branchRunnable] = this.branches[i];\n\t\t\tconst conditionValue = await condition.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) }));\n\t\t\tif (conditionValue) {\n\t\t\t\tresult = await branchRunnable.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) }));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!result) result = await this.default.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(\"branch:default\") }));\n\t\treturn result;\n\t}\n\tasync invoke(input, config = {}) {\n\t\treturn this._callWithConfig(this._invoke, input, config);\n\t}\n\tasync *_streamIterator(input, config) {\n\t\tconst callbackManager_ = await getCallbackManagerForConfig(config);\n\t\tconst runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), config?.runId, void 0, void 0, void 0, config?.runName);\n\t\tlet finalOutput;\n\t\tlet finalOutputSupported = true;\n\t\tlet stream;\n\t\ttry {\n\t\t\tfor (let i = 0; i < this.branches.length; i += 1) {\n\t\t\t\tconst [condition, branchRunnable] = this.branches[i];\n\t\t\t\tconst conditionValue = await condition.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) }));\n\t\t\t\tif (conditionValue) {\n\t\t\t\t\tstream = await branchRunnable.stream(input, patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) }));\n\t\t\t\t\tfor await (const chunk of stream) {\n\t\t\t\t\t\tyield chunk;\n\t\t\t\t\t\tif (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk;\n\t\t\t\t\t\telse try {\n\t\t\t\t\t\t\tfinalOutput = concat(finalOutput, chunk);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tfinalOutput = void 0;\n\t\t\t\t\t\t\tfinalOutputSupported = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (stream === void 0) {\n\t\t\t\tstream = await this.default.stream(input, patchConfig(config, { callbacks: runManager?.getChild(\"branch:default\") }));\n\t\t\t\tfor await (const chunk of stream) {\n\t\t\t\t\tyield chunk;\n\t\t\t\t\tif (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk;\n\t\t\t\t\telse try {\n\t\t\t\t\t\tfinalOutput = concat(finalOutput, chunk);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tfinalOutput = void 0;\n\t\t\t\t\t\tfinalOutputSupported = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tawait runManager?.handleChainEnd(finalOutput ?? {});\n\t}\n};\n\n//#endregion\nexport { RunnableBranch };\n//# sourceMappingURL=branch.js.map","import { isBaseMessage } from \"../messages/base.js\";\nimport { AIMessage } from \"../messages/ai.js\";\nimport { HumanMessage } from \"../messages/human.js\";\nimport { RunnableBinding, RunnableLambda } from \"./base.js\";\nimport \"../messages/index.js\";\nimport { RunnablePassthrough } from \"./passthrough.js\";\n\n//#region src/runnables/history.ts\n/**\n* Wraps a LCEL chain and manages history. It appends input messages\n* and chain outputs as history, and adds the current history messages to\n* the chain input.\n* @example\n* ```typescript\n* // pnpm install @langchain/anthropic @langchain/community @upstash/redis\n*\n* import {\n* ChatPromptTemplate,\n* MessagesPlaceholder,\n* } from \"@langchain/core/prompts\";\n* import { ChatAnthropic } from \"@langchain/anthropic\";\n* import { UpstashRedisChatMessageHistory } from \"@langchain/community/stores/message/upstash_redis\";\n* // For demos, you can also use an in-memory store:\n* // import { ChatMessageHistory } from \"@langchain/classic/stores/message/in_memory\";\n*\n* const prompt = ChatPromptTemplate.fromMessages([\n* [\"system\", \"You're an assistant who's good at {ability}\"],\n* new MessagesPlaceholder(\"history\"),\n* [\"human\", \"{question}\"],\n* ]);\n*\n* const chain = prompt.pipe(new ChatAnthropic({}));\n*\n* const chainWithHistory = new RunnableWithMessageHistory({\n* runnable: chain,\n* getMessageHistory: (sessionId) =>\n* new UpstashRedisChatMessageHistory({\n* sessionId,\n* config: {\n* url: process.env.UPSTASH_REDIS_REST_URL!,\n* token: process.env.UPSTASH_REDIS_REST_TOKEN!,\n* },\n* }),\n* inputMessagesKey: \"question\",\n* historyMessagesKey: \"history\",\n* });\n*\n* const result = await chainWithHistory.invoke(\n* {\n* ability: \"math\",\n* question: \"What does cosine mean?\",\n* },\n* {\n* configurable: {\n* sessionId: \"some_string_identifying_a_user\",\n* },\n* }\n* );\n*\n* const result2 = await chainWithHistory.invoke(\n* {\n* ability: \"math\",\n* question: \"What's its inverse?\",\n* },\n* {\n* configurable: {\n* sessionId: \"some_string_identifying_a_user\",\n* },\n* }\n* );\n* ```\n*/\nvar RunnableWithMessageHistory = class extends RunnableBinding {\n\trunnable;\n\tinputMessagesKey;\n\toutputMessagesKey;\n\thistoryMessagesKey;\n\tgetMessageHistory;\n\tconstructor(fields) {\n\t\tlet historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: \"loadHistory\" });\n\t\tconst messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey;\n\t\tif (messagesKey) historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: \"insertHistory\" });\n\t\tconst bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run, config$1) => this._exitHistory(run, config$1 ?? {}) })).withConfig({ runName: \"RunnableWithMessageHistory\" });\n\t\tconst config = fields.config ?? {};\n\t\tsuper({\n\t\t\t...fields,\n\t\t\tconfig,\n\t\t\tbound\n\t\t});\n\t\tthis.runnable = fields.runnable;\n\t\tthis.getMessageHistory = fields.getMessageHistory;\n\t\tthis.inputMessagesKey = fields.inputMessagesKey;\n\t\tthis.outputMessagesKey = fields.outputMessagesKey;\n\t\tthis.historyMessagesKey = fields.historyMessagesKey;\n\t}\n\t_getInputMessages(inputValue) {\n\t\tlet parsedInputValue;\n\t\tif (typeof inputValue === \"object\" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) {\n\t\t\tlet key;\n\t\t\tif (this.inputMessagesKey) key = this.inputMessagesKey;\n\t\t\telse if (Object.keys(inputValue).length === 1) key = Object.keys(inputValue)[0];\n\t\t\telse key = \"input\";\n\t\t\tif (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) parsedInputValue = inputValue[key][0];\n\t\t\telse parsedInputValue = inputValue[key];\n\t\t} else parsedInputValue = inputValue;\n\t\tif (typeof parsedInputValue === \"string\") return [new HumanMessage(parsedInputValue)];\n\t\telse if (Array.isArray(parsedInputValue)) return parsedInputValue;\n\t\telse if (isBaseMessage(parsedInputValue)) return [parsedInputValue];\n\t\telse throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\\nGot ${JSON.stringify(parsedInputValue, null, 2)}`);\n\t}\n\t_getOutputMessages(outputValue) {\n\t\tlet parsedOutputValue;\n\t\tif (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== \"string\") {\n\t\t\tlet key;\n\t\t\tif (this.outputMessagesKey !== void 0) key = this.outputMessagesKey;\n\t\t\telse if (Object.keys(outputValue).length === 1) key = Object.keys(outputValue)[0];\n\t\t\telse key = \"output\";\n\t\t\tif (outputValue.generations !== void 0) parsedOutputValue = outputValue.generations[0][0].message;\n\t\t\telse parsedOutputValue = outputValue[key];\n\t\t} else parsedOutputValue = outputValue;\n\t\tif (typeof parsedOutputValue === \"string\") return [new AIMessage(parsedOutputValue)];\n\t\telse if (Array.isArray(parsedOutputValue)) return parsedOutputValue;\n\t\telse if (isBaseMessage(parsedOutputValue)) return [parsedOutputValue];\n\t\telse throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`);\n\t}\n\tasync _enterHistory(input, kwargs) {\n\t\tconst history = kwargs?.configurable?.messageHistory;\n\t\tconst messages = await history.getMessages();\n\t\tif (this.historyMessagesKey === void 0) return messages.concat(this._getInputMessages(input));\n\t\treturn messages;\n\t}\n\tasync _exitHistory(run, config) {\n\t\tconst history = config.configurable?.messageHistory;\n\t\tlet inputs;\n\t\tif (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) inputs = run.inputs[0];\n\t\telse inputs = run.inputs;\n\t\tlet inputMessages = this._getInputMessages(inputs);\n\t\tif (this.historyMessagesKey === void 0) {\n\t\t\tconst existingMessages = await history.getMessages();\n\t\t\tinputMessages = inputMessages.slice(existingMessages.length);\n\t\t}\n\t\tconst outputValue = run.outputs;\n\t\tif (!outputValue) throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`);\n\t\tconst outputMessages = this._getOutputMessages(outputValue);\n\t\tawait history.addMessages([...inputMessages, ...outputMessages]);\n\t}\n\tasync _mergeConfig(...configs) {\n\t\tconst config = await super._mergeConfig(...configs);\n\t\tif (!config.configurable || !config.configurable.sessionId) {\n\t\t\tconst exampleInput = { [this.inputMessagesKey ?? \"input\"]: \"foo\" };\n\t\t\tconst exampleConfig = { configurable: { sessionId: \"123\" } };\n\t\t\tthrow new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\\neg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`);\n\t\t}\n\t\tconst { sessionId } = config.configurable;\n\t\tconfig.configurable.messageHistory = await this.getMessageHistory(sessionId);\n\t\treturn config;\n\t}\n};\n\n//#endregion\nexport { RunnableWithMessageHistory };\n//# sourceMappingURL=history.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys } from \"./config.js\";\nimport { Runnable, RunnableAssign, RunnableBinding, RunnableEach, RunnableLambda, RunnableMap, RunnableParallel, RunnablePick, RunnableRetry, RunnableSequence, RunnableToolLike, RunnableWithFallbacks, _coerceToRunnable } from \"./base.js\";\nimport { RunnablePassthrough } from \"./passthrough.js\";\nimport { RouterRunnable } from \"./router.js\";\nimport { RunnableBranch } from \"./branch.js\";\nimport { RunnableWithMessageHistory } from \"./history.js\";\n\n//#region src/runnables/index.ts\nvar runnables_exports = {};\n__export(runnables_exports, {\n\tRouterRunnable: () => RouterRunnable,\n\tRunnable: () => Runnable,\n\tRunnableAssign: () => RunnableAssign,\n\tRunnableBinding: () => RunnableBinding,\n\tRunnableBranch: () => RunnableBranch,\n\tRunnableEach: () => RunnableEach,\n\tRunnableLambda: () => RunnableLambda,\n\tRunnableMap: () => RunnableMap,\n\tRunnableParallel: () => RunnableParallel,\n\tRunnablePassthrough: () => RunnablePassthrough,\n\tRunnablePick: () => RunnablePick,\n\tRunnableRetry: () => RunnableRetry,\n\tRunnableSequence: () => RunnableSequence,\n\tRunnableToolLike: () => RunnableToolLike,\n\tRunnableWithFallbacks: () => RunnableWithFallbacks,\n\tRunnableWithMessageHistory: () => RunnableWithMessageHistory,\n\t_coerceToRunnable: () => _coerceToRunnable,\n\tensureConfig: () => ensureConfig,\n\tgetCallbackManagerForConfig: () => getCallbackManagerForConfig,\n\tmergeConfigs: () => mergeConfigs,\n\tpatchConfig: () => patchConfig,\n\tpickRunnableConfigKeys: () => pickRunnableConfigKeys\n});\n\n//#endregion\nexport { RouterRunnable, Runnable, RunnableAssign, RunnableBinding, RunnableBranch, RunnableEach, RunnableLambda, RunnableMap, RunnableParallel, RunnablePassthrough, RunnablePick, RunnableRetry, RunnableSequence, RunnableToolLike, RunnableWithFallbacks, RunnableWithMessageHistory, _coerceToRunnable, ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys, runnables_exports };\n//# sourceMappingURL=index.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { applyPatch } from \"./fast-json-patch/src/core.js\";\nimport { compare } from \"./fast-json-patch/src/duplex.js\";\nimport \"./fast-json-patch/index.js\";\n\n//#region src/utils/json_patch.ts\nvar json_patch_exports = {};\n__export(json_patch_exports, {\n\tapplyPatch: () => applyPatch,\n\tcompare: () => compare\n});\n\n//#endregion\nexport { applyPatch, compare, json_patch_exports };\n//# sourceMappingURL=json_patch.js.map","import { addLangChainErrorFields } from \"../errors/index.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport \"../runnables/index.js\";\n\n//#region src/output_parsers/base.ts\n/**\n* Abstract base class for parsing the output of a Large Language Model\n* (LLM) call. It provides methods for parsing the result of an LLM call\n* and invoking the parser with a given input.\n*/\nvar BaseLLMOutputParser = class extends Runnable {\n\t/**\n\t* Parses the result of an LLM call with a given prompt. By default, it\n\t* simply calls `parseResult`.\n\t* @param generations The generations from an LLM call.\n\t* @param _prompt The prompt used in the LLM call.\n\t* @param callbacks Optional callbacks.\n\t* @returns A promise of the parsed output.\n\t*/\n\tparseResultWithPrompt(generations, _prompt, callbacks) {\n\t\treturn this.parseResult(generations, callbacks);\n\t}\n\t_baseMessageToString(message) {\n\t\treturn typeof message.content === \"string\" ? message.content : this._baseMessageContentToString(message.content);\n\t}\n\t_baseMessageContentToString(content) {\n\t\treturn JSON.stringify(content);\n\t}\n\t/**\n\t* Calls the parser with a given input and optional configuration options.\n\t* If the input is a string, it creates a generation with the input as\n\t* text and calls `parseResult`. If the input is a `BaseMessage`, it\n\t* creates a generation with the input as a message and the content of the\n\t* input as text, and then calls `parseResult`.\n\t* @param input The input to the parser, which can be a string or a `BaseMessage`.\n\t* @param options Optional configuration options.\n\t* @returns A promise of the parsed output.\n\t*/\n\tasync invoke(input, options) {\n\t\tif (typeof input === \"string\") return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ text: input$1 }], options$1?.callbacks), input, {\n\t\t\t...options,\n\t\t\trunType: \"parser\"\n\t\t});\n\t\telse return this._callWithConfig(async (input$1, options$1) => this.parseResult([{\n\t\t\tmessage: input$1,\n\t\t\ttext: this._baseMessageToString(input$1)\n\t\t}], options$1?.callbacks), input, {\n\t\t\t...options,\n\t\t\trunType: \"parser\"\n\t\t});\n\t}\n};\n/**\n* Class to parse the output of an LLM call.\n*/\nvar BaseOutputParser = class extends BaseLLMOutputParser {\n\tparseResult(generations, callbacks) {\n\t\treturn this.parse(generations[0].text, callbacks);\n\t}\n\tasync parseWithPrompt(text, _prompt, callbacks) {\n\t\treturn this.parse(text, callbacks);\n\t}\n\t/**\n\t* Return the string type key uniquely identifying this class of parser\n\t*/\n\t_type() {\n\t\tthrow new Error(\"_type not implemented\");\n\t}\n};\n/**\n* Exception that output parsers should raise to signify a parsing error.\n*\n* This exists to differentiate parsing errors from other code or execution errors\n* that also may arise inside the output parser. OutputParserExceptions will be\n* available to catch and handle in ways to fix the parsing error, while other\n* errors will be raised.\n*\n* @param message - The error that's being re-raised or an error message.\n* @param llmOutput - String model output which is error-ing.\n* @param observation - String explanation of error which can be passed to a\n* model to try and remediate the issue.\n* @param sendToLLM - Whether to send the observation and llm_output back to an Agent\n* after an OutputParserException has been raised. This gives the underlying\n* model driving the agent the context that the previous output was improperly\n* structured, in the hopes that it will update the output to the correct\n* format.\n*/\nvar OutputParserException = class extends Error {\n\tllmOutput;\n\tobservation;\n\tsendToLLM;\n\tconstructor(message, llmOutput, observation, sendToLLM = false) {\n\t\tsuper(message);\n\t\tthis.llmOutput = llmOutput;\n\t\tthis.observation = observation;\n\t\tthis.sendToLLM = sendToLLM;\n\t\tif (sendToLLM) {\n\t\t\tif (observation === void 0 || llmOutput === void 0) throw new Error(\"Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true\");\n\t\t}\n\t\taddLangChainErrorFields(this, \"OUTPUT_PARSING_FAILURE\");\n\t}\n};\n\n//#endregion\nexport { BaseLLMOutputParser, BaseOutputParser, OutputParserException };\n//# sourceMappingURL=base.js.map","import { isBaseMessage, isBaseMessageChunk } from \"../messages/base.js\";\nimport { convertToChunk } from \"../messages/utils.js\";\nimport { ChatGenerationChunk, GenerationChunk } from \"../outputs.js\";\nimport { BaseOutputParser } from \"./base.js\";\nimport { deepCompareStrict } from \"@cfworker/json-schema\";\n\n//#region src/output_parsers/transform.ts\n/**\n* Class to parse the output of an LLM call that also allows streaming inputs.\n*/\nvar BaseTransformOutputParser = class extends BaseOutputParser {\n\tasync *_transform(inputGenerator) {\n\t\tfor await (const chunk of inputGenerator) if (typeof chunk === \"string\") yield this.parseResult([{ text: chunk }]);\n\t\telse yield this.parseResult([{\n\t\t\tmessage: chunk,\n\t\t\ttext: this._baseMessageToString(chunk)\n\t\t}]);\n\t}\n\t/**\n\t* Transforms an asynchronous generator of input into an asynchronous\n\t* generator of parsed output.\n\t* @param inputGenerator An asynchronous generator of input.\n\t* @param options A configuration object.\n\t* @returns An asynchronous generator of parsed output.\n\t*/\n\tasync *transform(inputGenerator, options) {\n\t\tyield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), {\n\t\t\t...options,\n\t\t\trunType: \"parser\"\n\t\t});\n\t}\n};\n/**\n* A base class for output parsers that can handle streaming input. It\n* extends the `BaseTransformOutputParser` class and provides a method for\n* converting parsed outputs into a diff format.\n*/\nvar BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser {\n\tdiff = false;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.diff = fields?.diff ?? this.diff;\n\t}\n\tasync *_transform(inputGenerator) {\n\t\tlet prevParsed;\n\t\tlet accGen;\n\t\tfor await (const chunk of inputGenerator) {\n\t\t\tif (typeof chunk !== \"string\" && typeof chunk.content !== \"string\") throw new Error(\"Cannot handle non-string output.\");\n\t\t\tlet chunkGen;\n\t\t\tif (isBaseMessageChunk(chunk)) {\n\t\t\t\tif (typeof chunk.content !== \"string\") throw new Error(\"Cannot handle non-string message output.\");\n\t\t\t\tchunkGen = new ChatGenerationChunk({\n\t\t\t\t\tmessage: chunk,\n\t\t\t\t\ttext: chunk.content\n\t\t\t\t});\n\t\t\t} else if (isBaseMessage(chunk)) {\n\t\t\t\tif (typeof chunk.content !== \"string\") throw new Error(\"Cannot handle non-string message output.\");\n\t\t\t\tchunkGen = new ChatGenerationChunk({\n\t\t\t\t\tmessage: convertToChunk(chunk),\n\t\t\t\t\ttext: chunk.content\n\t\t\t\t});\n\t\t\t} else chunkGen = new GenerationChunk({ text: chunk });\n\t\t\tif (accGen === void 0) accGen = chunkGen;\n\t\t\telse accGen = accGen.concat(chunkGen);\n\t\t\tconst parsed = await this.parsePartialResult([accGen]);\n\t\t\tif (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) {\n\t\t\t\tif (this.diff) yield this._diff(prevParsed, parsed);\n\t\t\t\telse yield parsed;\n\t\t\t\tprevParsed = parsed;\n\t\t\t}\n\t\t}\n\t}\n\tgetFormatInstructions() {\n\t\treturn \"\";\n\t}\n};\n\n//#endregion\nexport { BaseCumulativeTransformOutputParser, BaseTransformOutputParser };\n//# sourceMappingURL=transform.js.map","import { BaseTransformOutputParser } from \"./transform.js\";\n\n//#region src/output_parsers/bytes.ts\n/**\n* OutputParser that parses LLMResult into the top likely string and\n* encodes it into bytes.\n*/\nvar BytesOutputParser = class extends BaseTransformOutputParser {\n\tstatic lc_name() {\n\t\treturn \"BytesOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"output_parsers\",\n\t\t\"bytes\"\n\t];\n\tlc_serializable = true;\n\ttextEncoder = new TextEncoder();\n\tparse(text) {\n\t\treturn Promise.resolve(this.textEncoder.encode(text));\n\t}\n\tgetFormatInstructions() {\n\t\treturn \"\";\n\t}\n};\n\n//#endregion\nexport { BytesOutputParser };\n//# sourceMappingURL=bytes.js.map","import { OutputParserException } from \"./base.js\";\nimport { BaseTransformOutputParser } from \"./transform.js\";\n\n//#region src/output_parsers/list.ts\n/**\n* Class to parse the output of an LLM call to a list.\n* @augments BaseOutputParser\n*/\nvar ListOutputParser = class extends BaseTransformOutputParser {\n\tre;\n\tasync *_transform(inputGenerator) {\n\t\tlet buffer = \"\";\n\t\tfor await (const input of inputGenerator) {\n\t\t\tif (typeof input === \"string\") buffer += input;\n\t\t\telse buffer += input.content;\n\t\t\tif (!this.re) {\n\t\t\t\tconst parts = await this.parse(buffer);\n\t\t\t\tif (parts.length > 1) {\n\t\t\t\t\tfor (const part of parts.slice(0, -1)) yield [part];\n\t\t\t\t\tbuffer = parts[parts.length - 1];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst matches = [...buffer.matchAll(this.re)];\n\t\t\t\tif (matches.length > 1) {\n\t\t\t\t\tlet doneIdx = 0;\n\t\t\t\t\tfor (const match of matches.slice(0, -1)) {\n\t\t\t\t\t\tyield [match[1]];\n\t\t\t\t\t\tdoneIdx += (match.index ?? 0) + match[0].length;\n\t\t\t\t\t}\n\t\t\t\t\tbuffer = buffer.slice(doneIdx);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const part of await this.parse(buffer)) yield [part];\n\t}\n};\n/**\n* Class to parse the output of an LLM call as a comma-separated list.\n* @augments ListOutputParser\n*/\nvar CommaSeparatedListOutputParser = class extends ListOutputParser {\n\tstatic lc_name() {\n\t\treturn \"CommaSeparatedListOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"output_parsers\",\n\t\t\"list\"\n\t];\n\tlc_serializable = true;\n\t/**\n\t* Parses the given text into an array of strings, using a comma as the\n\t* separator. If the parsing fails, throws an OutputParserException.\n\t* @param text The text to parse.\n\t* @returns An array of strings obtained by splitting the input text at each comma.\n\t*/\n\tasync parse(text) {\n\t\ttry {\n\t\t\treturn text.trim().split(\",\").map((s) => s.trim());\n\t\t} catch {\n\t\t\tthrow new OutputParserException(`Could not parse output: ${text}`, text);\n\t\t}\n\t}\n\t/**\n\t* Provides instructions on the expected format of the response for the\n\t* CommaSeparatedListOutputParser.\n\t* @returns A string containing instructions on the expected format of the response.\n\t*/\n\tgetFormatInstructions() {\n\t\treturn `Your response should be a list of comma separated values, eg: \\`foo, bar, baz\\``;\n\t}\n};\n/**\n* Class to parse the output of an LLM call to a list with a specific length and separator.\n* @augments ListOutputParser\n*/\nvar CustomListOutputParser = class extends ListOutputParser {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"output_parsers\",\n\t\t\"list\"\n\t];\n\tlength;\n\tseparator;\n\tconstructor({ length, separator }) {\n\t\tsuper(...arguments);\n\t\tthis.length = length;\n\t\tthis.separator = separator || \",\";\n\t}\n\t/**\n\t* Parses the given text into an array of strings, using the specified\n\t* separator. If the parsing fails or the number of items in the list\n\t* doesn't match the expected length, throws an OutputParserException.\n\t* @param text The text to parse.\n\t* @returns An array of strings obtained by splitting the input text at each occurrence of the specified separator.\n\t*/\n\tasync parse(text) {\n\t\ttry {\n\t\t\tconst items = text.trim().split(this.separator).map((s) => s.trim());\n\t\t\tif (this.length !== void 0 && items.length !== this.length) throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`);\n\t\t\treturn items;\n\t\t} catch (e) {\n\t\t\tif (Object.getPrototypeOf(e) === OutputParserException.prototype) throw e;\n\t\t\tthrow new OutputParserException(`Could not parse output: ${text}`);\n\t\t}\n\t}\n\t/**\n\t* Provides instructions on the expected format of the response for the\n\t* CustomListOutputParser, including the number of items and the\n\t* separator.\n\t* @returns A string containing instructions on the expected format of the response.\n\t*/\n\tgetFormatInstructions() {\n\t\treturn `Your response should be a list of ${this.length === void 0 ? \"\" : `${this.length} `}items separated by \"${this.separator}\" (eg: \\`foo${this.separator} bar${this.separator} baz\\`)`;\n\t}\n};\nvar NumberedListOutputParser = class extends ListOutputParser {\n\tstatic lc_name() {\n\t\treturn \"NumberedListOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"output_parsers\",\n\t\t\"list\"\n\t];\n\tlc_serializable = true;\n\tgetFormatInstructions() {\n\t\treturn `Your response should be a numbered list with each item on a new line. For example: \\n\\n1. foo\\n\\n2. bar\\n\\n3. baz`;\n\t}\n\tre = /\\d+\\.\\s([^\\n]+)/g;\n\tasync parse(text) {\n\t\treturn [...text.matchAll(this.re) ?? []].map((m) => m[1]);\n\t}\n};\nvar MarkdownListOutputParser = class extends ListOutputParser {\n\tstatic lc_name() {\n\t\treturn \"NumberedListOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"output_parsers\",\n\t\t\"list\"\n\t];\n\tlc_serializable = true;\n\tgetFormatInstructions() {\n\t\treturn `Your response should be a numbered list with each item on a new line. For example: \\n\\n1. foo\\n\\n2. bar\\n\\n3. baz`;\n\t}\n\tre = /^\\s*[-*]\\s([^\\n]+)$/gm;\n\tasync parse(text) {\n\t\treturn [...text.matchAll(this.re) ?? []].map((m) => m[1]);\n\t}\n};\n\n//#endregion\nexport { CommaSeparatedListOutputParser, CustomListOutputParser, ListOutputParser, MarkdownListOutputParser, NumberedListOutputParser };\n//# sourceMappingURL=list.js.map","import { BaseTransformOutputParser } from \"./transform.js\";\n\n//#region src/output_parsers/string.ts\n/**\n* OutputParser that parses LLMResult into the top likely string.\n* @example\n* ```typescript\n* const promptTemplate = PromptTemplate.fromTemplate(\n* \"Tell me a joke about {topic}\",\n* );\n*\n* const chain = RunnableSequence.from([\n* promptTemplate,\n* new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n* new StringOutputParser(),\n* ]);\n*\n* const result = await chain.invoke({ topic: \"bears\" });\n* console.log(\"What do you call a bear with no teeth? A gummy bear!\");\n* ```\n*/\nvar StringOutputParser = class extends BaseTransformOutputParser {\n\tstatic lc_name() {\n\t\treturn \"StrOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"output_parsers\",\n\t\t\"string\"\n\t];\n\tlc_serializable = true;\n\t/**\n\t* Parses a string output from an LLM call. This method is meant to be\n\t* implemented by subclasses to define how a string output from an LLM\n\t* should be parsed.\n\t* @param text The string output from an LLM call.\n\t* @param callbacks Optional callbacks.\n\t* @returns A promise of the parsed output.\n\t*/\n\tparse(text) {\n\t\treturn Promise.resolve(text);\n\t}\n\tgetFormatInstructions() {\n\t\treturn \"\";\n\t}\n\t_textContentToString(content) {\n\t\treturn content.text;\n\t}\n\t_imageUrlContentToString(_content) {\n\t\tthrow new Error(`Cannot coerce a multimodal \"image_url\" message part into a string.`);\n\t}\n\t_messageContentToString(content) {\n\t\tswitch (content.type) {\n\t\t\tcase \"text\":\n\t\t\tcase \"text_delta\":\n\t\t\t\tif (\"text\" in content) return this._textContentToString(content);\n\t\t\t\tbreak;\n\t\t\tcase \"image_url\":\n\t\t\t\tif (\"image_url\" in content) return this._imageUrlContentToString(content);\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Cannot coerce \"${content.type}\" message part into a string.`);\n\t\t}\n\t\tthrow new Error(`Invalid content type: ${content.type}`);\n\t}\n\t_baseMessageContentToString(content) {\n\t\treturn content.reduce((acc, item) => acc + this._messageContentToString(item), \"\");\n\t}\n};\n\n//#endregion\nexport { StringOutputParser };\n//# sourceMappingURL=string.js.map","import { interopParseAsync } from \"../utils/types/zod.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\nimport { BaseOutputParser, OutputParserException } from \"./base.js\";\nimport { z } from \"zod/v3\";\n\n//#region src/output_parsers/structured.ts\nvar StructuredOutputParser = class extends BaseOutputParser {\n\tstatic lc_name() {\n\t\treturn \"StructuredOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"output_parsers\",\n\t\t\"structured\"\n\t];\n\ttoJSON() {\n\t\treturn this.toJSONNotImplemented();\n\t}\n\tconstructor(schema) {\n\t\tsuper(schema);\n\t\tthis.schema = schema;\n\t}\n\t/**\n\t* Creates a new StructuredOutputParser from a Zod schema.\n\t* @param schema The Zod schema which the output should match\n\t* @returns A new instance of StructuredOutputParser.\n\t*/\n\tstatic fromZodSchema(schema) {\n\t\treturn new this(schema);\n\t}\n\t/**\n\t* Creates a new StructuredOutputParser from a set of names and\n\t* descriptions.\n\t* @param schemas An object where each key is a name and each value is a description\n\t* @returns A new instance of StructuredOutputParser.\n\t*/\n\tstatic fromNamesAndDescriptions(schemas) {\n\t\tconst zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)])));\n\t\treturn new this(zodSchema);\n\t}\n\t/**\n\t* Returns a markdown code snippet with a JSON object formatted according\n\t* to the schema.\n\t* @param options Optional. The options for formatting the instructions\n\t* @returns A markdown code snippet with a JSON object formatted according to the schema.\n\t*/\n\tgetFormatInstructions() {\n\t\treturn `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n\t}\n\t/**\n\t* Parses the given text according to the schema.\n\t* @param text The text to parse\n\t* @returns The parsed output.\n\t*/\n\tasync parse(text) {\n\t\ttry {\n\t\t\tconst trimmedText = text.trim();\n\t\t\tconst json = trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] || trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] || trimmedText;\n\t\t\tconst escapedJson = json.replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n\t\t\t\tconst escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n\t\t\t\treturn `\"${escapedInsideQuotes}\"`;\n\t\t\t}).replace(/\\n/g, \"\");\n\t\t\treturn await interopParseAsync(this.schema, JSON.parse(escapedJson));\n\t\t} catch (e) {\n\t\t\tthrow new OutputParserException(`Failed to parse. Text: \"${text}\". Error: ${e}`, text);\n\t\t}\n\t}\n};\n/**\n* A specific type of `StructuredOutputParser` that parses JSON data\n* formatted as a markdown code snippet.\n*/\nvar JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser {\n\tstatic lc_name() {\n\t\treturn \"JsonMarkdownStructuredOutputParser\";\n\t}\n\tgetFormatInstructions(options) {\n\t\tconst interpolationDepth = options?.interpolationDepth ?? 1;\n\t\tif (interpolationDepth < 1) throw new Error(\"f string interpolation depth must be at least 1\");\n\t\treturn `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll(\"{\", \"{\".repeat(interpolationDepth)).replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n\t}\n\t_schemaToInstruction(schemaInput, indent = 2) {\n\t\tconst schema = schemaInput;\n\t\tif (\"type\" in schema) {\n\t\t\tlet nullable = false;\n\t\t\tlet type;\n\t\t\tif (Array.isArray(schema.type)) {\n\t\t\t\tconst nullIdx = schema.type.findIndex((type$1) => type$1 === \"null\");\n\t\t\t\tif (nullIdx !== -1) {\n\t\t\t\t\tnullable = true;\n\t\t\t\t\tschema.type.splice(nullIdx, 1);\n\t\t\t\t}\n\t\t\t\ttype = schema.type.join(\" | \");\n\t\t\t} else type = schema.type;\n\t\t\tif (schema.type === \"object\" && schema.properties) {\n\t\t\t\tconst description$1 = schema.description ? ` // ${schema.description}` : \"\";\n\t\t\t\tconst properties = Object.entries(schema.properties).map(([key, value]) => {\n\t\t\t\t\tconst isOptional = schema.required?.includes(key) ? \"\" : \" (optional)\";\n\t\t\t\t\treturn `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`;\n\t\t\t\t}).join(\"\\n\");\n\t\t\t\treturn `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description$1}`;\n\t\t\t}\n\t\t\tif (schema.type === \"array\" && schema.items) {\n\t\t\t\tconst description$1 = schema.description ? ` // ${schema.description}` : \"\";\n\t\t\t\treturn `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\\n${\" \".repeat(indent - 2)}] ${description$1}`;\n\t\t\t}\n\t\t\tconst isNullable = nullable ? \" (nullable)\" : \"\";\n\t\t\tconst description = schema.description ? ` // ${schema.description}` : \"\";\n\t\t\treturn `${type}${description}${isNullable}`;\n\t\t}\n\t\tif (\"anyOf\" in schema) return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(`\\n${\" \".repeat(indent - 2)}`);\n\t\tthrow new Error(\"unsupported schema type\");\n\t}\n\tstatic fromZodSchema(schema) {\n\t\treturn new this(schema);\n\t}\n\tstatic fromNamesAndDescriptions(schemas) {\n\t\tconst zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)])));\n\t\treturn new this(zodSchema);\n\t}\n};\n/**\n* A type of `StructuredOutputParser` that handles asymmetric input and\n* output schemas.\n*/\nvar AsymmetricStructuredOutputParser = class extends BaseOutputParser {\n\tstructuredInputParser;\n\tconstructor({ inputSchema }) {\n\t\tsuper(...arguments);\n\t\tthis.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema);\n\t}\n\tasync parse(text) {\n\t\tlet parsedInput;\n\t\ttry {\n\t\t\tparsedInput = await this.structuredInputParser.parse(text);\n\t\t} catch (e) {\n\t\t\tthrow new OutputParserException(`Failed to parse. Text: \"${text}\". Error: ${e}`, text);\n\t\t}\n\t\treturn this.outputProcessor(parsedInput);\n\t}\n\tgetFormatInstructions() {\n\t\treturn this.structuredInputParser.getFormatInstructions();\n\t}\n};\n\n//#endregion\nexport { AsymmetricStructuredOutputParser, JsonMarkdownStructuredOutputParser, StructuredOutputParser };\n//# sourceMappingURL=structured.js.map","import { parseJsonMarkdown, parsePartialJson } from \"../utils/json.js\";\nimport { compare } from \"../utils/fast-json-patch/src/duplex.js\";\nimport { BaseCumulativeTransformOutputParser } from \"./transform.js\";\nimport \"../utils/json_patch.js\";\n\n//#region src/output_parsers/json.ts\n/**\n* Class for parsing the output of an LLM into a JSON object.\n*/\nvar JsonOutputParser = class extends BaseCumulativeTransformOutputParser {\n\tstatic lc_name() {\n\t\treturn \"JsonOutputParser\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"output_parsers\"];\n\tlc_serializable = true;\n\t/** @internal */\n\t_concatOutputChunks(first, second) {\n\t\tif (this.diff) return super._concatOutputChunks(first, second);\n\t\treturn second;\n\t}\n\t_diff(prev, next) {\n\t\tif (!next) return void 0;\n\t\tif (!prev) return [{\n\t\t\top: \"replace\",\n\t\t\tpath: \"\",\n\t\t\tvalue: next\n\t\t}];\n\t\treturn compare(prev, next);\n\t}\n\tasync parsePartialResult(generations) {\n\t\treturn parseJsonMarkdown(generations[0].text);\n\t}\n\tasync parse(text) {\n\t\treturn parseJsonMarkdown(text, JSON.parse);\n\t}\n\tgetFormatInstructions() {\n\t\treturn \"\";\n\t}\n};\n\n//#endregion\nexport { JsonOutputParser };\n//# sourceMappingURL=json.js.map","//#region src/utils/sax-js/sax.ts\nconst initializeSax = function() {\n\tconst sax$1 = {};\n\tsax$1.parser = function(strict, opt) {\n\t\treturn new SAXParser(strict, opt);\n\t};\n\tsax$1.SAXParser = SAXParser;\n\tsax$1.SAXStream = SAXStream;\n\tsax$1.createStream = createStream;\n\tsax$1.MAX_BUFFER_LENGTH = 64 * 1024;\n\tconst buffers = [\n\t\t\"comment\",\n\t\t\"sgmlDecl\",\n\t\t\"textNode\",\n\t\t\"tagName\",\n\t\t\"doctype\",\n\t\t\"procInstName\",\n\t\t\"procInstBody\",\n\t\t\"entity\",\n\t\t\"attribName\",\n\t\t\"attribValue\",\n\t\t\"cdata\",\n\t\t\"script\"\n\t];\n\tsax$1.EVENTS = [\n\t\t\"text\",\n\t\t\"processinginstruction\",\n\t\t\"sgmldeclaration\",\n\t\t\"doctype\",\n\t\t\"comment\",\n\t\t\"opentagstart\",\n\t\t\"attribute\",\n\t\t\"opentag\",\n\t\t\"closetag\",\n\t\t\"opencdata\",\n\t\t\"cdata\",\n\t\t\"closecdata\",\n\t\t\"error\",\n\t\t\"end\",\n\t\t\"ready\",\n\t\t\"script\",\n\t\t\"opennamespace\",\n\t\t\"closenamespace\"\n\t];\n\tfunction SAXParser(strict, opt) {\n\t\tif (!(this instanceof SAXParser)) return new SAXParser(strict, opt);\n\t\tvar parser = this;\n\t\tclearBuffers(parser);\n\t\tparser.q = parser.c = \"\";\n\t\tparser.bufferCheckPosition = sax$1.MAX_BUFFER_LENGTH;\n\t\tparser.opt = opt || {};\n\t\tparser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags;\n\t\tparser.looseCase = parser.opt.lowercase ? \"toLowerCase\" : \"toUpperCase\";\n\t\tparser.tags = [];\n\t\tparser.closed = parser.closedRoot = parser.sawRoot = false;\n\t\tparser.tag = parser.error = null;\n\t\tparser.strict = !!strict;\n\t\tparser.noscript = !!(strict || parser.opt.noscript);\n\t\tparser.state = S.BEGIN;\n\t\tparser.strictEntities = parser.opt.strictEntities;\n\t\tparser.ENTITIES = parser.strictEntities ? Object.create(sax$1.XML_ENTITIES) : Object.create(sax$1.ENTITIES);\n\t\tparser.attribList = [];\n\t\tif (parser.opt.xmlns) parser.ns = Object.create(rootNS);\n\t\tparser.trackPosition = parser.opt.position !== false;\n\t\tif (parser.trackPosition) parser.position = parser.line = parser.column = 0;\n\t\temit(parser, \"onready\");\n\t}\n\tif (!Object.create) Object.create = function(o) {\n\t\tfunction F() {}\n\t\tF.prototype = o;\n\t\tvar newf = new F();\n\t\treturn newf;\n\t};\n\tif (!Object.keys) Object.keys = function(o) {\n\t\tvar a = [];\n\t\tfor (var i in o) if (o.hasOwnProperty(i)) a.push(i);\n\t\treturn a;\n\t};\n\tfunction checkBufferLength(parser) {\n\t\tvar maxAllowed = Math.max(sax$1.MAX_BUFFER_LENGTH, 10);\n\t\tvar maxActual = 0;\n\t\tfor (var i = 0, l = buffers.length; i < l; i++) {\n\t\t\tvar len = parser[buffers[i]].length;\n\t\t\tif (len > maxAllowed) switch (buffers[i]) {\n\t\t\t\tcase \"textNode\":\n\t\t\t\t\tcloseText(parser);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"cdata\":\n\t\t\t\t\temitNode(parser, \"oncdata\", parser.cdata);\n\t\t\t\t\tparser.cdata = \"\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"script\":\n\t\t\t\t\temitNode(parser, \"onscript\", parser.script);\n\t\t\t\t\tparser.script = \"\";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: error(parser, \"Max buffer length exceeded: \" + buffers[i]);\n\t\t\t}\n\t\t\tmaxActual = Math.max(maxActual, len);\n\t\t}\n\t\tvar m = sax$1.MAX_BUFFER_LENGTH - maxActual;\n\t\tparser.bufferCheckPosition = m + parser.position;\n\t}\n\tfunction clearBuffers(parser) {\n\t\tfor (var i = 0, l = buffers.length; i < l; i++) parser[buffers[i]] = \"\";\n\t}\n\tfunction flushBuffers(parser) {\n\t\tcloseText(parser);\n\t\tif (parser.cdata !== \"\") {\n\t\t\temitNode(parser, \"oncdata\", parser.cdata);\n\t\t\tparser.cdata = \"\";\n\t\t}\n\t\tif (parser.script !== \"\") {\n\t\t\temitNode(parser, \"onscript\", parser.script);\n\t\t\tparser.script = \"\";\n\t\t}\n\t}\n\tSAXParser.prototype = {\n\t\tend: function() {\n\t\t\tend(this);\n\t\t},\n\t\twrite,\n\t\tresume: function() {\n\t\t\tthis.error = null;\n\t\t\treturn this;\n\t\t},\n\t\tclose: function() {\n\t\t\treturn this.write(null);\n\t\t},\n\t\tflush: function() {\n\t\t\tflushBuffers(this);\n\t\t}\n\t};\n\tvar Stream = ReadableStream;\n\tif (!Stream) Stream = function() {};\n\tvar streamWraps = sax$1.EVENTS.filter(function(ev) {\n\t\treturn ev !== \"error\" && ev !== \"end\";\n\t});\n\tfunction createStream(strict, opt) {\n\t\treturn new SAXStream(strict, opt);\n\t}\n\tfunction SAXStream(strict, opt) {\n\t\tif (!(this instanceof SAXStream)) return new SAXStream(strict, opt);\n\t\tStream.apply(this);\n\t\tthis._parser = new SAXParser(strict, opt);\n\t\tthis.writable = true;\n\t\tthis.readable = true;\n\t\tvar me = this;\n\t\tthis._parser.onend = function() {\n\t\t\tme.emit(\"end\");\n\t\t};\n\t\tthis._parser.onerror = function(er) {\n\t\t\tme.emit(\"error\", er);\n\t\t\tme._parser.error = null;\n\t\t};\n\t\tthis._decoder = null;\n\t\tstreamWraps.forEach(function(ev) {\n\t\t\tObject.defineProperty(me, \"on\" + ev, {\n\t\t\t\tget: function() {\n\t\t\t\t\treturn me._parser[\"on\" + ev];\n\t\t\t\t},\n\t\t\t\tset: function(h) {\n\t\t\t\t\tif (!h) {\n\t\t\t\t\t\tme.removeAllListeners(ev);\n\t\t\t\t\t\tme._parser[\"on\" + ev] = h;\n\t\t\t\t\t\treturn h;\n\t\t\t\t\t}\n\t\t\t\t\tme.on(ev, h);\n\t\t\t\t},\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: false\n\t\t\t});\n\t\t});\n\t}\n\tSAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } });\n\tSAXStream.prototype.write = function(data) {\n\t\tthis._parser.write(data.toString());\n\t\tthis.emit(\"data\", data);\n\t\treturn true;\n\t};\n\tSAXStream.prototype.end = function(chunk) {\n\t\tif (chunk && chunk.length) this.write(chunk);\n\t\tthis._parser.end();\n\t\treturn true;\n\t};\n\tSAXStream.prototype.on = function(ev, handler) {\n\t\tvar me = this;\n\t\tif (!me._parser[\"on\" + ev] && streamWraps.indexOf(ev) !== -1) me._parser[\"on\" + ev] = function() {\n\t\t\tvar args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments);\n\t\t\targs.splice(0, 0, ev);\n\t\t\tme.emit.apply(me, args);\n\t\t};\n\t\treturn Stream.prototype.on.call(me, ev, handler);\n\t};\n\tvar CDATA = \"[CDATA[\";\n\tvar DOCTYPE = \"DOCTYPE\";\n\tvar XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\n\tvar XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\n\tvar rootNS = {\n\t\txml: XML_NAMESPACE,\n\t\txmlns: XMLNS_NAMESPACE\n\t};\n\tvar nameStart = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/;\n\tvar nameBody = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/;\n\tvar entityStart = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/;\n\tvar entityBody = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/;\n\tfunction isWhitespace(c) {\n\t\treturn c === \" \" || c === \"\\n\" || c === \"\\r\" || c === \"\t\";\n\t}\n\tfunction isQuote(c) {\n\t\treturn c === \"\\\"\" || c === \"'\";\n\t}\n\tfunction isAttribEnd(c) {\n\t\treturn c === \">\" || isWhitespace(c);\n\t}\n\tfunction isMatch(regex, c) {\n\t\treturn regex.test(c);\n\t}\n\tfunction notMatch(regex, c) {\n\t\treturn !isMatch(regex, c);\n\t}\n\tvar S = 0;\n\tsax$1.STATE = {\n\t\tBEGIN: S++,\n\t\tBEGIN_WHITESPACE: S++,\n\t\tTEXT: S++,\n\t\tTEXT_ENTITY: S++,\n\t\tOPEN_WAKA: S++,\n\t\tSGML_DECL: S++,\n\t\tSGML_DECL_QUOTED: S++,\n\t\tDOCTYPE: S++,\n\t\tDOCTYPE_QUOTED: S++,\n\t\tDOCTYPE_DTD: S++,\n\t\tDOCTYPE_DTD_QUOTED: S++,\n\t\tCOMMENT_STARTING: S++,\n\t\tCOMMENT: S++,\n\t\tCOMMENT_ENDING: S++,\n\t\tCOMMENT_ENDED: S++,\n\t\tCDATA: S++,\n\t\tCDATA_ENDING: S++,\n\t\tCDATA_ENDING_2: S++,\n\t\tPROC_INST: S++,\n\t\tPROC_INST_BODY: S++,\n\t\tPROC_INST_ENDING: S++,\n\t\tOPEN_TAG: S++,\n\t\tOPEN_TAG_SLASH: S++,\n\t\tATTRIB: S++,\n\t\tATTRIB_NAME: S++,\n\t\tATTRIB_NAME_SAW_WHITE: S++,\n\t\tATTRIB_VALUE: S++,\n\t\tATTRIB_VALUE_QUOTED: S++,\n\t\tATTRIB_VALUE_CLOSED: S++,\n\t\tATTRIB_VALUE_UNQUOTED: S++,\n\t\tATTRIB_VALUE_ENTITY_Q: S++,\n\t\tATTRIB_VALUE_ENTITY_U: S++,\n\t\tCLOSE_TAG: S++,\n\t\tCLOSE_TAG_SAW_WHITE: S++,\n\t\tSCRIPT: S++,\n\t\tSCRIPT_ENDING: S++\n\t};\n\tsax$1.XML_ENTITIES = {\n\t\tamp: \"&\",\n\t\tgt: \">\",\n\t\tlt: \"<\",\n\t\tquot: \"\\\"\",\n\t\tapos: \"'\"\n\t};\n\tsax$1.ENTITIES = {\n\t\tamp: \"&\",\n\t\tgt: \">\",\n\t\tlt: \"<\",\n\t\tquot: \"\\\"\",\n\t\tapos: \"'\",\n\t\tAElig: 198,\n\t\tAacute: 193,\n\t\tAcirc: 194,\n\t\tAgrave: 192,\n\t\tAring: 197,\n\t\tAtilde: 195,\n\t\tAuml: 196,\n\t\tCcedil: 199,\n\t\tETH: 208,\n\t\tEacute: 201,\n\t\tEcirc: 202,\n\t\tEgrave: 200,\n\t\tEuml: 203,\n\t\tIacute: 205,\n\t\tIcirc: 206,\n\t\tIgrave: 204,\n\t\tIuml: 207,\n\t\tNtilde: 209,\n\t\tOacute: 211,\n\t\tOcirc: 212,\n\t\tOgrave: 210,\n\t\tOslash: 216,\n\t\tOtilde: 213,\n\t\tOuml: 214,\n\t\tTHORN: 222,\n\t\tUacute: 218,\n\t\tUcirc: 219,\n\t\tUgrave: 217,\n\t\tUuml: 220,\n\t\tYacute: 221,\n\t\taacute: 225,\n\t\tacirc: 226,\n\t\taelig: 230,\n\t\tagrave: 224,\n\t\taring: 229,\n\t\tatilde: 227,\n\t\tauml: 228,\n\t\tccedil: 231,\n\t\teacute: 233,\n\t\tecirc: 234,\n\t\tegrave: 232,\n\t\teth: 240,\n\t\teuml: 235,\n\t\tiacute: 237,\n\t\ticirc: 238,\n\t\tigrave: 236,\n\t\tiuml: 239,\n\t\tntilde: 241,\n\t\toacute: 243,\n\t\tocirc: 244,\n\t\tograve: 242,\n\t\toslash: 248,\n\t\totilde: 245,\n\t\touml: 246,\n\t\tszlig: 223,\n\t\tthorn: 254,\n\t\tuacute: 250,\n\t\tucirc: 251,\n\t\tugrave: 249,\n\t\tuuml: 252,\n\t\tyacute: 253,\n\t\tyuml: 255,\n\t\tcopy: 169,\n\t\treg: 174,\n\t\tnbsp: 160,\n\t\tiexcl: 161,\n\t\tcent: 162,\n\t\tpound: 163,\n\t\tcurren: 164,\n\t\tyen: 165,\n\t\tbrvbar: 166,\n\t\tsect: 167,\n\t\tuml: 168,\n\t\tordf: 170,\n\t\tlaquo: 171,\n\t\tnot: 172,\n\t\tshy: 173,\n\t\tmacr: 175,\n\t\tdeg: 176,\n\t\tplusmn: 177,\n\t\tsup1: 185,\n\t\tsup2: 178,\n\t\tsup3: 179,\n\t\tacute: 180,\n\t\tmicro: 181,\n\t\tpara: 182,\n\t\tmiddot: 183,\n\t\tcedil: 184,\n\t\tordm: 186,\n\t\traquo: 187,\n\t\tfrac14: 188,\n\t\tfrac12: 189,\n\t\tfrac34: 190,\n\t\tiquest: 191,\n\t\ttimes: 215,\n\t\tdivide: 247,\n\t\tOElig: 338,\n\t\toelig: 339,\n\t\tScaron: 352,\n\t\tscaron: 353,\n\t\tYuml: 376,\n\t\tfnof: 402,\n\t\tcirc: 710,\n\t\ttilde: 732,\n\t\tAlpha: 913,\n\t\tBeta: 914,\n\t\tGamma: 915,\n\t\tDelta: 916,\n\t\tEpsilon: 917,\n\t\tZeta: 918,\n\t\tEta: 919,\n\t\tTheta: 920,\n\t\tIota: 921,\n\t\tKappa: 922,\n\t\tLambda: 923,\n\t\tMu: 924,\n\t\tNu: 925,\n\t\tXi: 926,\n\t\tOmicron: 927,\n\t\tPi: 928,\n\t\tRho: 929,\n\t\tSigma: 931,\n\t\tTau: 932,\n\t\tUpsilon: 933,\n\t\tPhi: 934,\n\t\tChi: 935,\n\t\tPsi: 936,\n\t\tOmega: 937,\n\t\talpha: 945,\n\t\tbeta: 946,\n\t\tgamma: 947,\n\t\tdelta: 948,\n\t\tepsilon: 949,\n\t\tzeta: 950,\n\t\teta: 951,\n\t\ttheta: 952,\n\t\tiota: 953,\n\t\tkappa: 954,\n\t\tlambda: 955,\n\t\tmu: 956,\n\t\tnu: 957,\n\t\txi: 958,\n\t\tomicron: 959,\n\t\tpi: 960,\n\t\trho: 961,\n\t\tsigmaf: 962,\n\t\tsigma: 963,\n\t\ttau: 964,\n\t\tupsilon: 965,\n\t\tphi: 966,\n\t\tchi: 967,\n\t\tpsi: 968,\n\t\tomega: 969,\n\t\tthetasym: 977,\n\t\tupsih: 978,\n\t\tpiv: 982,\n\t\tensp: 8194,\n\t\temsp: 8195,\n\t\tthinsp: 8201,\n\t\tzwnj: 8204,\n\t\tzwj: 8205,\n\t\tlrm: 8206,\n\t\trlm: 8207,\n\t\tndash: 8211,\n\t\tmdash: 8212,\n\t\tlsquo: 8216,\n\t\trsquo: 8217,\n\t\tsbquo: 8218,\n\t\tldquo: 8220,\n\t\trdquo: 8221,\n\t\tbdquo: 8222,\n\t\tdagger: 8224,\n\t\tDagger: 8225,\n\t\tbull: 8226,\n\t\thellip: 8230,\n\t\tpermil: 8240,\n\t\tprime: 8242,\n\t\tPrime: 8243,\n\t\tlsaquo: 8249,\n\t\trsaquo: 8250,\n\t\toline: 8254,\n\t\tfrasl: 8260,\n\t\teuro: 8364,\n\t\timage: 8465,\n\t\tweierp: 8472,\n\t\treal: 8476,\n\t\ttrade: 8482,\n\t\talefsym: 8501,\n\t\tlarr: 8592,\n\t\tuarr: 8593,\n\t\trarr: 8594,\n\t\tdarr: 8595,\n\t\tharr: 8596,\n\t\tcrarr: 8629,\n\t\tlArr: 8656,\n\t\tuArr: 8657,\n\t\trArr: 8658,\n\t\tdArr: 8659,\n\t\thArr: 8660,\n\t\tforall: 8704,\n\t\tpart: 8706,\n\t\texist: 8707,\n\t\tempty: 8709,\n\t\tnabla: 8711,\n\t\tisin: 8712,\n\t\tnotin: 8713,\n\t\tni: 8715,\n\t\tprod: 8719,\n\t\tsum: 8721,\n\t\tminus: 8722,\n\t\tlowast: 8727,\n\t\tradic: 8730,\n\t\tprop: 8733,\n\t\tinfin: 8734,\n\t\tang: 8736,\n\t\tand: 8743,\n\t\tor: 8744,\n\t\tcap: 8745,\n\t\tcup: 8746,\n\t\tint: 8747,\n\t\tthere4: 8756,\n\t\tsim: 8764,\n\t\tcong: 8773,\n\t\tasymp: 8776,\n\t\tne: 8800,\n\t\tequiv: 8801,\n\t\tle: 8804,\n\t\tge: 8805,\n\t\tsub: 8834,\n\t\tsup: 8835,\n\t\tnsub: 8836,\n\t\tsube: 8838,\n\t\tsupe: 8839,\n\t\toplus: 8853,\n\t\totimes: 8855,\n\t\tperp: 8869,\n\t\tsdot: 8901,\n\t\tlceil: 8968,\n\t\trceil: 8969,\n\t\tlfloor: 8970,\n\t\trfloor: 8971,\n\t\tlang: 9001,\n\t\trang: 9002,\n\t\tloz: 9674,\n\t\tspades: 9824,\n\t\tclubs: 9827,\n\t\thearts: 9829,\n\t\tdiams: 9830\n\t};\n\tObject.keys(sax$1.ENTITIES).forEach(function(key) {\n\t\tvar e = sax$1.ENTITIES[key];\n\t\tvar s$1 = typeof e === \"number\" ? String.fromCharCode(e) : e;\n\t\tsax$1.ENTITIES[key] = s$1;\n\t});\n\tfor (var s in sax$1.STATE) sax$1.STATE[sax$1.STATE[s]] = s;\n\tS = sax$1.STATE;\n\tfunction emit(parser, event, data) {\n\t\tparser[event] && parser[event](data);\n\t}\n\tfunction emitNode(parser, nodeType, data) {\n\t\tif (parser.textNode) closeText(parser);\n\t\temit(parser, nodeType, data);\n\t}\n\tfunction closeText(parser) {\n\t\tparser.textNode = textopts(parser.opt, parser.textNode);\n\t\tif (parser.textNode) emit(parser, \"ontext\", parser.textNode);\n\t\tparser.textNode = \"\";\n\t}\n\tfunction textopts(opt, text) {\n\t\tif (opt.trim) text = text.trim();\n\t\tif (opt.normalize) text = text.replace(/\\s+/g, \" \");\n\t\treturn text;\n\t}\n\tfunction error(parser, er) {\n\t\tcloseText(parser);\n\t\tif (parser.trackPosition) er += \"\\nLine: \" + parser.line + \"\\nColumn: \" + parser.column + \"\\nChar: \" + parser.c;\n\t\ter = new Error(er);\n\t\tparser.error = er;\n\t\temit(parser, \"onerror\", er);\n\t\treturn parser;\n\t}\n\tfunction end(parser) {\n\t\tif (parser.sawRoot && !parser.closedRoot) strictFail(parser, \"Unclosed root tag\");\n\t\tif (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) error(parser, \"Unexpected end\");\n\t\tcloseText(parser);\n\t\tparser.c = \"\";\n\t\tparser.closed = true;\n\t\temit(parser, \"onend\");\n\t\tSAXParser.call(parser, parser.strict, parser.opt);\n\t\treturn parser;\n\t}\n\tfunction strictFail(parser, message) {\n\t\tif (typeof parser !== \"object\" || !(parser instanceof SAXParser)) throw new Error(\"bad call to strictFail\");\n\t\tif (parser.strict) error(parser, message);\n\t}\n\tfunction newTag(parser) {\n\t\tif (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]();\n\t\tvar parent = parser.tags[parser.tags.length - 1] || parser;\n\t\tvar tag = parser.tag = {\n\t\t\tname: parser.tagName,\n\t\t\tattributes: {}\n\t\t};\n\t\tif (parser.opt.xmlns) tag.ns = parent.ns;\n\t\tparser.attribList.length = 0;\n\t\temitNode(parser, \"onopentagstart\", tag);\n\t}\n\tfunction qname(name, attribute) {\n\t\tvar i = name.indexOf(\":\");\n\t\tvar qualName = i < 0 ? [\"\", name] : name.split(\":\");\n\t\tvar prefix = qualName[0];\n\t\tvar local = qualName[1];\n\t\tif (attribute && name === \"xmlns\") {\n\t\t\tprefix = \"xmlns\";\n\t\t\tlocal = \"\";\n\t\t}\n\t\treturn {\n\t\t\tprefix,\n\t\t\tlocal\n\t\t};\n\t}\n\tfunction attrib(parser) {\n\t\tif (!parser.strict) parser.attribName = parser.attribName[parser.looseCase]();\n\t\tif (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) {\n\t\t\tparser.attribName = parser.attribValue = \"\";\n\t\t\treturn;\n\t\t}\n\t\tif (parser.opt.xmlns) {\n\t\t\tvar qn = qname(parser.attribName, true);\n\t\t\tvar prefix = qn.prefix;\n\t\t\tvar local = qn.local;\n\t\t\tif (prefix === \"xmlns\") if (local === \"xml\" && parser.attribValue !== XML_NAMESPACE) strictFail(parser, \"xml: prefix must be bound to \" + XML_NAMESPACE + \"\\nActual: \" + parser.attribValue);\n\t\t\telse if (local === \"xmlns\" && parser.attribValue !== XMLNS_NAMESPACE) strictFail(parser, \"xmlns: prefix must be bound to \" + XMLNS_NAMESPACE + \"\\nActual: \" + parser.attribValue);\n\t\t\telse {\n\t\t\t\tvar tag = parser.tag;\n\t\t\t\tvar parent = parser.tags[parser.tags.length - 1] || parser;\n\t\t\t\tif (tag.ns === parent.ns) tag.ns = Object.create(parent.ns);\n\t\t\t\ttag.ns[local] = parser.attribValue;\n\t\t\t}\n\t\t\tparser.attribList.push([parser.attribName, parser.attribValue]);\n\t\t} else {\n\t\t\tparser.tag.attributes[parser.attribName] = parser.attribValue;\n\t\t\temitNode(parser, \"onattribute\", {\n\t\t\t\tname: parser.attribName,\n\t\t\t\tvalue: parser.attribValue\n\t\t\t});\n\t\t}\n\t\tparser.attribName = parser.attribValue = \"\";\n\t}\n\tfunction openTag(parser, selfClosing) {\n\t\tif (parser.opt.xmlns) {\n\t\t\tvar tag = parser.tag;\n\t\t\tvar qn = qname(parser.tagName);\n\t\t\ttag.prefix = qn.prefix;\n\t\t\ttag.local = qn.local;\n\t\t\ttag.uri = tag.ns[qn.prefix] || \"\";\n\t\t\tif (tag.prefix && !tag.uri) {\n\t\t\t\tstrictFail(parser, \"Unbound namespace prefix: \" + JSON.stringify(parser.tagName));\n\t\t\t\ttag.uri = qn.prefix;\n\t\t\t}\n\t\t\tvar parent = parser.tags[parser.tags.length - 1] || parser;\n\t\t\tif (tag.ns && parent.ns !== tag.ns) Object.keys(tag.ns).forEach(function(p) {\n\t\t\t\temitNode(parser, \"onopennamespace\", {\n\t\t\t\t\tprefix: p,\n\t\t\t\t\turi: tag.ns[p]\n\t\t\t\t});\n\t\t\t});\n\t\t\tfor (var i = 0, l = parser.attribList.length; i < l; i++) {\n\t\t\t\tvar nv = parser.attribList[i];\n\t\t\t\tvar name = nv[0];\n\t\t\t\tvar value = nv[1];\n\t\t\t\tvar qualName = qname(name, true);\n\t\t\t\tvar prefix = qualName.prefix;\n\t\t\t\tvar local = qualName.local;\n\t\t\t\tvar uri = prefix === \"\" ? \"\" : tag.ns[prefix] || \"\";\n\t\t\t\tvar a = {\n\t\t\t\t\tname,\n\t\t\t\t\tvalue,\n\t\t\t\t\tprefix,\n\t\t\t\t\tlocal,\n\t\t\t\t\turi\n\t\t\t\t};\n\t\t\t\tif (prefix && prefix !== \"xmlns\" && !uri) {\n\t\t\t\t\tstrictFail(parser, \"Unbound namespace prefix: \" + JSON.stringify(prefix));\n\t\t\t\t\ta.uri = prefix;\n\t\t\t\t}\n\t\t\t\tparser.tag.attributes[name] = a;\n\t\t\t\temitNode(parser, \"onattribute\", a);\n\t\t\t}\n\t\t\tparser.attribList.length = 0;\n\t\t}\n\t\tparser.tag.isSelfClosing = !!selfClosing;\n\t\tparser.sawRoot = true;\n\t\tparser.tags.push(parser.tag);\n\t\temitNode(parser, \"onopentag\", parser.tag);\n\t\tif (!selfClosing) {\n\t\t\tif (!parser.noscript && parser.tagName.toLowerCase() === \"script\") parser.state = S.SCRIPT;\n\t\t\telse parser.state = S.TEXT;\n\t\t\tparser.tag = null;\n\t\t\tparser.tagName = \"\";\n\t\t}\n\t\tparser.attribName = parser.attribValue = \"\";\n\t\tparser.attribList.length = 0;\n\t}\n\tfunction closeTag(parser) {\n\t\tif (!parser.tagName) {\n\t\t\tstrictFail(parser, \"Weird empty close tag.\");\n\t\t\tparser.textNode += \"\";\n\t\t\tparser.state = S.TEXT;\n\t\t\treturn;\n\t\t}\n\t\tif (parser.script) {\n\t\t\tif (parser.tagName !== \"script\") {\n\t\t\t\tparser.script += \"\";\n\t\t\t\tparser.tagName = \"\";\n\t\t\t\tparser.state = S.SCRIPT;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\temitNode(parser, \"onscript\", parser.script);\n\t\t\tparser.script = \"\";\n\t\t}\n\t\tvar t = parser.tags.length;\n\t\tvar tagName = parser.tagName;\n\t\tif (!parser.strict) tagName = tagName[parser.looseCase]();\n\t\tvar closeTo = tagName;\n\t\twhile (t--) {\n\t\t\tvar close = parser.tags[t];\n\t\t\tif (close.name !== closeTo) strictFail(parser, \"Unexpected close tag\");\n\t\t\telse break;\n\t\t}\n\t\tif (t < 0) {\n\t\t\tstrictFail(parser, \"Unmatched closing tag: \" + parser.tagName);\n\t\t\tparser.textNode += \"\";\n\t\t\tparser.state = S.TEXT;\n\t\t\treturn;\n\t\t}\n\t\tparser.tagName = tagName;\n\t\tvar s$1 = parser.tags.length;\n\t\twhile (s$1-- > t) {\n\t\t\tvar tag = parser.tag = parser.tags.pop();\n\t\t\tparser.tagName = parser.tag.name;\n\t\t\temitNode(parser, \"onclosetag\", parser.tagName);\n\t\t\tvar x = {};\n\t\t\tfor (var i in tag.ns) x[i] = tag.ns[i];\n\t\t\tvar parent = parser.tags[parser.tags.length - 1] || parser;\n\t\t\tif (parser.opt.xmlns && tag.ns !== parent.ns) Object.keys(tag.ns).forEach(function(p) {\n\t\t\t\tvar n = tag.ns[p];\n\t\t\t\temitNode(parser, \"onclosenamespace\", {\n\t\t\t\t\tprefix: p,\n\t\t\t\t\turi: n\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\tif (t === 0) parser.closedRoot = true;\n\t\tparser.tagName = parser.attribValue = parser.attribName = \"\";\n\t\tparser.attribList.length = 0;\n\t\tparser.state = S.TEXT;\n\t}\n\tfunction parseEntity(parser) {\n\t\tvar entity = parser.entity;\n\t\tvar entityLC = entity.toLowerCase();\n\t\tvar num;\n\t\tvar numStr = \"\";\n\t\tif (parser.ENTITIES[entity]) return parser.ENTITIES[entity];\n\t\tif (parser.ENTITIES[entityLC]) return parser.ENTITIES[entityLC];\n\t\tentity = entityLC;\n\t\tif (entity.charAt(0) === \"#\") if (entity.charAt(1) === \"x\") {\n\t\t\tentity = entity.slice(2);\n\t\t\tnum = parseInt(entity, 16);\n\t\t\tnumStr = num.toString(16);\n\t\t} else {\n\t\t\tentity = entity.slice(1);\n\t\t\tnum = parseInt(entity, 10);\n\t\t\tnumStr = num.toString(10);\n\t\t}\n\t\tentity = entity.replace(/^0+/, \"\");\n\t\tif (isNaN(num) || numStr.toLowerCase() !== entity) {\n\t\t\tstrictFail(parser, \"Invalid character entity\");\n\t\t\treturn \"&\" + parser.entity + \";\";\n\t\t}\n\t\treturn String.fromCodePoint(num);\n\t}\n\tfunction beginWhiteSpace(parser, c) {\n\t\tif (c === \"<\") {\n\t\t\tparser.state = S.OPEN_WAKA;\n\t\t\tparser.startTagPosition = parser.position;\n\t\t} else if (!isWhitespace(c)) {\n\t\t\tstrictFail(parser, \"Non-whitespace before first tag.\");\n\t\t\tparser.textNode = c;\n\t\t\tparser.state = S.TEXT;\n\t\t}\n\t}\n\tfunction charAt(chunk, i) {\n\t\tvar result = \"\";\n\t\tif (i < chunk.length) result = chunk.charAt(i);\n\t\treturn result;\n\t}\n\tfunction write(chunk) {\n\t\tvar parser = this;\n\t\tif (this.error) throw this.error;\n\t\tif (parser.closed) return error(parser, \"Cannot write after close. Assign an onready handler.\");\n\t\tif (chunk === null) return end(parser);\n\t\tif (typeof chunk === \"object\") chunk = chunk.toString();\n\t\tvar i = 0;\n\t\tvar c = \"\";\n\t\twhile (true) {\n\t\t\tc = charAt(chunk, i++);\n\t\t\tparser.c = c;\n\t\t\tif (!c) break;\n\t\t\tif (parser.trackPosition) {\n\t\t\t\tparser.position++;\n\t\t\t\tif (c === \"\\n\") {\n\t\t\t\t\tparser.line++;\n\t\t\t\t\tparser.column = 0;\n\t\t\t\t} else parser.column++;\n\t\t\t}\n\t\t\tswitch (parser.state) {\n\t\t\t\tcase S.BEGIN:\n\t\t\t\t\tparser.state = S.BEGIN_WHITESPACE;\n\t\t\t\t\tif (c === \"\") continue;\n\t\t\t\t\tbeginWhiteSpace(parser, c);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.BEGIN_WHITESPACE:\n\t\t\t\t\tbeginWhiteSpace(parser, c);\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.TEXT:\n\t\t\t\t\tif (parser.sawRoot && !parser.closedRoot) {\n\t\t\t\t\t\tvar starti = i - 1;\n\t\t\t\t\t\twhile (c && c !== \"<\" && c !== \"&\") {\n\t\t\t\t\t\t\tc = charAt(chunk, i++);\n\t\t\t\t\t\t\tif (c && parser.trackPosition) {\n\t\t\t\t\t\t\t\tparser.position++;\n\t\t\t\t\t\t\t\tif (c === \"\\n\") {\n\t\t\t\t\t\t\t\t\tparser.line++;\n\t\t\t\t\t\t\t\t\tparser.column = 0;\n\t\t\t\t\t\t\t\t} else parser.column++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tparser.textNode += chunk.substring(starti, i - 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (c === \"<\" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {\n\t\t\t\t\t\tparser.state = S.OPEN_WAKA;\n\t\t\t\t\t\tparser.startTagPosition = parser.position;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) strictFail(parser, \"Text data outside of root node.\");\n\t\t\t\t\t\tif (c === \"&\") parser.state = S.TEXT_ENTITY;\n\t\t\t\t\t\telse parser.textNode += c;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.SCRIPT:\n\t\t\t\t\tif (c === \"<\") parser.state = S.SCRIPT_ENDING;\n\t\t\t\t\telse parser.script += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.SCRIPT_ENDING:\n\t\t\t\t\tif (c === \"/\") parser.state = S.CLOSE_TAG;\n\t\t\t\t\telse {\n\t\t\t\t\t\tparser.script += \"<\" + c;\n\t\t\t\t\t\tparser.state = S.SCRIPT;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.OPEN_WAKA:\n\t\t\t\t\tif (c === \"!\") {\n\t\t\t\t\t\tparser.state = S.SGML_DECL;\n\t\t\t\t\t\tparser.sgmlDecl = \"\";\n\t\t\t\t\t} else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) {\n\t\t\t\t\t\tparser.state = S.OPEN_TAG;\n\t\t\t\t\t\tparser.tagName = c;\n\t\t\t\t\t} else if (c === \"/\") {\n\t\t\t\t\t\tparser.state = S.CLOSE_TAG;\n\t\t\t\t\t\tparser.tagName = \"\";\n\t\t\t\t\t} else if (c === \"?\") {\n\t\t\t\t\t\tparser.state = S.PROC_INST;\n\t\t\t\t\t\tparser.procInstName = parser.procInstBody = \"\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstrictFail(parser, \"Unencoded <\");\n\t\t\t\t\t\tif (parser.startTagPosition + 1 < parser.position) {\n\t\t\t\t\t\t\tvar pad = parser.position - parser.startTagPosition;\n\t\t\t\t\t\t\tc = new Array(pad).join(\" \") + c;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tparser.textNode += \"<\" + c;\n\t\t\t\t\t\tparser.state = S.TEXT;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.SGML_DECL:\n\t\t\t\t\tif ((parser.sgmlDecl + c).toUpperCase() === CDATA) {\n\t\t\t\t\t\temitNode(parser, \"onopencdata\");\n\t\t\t\t\t\tparser.state = S.CDATA;\n\t\t\t\t\t\tparser.sgmlDecl = \"\";\n\t\t\t\t\t\tparser.cdata = \"\";\n\t\t\t\t\t} else if (parser.sgmlDecl + c === \"--\") {\n\t\t\t\t\t\tparser.state = S.COMMENT;\n\t\t\t\t\t\tparser.comment = \"\";\n\t\t\t\t\t\tparser.sgmlDecl = \"\";\n\t\t\t\t\t} else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {\n\t\t\t\t\t\tparser.state = S.DOCTYPE;\n\t\t\t\t\t\tif (parser.doctype || parser.sawRoot) strictFail(parser, \"Inappropriately located doctype declaration\");\n\t\t\t\t\t\tparser.doctype = \"\";\n\t\t\t\t\t\tparser.sgmlDecl = \"\";\n\t\t\t\t\t} else if (c === \">\") {\n\t\t\t\t\t\temitNode(parser, \"onsgmldeclaration\", parser.sgmlDecl);\n\t\t\t\t\t\tparser.sgmlDecl = \"\";\n\t\t\t\t\t\tparser.state = S.TEXT;\n\t\t\t\t\t} else if (isQuote(c)) {\n\t\t\t\t\t\tparser.state = S.SGML_DECL_QUOTED;\n\t\t\t\t\t\tparser.sgmlDecl += c;\n\t\t\t\t\t} else parser.sgmlDecl += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.SGML_DECL_QUOTED:\n\t\t\t\t\tif (c === parser.q) {\n\t\t\t\t\t\tparser.state = S.SGML_DECL;\n\t\t\t\t\t\tparser.q = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tparser.sgmlDecl += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.DOCTYPE:\n\t\t\t\t\tif (c === \">\") {\n\t\t\t\t\t\tparser.state = S.TEXT;\n\t\t\t\t\t\temitNode(parser, \"ondoctype\", parser.doctype);\n\t\t\t\t\t\tparser.doctype = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparser.doctype += c;\n\t\t\t\t\t\tif (c === \"[\") parser.state = S.DOCTYPE_DTD;\n\t\t\t\t\t\telse if (isQuote(c)) {\n\t\t\t\t\t\t\tparser.state = S.DOCTYPE_QUOTED;\n\t\t\t\t\t\t\tparser.q = c;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.DOCTYPE_QUOTED:\n\t\t\t\t\tparser.doctype += c;\n\t\t\t\t\tif (c === parser.q) {\n\t\t\t\t\t\tparser.q = \"\";\n\t\t\t\t\t\tparser.state = S.DOCTYPE;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.DOCTYPE_DTD:\n\t\t\t\t\tparser.doctype += c;\n\t\t\t\t\tif (c === \"]\") parser.state = S.DOCTYPE;\n\t\t\t\t\telse if (isQuote(c)) {\n\t\t\t\t\t\tparser.state = S.DOCTYPE_DTD_QUOTED;\n\t\t\t\t\t\tparser.q = c;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.DOCTYPE_DTD_QUOTED:\n\t\t\t\t\tparser.doctype += c;\n\t\t\t\t\tif (c === parser.q) {\n\t\t\t\t\t\tparser.state = S.DOCTYPE_DTD;\n\t\t\t\t\t\tparser.q = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.COMMENT:\n\t\t\t\t\tif (c === \"-\") parser.state = S.COMMENT_ENDING;\n\t\t\t\t\telse parser.comment += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.COMMENT_ENDING:\n\t\t\t\t\tif (c === \"-\") {\n\t\t\t\t\t\tparser.state = S.COMMENT_ENDED;\n\t\t\t\t\t\tparser.comment = textopts(parser.opt, parser.comment);\n\t\t\t\t\t\tif (parser.comment) emitNode(parser, \"oncomment\", parser.comment);\n\t\t\t\t\t\tparser.comment = \"\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparser.comment += \"-\" + c;\n\t\t\t\t\t\tparser.state = S.COMMENT;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.COMMENT_ENDED:\n\t\t\t\t\tif (c !== \">\") {\n\t\t\t\t\t\tstrictFail(parser, \"Malformed comment\");\n\t\t\t\t\t\tparser.comment += \"--\" + c;\n\t\t\t\t\t\tparser.state = S.COMMENT;\n\t\t\t\t\t} else parser.state = S.TEXT;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.CDATA:\n\t\t\t\t\tif (c === \"]\") parser.state = S.CDATA_ENDING;\n\t\t\t\t\telse parser.cdata += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.CDATA_ENDING:\n\t\t\t\t\tif (c === \"]\") parser.state = S.CDATA_ENDING_2;\n\t\t\t\t\telse {\n\t\t\t\t\t\tparser.cdata += \"]\" + c;\n\t\t\t\t\t\tparser.state = S.CDATA;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.CDATA_ENDING_2:\n\t\t\t\t\tif (c === \">\") {\n\t\t\t\t\t\tif (parser.cdata) emitNode(parser, \"oncdata\", parser.cdata);\n\t\t\t\t\t\temitNode(parser, \"onclosecdata\");\n\t\t\t\t\t\tparser.cdata = \"\";\n\t\t\t\t\t\tparser.state = S.TEXT;\n\t\t\t\t\t} else if (c === \"]\") parser.cdata += \"]\";\n\t\t\t\t\telse {\n\t\t\t\t\t\tparser.cdata += \"]]\" + c;\n\t\t\t\t\t\tparser.state = S.CDATA;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.PROC_INST:\n\t\t\t\t\tif (c === \"?\") parser.state = S.PROC_INST_ENDING;\n\t\t\t\t\telse if (isWhitespace(c)) parser.state = S.PROC_INST_BODY;\n\t\t\t\t\telse parser.procInstName += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.PROC_INST_BODY:\n\t\t\t\t\tif (!parser.procInstBody && isWhitespace(c)) continue;\n\t\t\t\t\telse if (c === \"?\") parser.state = S.PROC_INST_ENDING;\n\t\t\t\t\telse parser.procInstBody += c;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.PROC_INST_ENDING:\n\t\t\t\t\tif (c === \">\") {\n\t\t\t\t\t\temitNode(parser, \"onprocessinginstruction\", {\n\t\t\t\t\t\t\tname: parser.procInstName,\n\t\t\t\t\t\t\tbody: parser.procInstBody\n\t\t\t\t\t\t});\n\t\t\t\t\t\tparser.procInstName = parser.procInstBody = \"\";\n\t\t\t\t\t\tparser.state = S.TEXT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparser.procInstBody += \"?\" + c;\n\t\t\t\t\t\tparser.state = S.PROC_INST_BODY;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.OPEN_TAG:\n\t\t\t\t\tif (isMatch(nameBody, c)) parser.tagName += c;\n\t\t\t\t\telse {\n\t\t\t\t\t\tnewTag(parser);\n\t\t\t\t\t\tif (c === \">\") openTag(parser);\n\t\t\t\t\t\telse if (c === \"/\") parser.state = S.OPEN_TAG_SLASH;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (!isWhitespace(c)) strictFail(parser, \"Invalid character in tag name\");\n\t\t\t\t\t\t\tparser.state = S.ATTRIB;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.OPEN_TAG_SLASH:\n\t\t\t\t\tif (c === \">\") {\n\t\t\t\t\t\topenTag(parser, true);\n\t\t\t\t\t\tcloseTag(parser);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstrictFail(parser, \"Forward-slash in opening tag not followed by >\");\n\t\t\t\t\t\tparser.state = S.ATTRIB;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB:\n\t\t\t\t\tif (isWhitespace(c)) continue;\n\t\t\t\t\telse if (c === \">\") openTag(parser);\n\t\t\t\t\telse if (c === \"/\") parser.state = S.OPEN_TAG_SLASH;\n\t\t\t\t\telse if (isMatch(nameStart, c)) {\n\t\t\t\t\t\tparser.attribName = c;\n\t\t\t\t\t\tparser.attribValue = \"\";\n\t\t\t\t\t\tparser.state = S.ATTRIB_NAME;\n\t\t\t\t\t} else strictFail(parser, \"Invalid attribute name\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB_NAME:\n\t\t\t\t\tif (c === \"=\") parser.state = S.ATTRIB_VALUE;\n\t\t\t\t\telse if (c === \">\") {\n\t\t\t\t\t\tstrictFail(parser, \"Attribute without value\");\n\t\t\t\t\t\tparser.attribValue = parser.attribName;\n\t\t\t\t\t\tattrib(parser);\n\t\t\t\t\t\topenTag(parser);\n\t\t\t\t\t} else if (isWhitespace(c)) parser.state = S.ATTRIB_NAME_SAW_WHITE;\n\t\t\t\t\telse if (isMatch(nameBody, c)) parser.attribName += c;\n\t\t\t\t\telse strictFail(parser, \"Invalid attribute name\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB_NAME_SAW_WHITE:\n\t\t\t\t\tif (c === \"=\") parser.state = S.ATTRIB_VALUE;\n\t\t\t\t\telse if (isWhitespace(c)) continue;\n\t\t\t\t\telse {\n\t\t\t\t\t\tstrictFail(parser, \"Attribute without value\");\n\t\t\t\t\t\tparser.tag.attributes[parser.attribName] = \"\";\n\t\t\t\t\t\tparser.attribValue = \"\";\n\t\t\t\t\t\temitNode(parser, \"onattribute\", {\n\t\t\t\t\t\t\tname: parser.attribName,\n\t\t\t\t\t\t\tvalue: \"\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\tparser.attribName = \"\";\n\t\t\t\t\t\tif (c === \">\") openTag(parser);\n\t\t\t\t\t\telse if (isMatch(nameStart, c)) {\n\t\t\t\t\t\t\tparser.attribName = c;\n\t\t\t\t\t\t\tparser.state = S.ATTRIB_NAME;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstrictFail(parser, \"Invalid attribute name\");\n\t\t\t\t\t\t\tparser.state = S.ATTRIB;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB_VALUE:\n\t\t\t\t\tif (isWhitespace(c)) continue;\n\t\t\t\t\telse if (isQuote(c)) {\n\t\t\t\t\t\tparser.q = c;\n\t\t\t\t\t\tparser.state = S.ATTRIB_VALUE_QUOTED;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstrictFail(parser, \"Unquoted attribute value\");\n\t\t\t\t\t\tparser.state = S.ATTRIB_VALUE_UNQUOTED;\n\t\t\t\t\t\tparser.attribValue = c;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB_VALUE_QUOTED:\n\t\t\t\t\tif (c !== parser.q) {\n\t\t\t\t\t\tif (c === \"&\") parser.state = S.ATTRIB_VALUE_ENTITY_Q;\n\t\t\t\t\t\telse parser.attribValue += c;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tattrib(parser);\n\t\t\t\t\tparser.q = \"\";\n\t\t\t\t\tparser.state = S.ATTRIB_VALUE_CLOSED;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB_VALUE_CLOSED:\n\t\t\t\t\tif (isWhitespace(c)) parser.state = S.ATTRIB;\n\t\t\t\t\telse if (c === \">\") openTag(parser);\n\t\t\t\t\telse if (c === \"/\") parser.state = S.OPEN_TAG_SLASH;\n\t\t\t\t\telse if (isMatch(nameStart, c)) {\n\t\t\t\t\t\tstrictFail(parser, \"No whitespace between attributes\");\n\t\t\t\t\t\tparser.attribName = c;\n\t\t\t\t\t\tparser.attribValue = \"\";\n\t\t\t\t\t\tparser.state = S.ATTRIB_NAME;\n\t\t\t\t\t} else strictFail(parser, \"Invalid attribute name\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.ATTRIB_VALUE_UNQUOTED:\n\t\t\t\t\tif (!isAttribEnd(c)) {\n\t\t\t\t\t\tif (c === \"&\") parser.state = S.ATTRIB_VALUE_ENTITY_U;\n\t\t\t\t\t\telse parser.attribValue += c;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tattrib(parser);\n\t\t\t\t\tif (c === \">\") openTag(parser);\n\t\t\t\t\telse parser.state = S.ATTRIB;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.CLOSE_TAG:\n\t\t\t\t\tif (!parser.tagName) if (isWhitespace(c)) continue;\n\t\t\t\t\telse if (notMatch(nameStart, c)) if (parser.script) {\n\t\t\t\t\t\tparser.script += \"\") closeTag(parser);\n\t\t\t\t\telse if (isMatch(nameBody, c)) parser.tagName += c;\n\t\t\t\t\telse if (parser.script) {\n\t\t\t\t\t\tparser.script += \"\") closeTag(parser);\n\t\t\t\t\telse strictFail(parser, \"Invalid characters in closing tag\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase S.TEXT_ENTITY:\n\t\t\t\tcase S.ATTRIB_VALUE_ENTITY_Q:\n\t\t\t\tcase S.ATTRIB_VALUE_ENTITY_U:\n\t\t\t\t\tvar returnState;\n\t\t\t\t\tvar buffer;\n\t\t\t\t\tswitch (parser.state) {\n\t\t\t\t\t\tcase S.TEXT_ENTITY:\n\t\t\t\t\t\t\treturnState = S.TEXT;\n\t\t\t\t\t\t\tbuffer = \"textNode\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase S.ATTRIB_VALUE_ENTITY_Q:\n\t\t\t\t\t\t\treturnState = S.ATTRIB_VALUE_QUOTED;\n\t\t\t\t\t\t\tbuffer = \"attribValue\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase S.ATTRIB_VALUE_ENTITY_U:\n\t\t\t\t\t\t\treturnState = S.ATTRIB_VALUE_UNQUOTED;\n\t\t\t\t\t\t\tbuffer = \"attribValue\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (c === \";\") if (parser.opt.unparsedEntities) {\n\t\t\t\t\t\tvar parsedEntity = parseEntity(parser);\n\t\t\t\t\t\tparser.entity = \"\";\n\t\t\t\t\t\tparser.state = returnState;\n\t\t\t\t\t\tparser.write(parsedEntity);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparser[buffer] += parseEntity(parser);\n\t\t\t\t\t\tparser.entity = \"\";\n\t\t\t\t\t\tparser.state = returnState;\n\t\t\t\t\t}\n\t\t\t\t\telse if (isMatch(parser.entity.length ? entityBody : entityStart, c)) parser.entity += c;\n\t\t\t\t\telse {\n\t\t\t\t\t\tstrictFail(parser, \"Invalid character in entity name\");\n\t\t\t\t\t\tparser[buffer] += \"&\" + parser.entity + c;\n\t\t\t\t\t\tparser.entity = \"\";\n\t\t\t\t\t\tparser.state = returnState;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\tdefault: throw new Error(parser, \"Unknown state: \" + parser.state);\n\t\t\t}\n\t\t}\n\t\tif (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser);\n\t\treturn parser;\n\t}\n\t/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */\n\t/* istanbul ignore next */\n\tif (!String.fromCodePoint) (function() {\n\t\tvar stringFromCharCode = String.fromCharCode;\n\t\tvar floor = Math.floor;\n\t\tvar fromCodePoint = function() {\n\t\t\tvar MAX_SIZE = 16384;\n\t\t\tvar codeUnits = [];\n\t\t\tvar highSurrogate;\n\t\t\tvar lowSurrogate;\n\t\t\tvar index = -1;\n\t\t\tvar length = arguments.length;\n\t\t\tif (!length) return \"\";\n\t\t\tvar result = \"\";\n\t\t\twhile (++index < length) {\n\t\t\t\tvar codePoint = Number(arguments[index]);\n\t\t\t\tif (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) throw RangeError(\"Invalid code point: \" + codePoint);\n\t\t\t\tif (codePoint <= 65535) codeUnits.push(codePoint);\n\t\t\t\telse {\n\t\t\t\t\tcodePoint -= 65536;\n\t\t\t\t\thighSurrogate = (codePoint >> 10) + 55296;\n\t\t\t\t\tlowSurrogate = codePoint % 1024 + 56320;\n\t\t\t\t\tcodeUnits.push(highSurrogate, lowSurrogate);\n\t\t\t\t}\n\t\t\t\tif (index + 1 === length || codeUnits.length > MAX_SIZE) {\n\t\t\t\t\tresult += stringFromCharCode.apply(null, codeUnits);\n\t\t\t\t\tcodeUnits.length = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t\t/* istanbul ignore next */\n\t\tif (Object.defineProperty) Object.defineProperty(String, \"fromCodePoint\", {\n\t\t\tvalue: fromCodePoint,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t\telse String.fromCodePoint = fromCodePoint;\n\t})();\n\treturn sax$1;\n};\nconst sax = initializeSax();\n\n//#endregion\nexport { sax };\n//# sourceMappingURL=sax.js.map","import { compare } from \"../utils/fast-json-patch/src/duplex.js\";\nimport { BaseCumulativeTransformOutputParser } from \"./transform.js\";\nimport \"../utils/json_patch.js\";\nimport { sax } from \"../utils/sax-js/sax.js\";\n\n//#region src/output_parsers/xml.ts\nconst XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n1. String \"\\n \\n \\n \\n\" is a well-formatted instance of the schema. \n2. String \"\\n \\n \" is a badly-formatted instance.\n3. String \"\\n \\n \\n\" is a badly-formatted instance.\n\nHere are the output tags:\n\\`\\`\\`\n{tags}\n\\`\\`\\``;\nvar XMLOutputParser = class extends BaseCumulativeTransformOutputParser {\n\ttags;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.tags = fields?.tags;\n\t}\n\tstatic lc_name() {\n\t\treturn \"XMLOutputParser\";\n\t}\n\tlc_namespace = [\"langchain_core\", \"output_parsers\"];\n\tlc_serializable = true;\n\t_diff(prev, next) {\n\t\tif (!next) return void 0;\n\t\tif (!prev) return [{\n\t\t\top: \"replace\",\n\t\t\tpath: \"\",\n\t\t\tvalue: next\n\t\t}];\n\t\treturn compare(prev, next);\n\t}\n\tasync parsePartialResult(generations) {\n\t\treturn parseXMLMarkdown(generations[0].text);\n\t}\n\tasync parse(text) {\n\t\treturn parseXMLMarkdown(text);\n\t}\n\tgetFormatInstructions() {\n\t\tconst withTags = !!(this.tags && this.tags.length > 0);\n\t\treturn withTags ? XML_FORMAT_INSTRUCTIONS.replace(\"{tags}\", this.tags?.join(\", \") ?? \"\") : XML_FORMAT_INSTRUCTIONS;\n\t}\n};\nconst strip = (text) => text.split(\"\\n\").map((line) => line.replace(/^\\s+/, \"\")).join(\"\\n\").trim();\nconst parseParsedResult = (input) => {\n\tif (Object.keys(input).length === 0) return {};\n\tconst result = {};\n\tif (input.children.length > 0) {\n\t\tresult[input.name] = input.children.map(parseParsedResult);\n\t\treturn result;\n\t} else {\n\t\tresult[input.name] = input.text ?? void 0;\n\t\treturn result;\n\t}\n};\nfunction parseXMLMarkdown(s) {\n\tconst cleanedString = strip(s);\n\tconst parser = sax.parser(true);\n\tlet parsedResult = {};\n\tconst elementStack = [];\n\tparser.onopentag = (node) => {\n\t\tconst element = {\n\t\t\tname: node.name,\n\t\t\tattributes: node.attributes,\n\t\t\tchildren: [],\n\t\t\ttext: \"\",\n\t\t\tisSelfClosing: node.isSelfClosing\n\t\t};\n\t\tif (elementStack.length > 0) {\n\t\t\tconst parentElement = elementStack[elementStack.length - 1];\n\t\t\tparentElement.children.push(element);\n\t\t} else parsedResult = element;\n\t\tif (!node.isSelfClosing) elementStack.push(element);\n\t};\n\tparser.onclosetag = () => {\n\t\tif (elementStack.length > 0) {\n\t\t\tconst lastElement = elementStack.pop();\n\t\t\tif (elementStack.length === 0 && lastElement) parsedResult = lastElement;\n\t\t}\n\t};\n\tparser.ontext = (text) => {\n\t\tif (elementStack.length > 0) {\n\t\t\tconst currentElement = elementStack[elementStack.length - 1];\n\t\t\tcurrentElement.text += text;\n\t\t}\n\t};\n\tparser.onattribute = (attr) => {\n\t\tif (elementStack.length > 0) {\n\t\t\tconst currentElement = elementStack[elementStack.length - 1];\n\t\t\tcurrentElement.attributes[attr.name] = attr.value;\n\t\t}\n\t};\n\tconst match = /```(xml)?(.*)```/s.exec(cleanedString);\n\tconst xmlString = match ? match[2] : cleanedString;\n\tparser.write(xmlString).close();\n\tif (parsedResult && parsedResult.name === \"?xml\") parsedResult = parsedResult.children[0];\n\treturn parseParsedResult(parsedResult);\n}\n\n//#endregion\nexport { XMLOutputParser, XML_FORMAT_INSTRUCTIONS, parseXMLMarkdown };\n//# sourceMappingURL=xml.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { parseJsonMarkdown, parsePartialJson } from \"../utils/json.js\";\nimport { BaseLLMOutputParser, BaseOutputParser, OutputParserException } from \"./base.js\";\nimport { BaseCumulativeTransformOutputParser, BaseTransformOutputParser } from \"./transform.js\";\nimport { BytesOutputParser } from \"./bytes.js\";\nimport { CommaSeparatedListOutputParser, CustomListOutputParser, ListOutputParser, MarkdownListOutputParser, NumberedListOutputParser } from \"./list.js\";\nimport { StringOutputParser } from \"./string.js\";\nimport { AsymmetricStructuredOutputParser, JsonMarkdownStructuredOutputParser, StructuredOutputParser } from \"./structured.js\";\nimport { JsonOutputParser } from \"./json.js\";\nimport { XMLOutputParser, XML_FORMAT_INSTRUCTIONS, parseXMLMarkdown } from \"./xml.js\";\n\n//#region src/output_parsers/index.ts\nvar output_parsers_exports = {};\n__export(output_parsers_exports, {\n\tAsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser,\n\tBaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser,\n\tBaseLLMOutputParser: () => BaseLLMOutputParser,\n\tBaseOutputParser: () => BaseOutputParser,\n\tBaseTransformOutputParser: () => BaseTransformOutputParser,\n\tBytesOutputParser: () => BytesOutputParser,\n\tCommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser,\n\tCustomListOutputParser: () => CustomListOutputParser,\n\tJsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser,\n\tJsonOutputParser: () => JsonOutputParser,\n\tListOutputParser: () => ListOutputParser,\n\tMarkdownListOutputParser: () => MarkdownListOutputParser,\n\tNumberedListOutputParser: () => NumberedListOutputParser,\n\tOutputParserException: () => OutputParserException,\n\tStringOutputParser: () => StringOutputParser,\n\tStructuredOutputParser: () => StructuredOutputParser,\n\tXMLOutputParser: () => XMLOutputParser,\n\tXML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS,\n\tparseJsonMarkdown: () => parseJsonMarkdown,\n\tparsePartialJson: () => parsePartialJson,\n\tparseXMLMarkdown: () => parseXMLMarkdown\n});\n\n//#endregion\nexport { AsymmetricStructuredOutputParser, BaseCumulativeTransformOutputParser, BaseLLMOutputParser, BaseOutputParser, BaseTransformOutputParser, BytesOutputParser, CommaSeparatedListOutputParser, CustomListOutputParser, JsonMarkdownStructuredOutputParser, JsonOutputParser, ListOutputParser, MarkdownListOutputParser, NumberedListOutputParser, OutputParserException, StringOutputParser, StructuredOutputParser, XMLOutputParser, XML_FORMAT_INSTRUCTIONS, output_parsers_exports, parseJsonMarkdown, parsePartialJson, parseXMLMarkdown };\n//# sourceMappingURL=index.js.map","import { parsePartialJson } from \"../../utils/json.js\";\nimport { isAIMessage } from \"../../messages/ai.js\";\nimport { interopSafeParseAsync } from \"../../utils/types/zod.js\";\nimport { OutputParserException } from \"../base.js\";\nimport { BaseCumulativeTransformOutputParser } from \"../transform.js\";\nimport \"../json.js\";\n\n//#region src/output_parsers/openai_tools/json_output_tools_parsers.ts\nfunction parseToolCall(rawToolCall, options) {\n\tif (rawToolCall.function === void 0) return void 0;\n\tlet functionArgs;\n\tif (options?.partial) try {\n\t\tfunctionArgs = parsePartialJson(rawToolCall.function.arguments ?? \"{}\");\n\t} catch {\n\t\treturn void 0;\n\t}\n\telse try {\n\t\tfunctionArgs = JSON.parse(rawToolCall.function.arguments);\n\t} catch (e) {\n\t\tthrow new OutputParserException([\n\t\t\t`Function \"${rawToolCall.function.name}\" arguments:`,\n\t\t\t``,\n\t\t\trawToolCall.function.arguments,\n\t\t\t``,\n\t\t\t`are not valid JSON.`,\n\t\t\t`Error: ${e.message}`\n\t\t].join(\"\\n\"));\n\t}\n\tconst parsedToolCall = {\n\t\tname: rawToolCall.function.name,\n\t\targs: functionArgs,\n\t\ttype: \"tool_call\"\n\t};\n\tif (options?.returnId) parsedToolCall.id = rawToolCall.id;\n\treturn parsedToolCall;\n}\nfunction convertLangChainToolCallToOpenAI(toolCall) {\n\tif (toolCall.id === void 0) throw new Error(`All OpenAI tool calls must have an \"id\" field.`);\n\treturn {\n\t\tid: toolCall.id,\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: toolCall.name,\n\t\t\targuments: JSON.stringify(toolCall.args)\n\t\t}\n\t};\n}\nfunction makeInvalidToolCall(rawToolCall, errorMsg) {\n\treturn {\n\t\tname: rawToolCall.function?.name,\n\t\targs: rawToolCall.function?.arguments,\n\t\tid: rawToolCall.id,\n\t\terror: errorMsg,\n\t\ttype: \"invalid_tool_call\"\n\t};\n}\n/**\n* Class for parsing the output of a tool-calling LLM into a JSON object.\n*/\nvar JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser {\n\tstatic lc_name() {\n\t\treturn \"JsonOutputToolsParser\";\n\t}\n\treturnId = false;\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"output_parsers\",\n\t\t\"openai_tools\"\n\t];\n\tlc_serializable = true;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.returnId = fields?.returnId ?? this.returnId;\n\t}\n\t_diff() {\n\t\tthrow new Error(\"Not supported.\");\n\t}\n\tasync parse() {\n\t\tthrow new Error(\"Not implemented.\");\n\t}\n\tasync parseResult(generations) {\n\t\tconst result = await this.parsePartialResult(generations, false);\n\t\treturn result;\n\t}\n\t/**\n\t* Parses the output and returns a JSON object. If `argsOnly` is true,\n\t* only the arguments of the function call are returned.\n\t* @param generations The output of the LLM to parse.\n\t* @returns A JSON object representation of the function call or its arguments.\n\t*/\n\tasync parsePartialResult(generations, partial = true) {\n\t\tconst message = generations[0].message;\n\t\tlet toolCalls;\n\t\tif (isAIMessage(message) && message.tool_calls?.length) toolCalls = message.tool_calls.map((toolCall) => {\n\t\t\tconst { id,...rest } = toolCall;\n\t\t\tif (!this.returnId) return rest;\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\t...rest\n\t\t\t};\n\t\t});\n\t\telse if (message.additional_kwargs.tool_calls !== void 0) {\n\t\t\tconst rawToolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls));\n\t\t\ttoolCalls = rawToolCalls.map((rawToolCall) => {\n\t\t\t\treturn parseToolCall(rawToolCall, {\n\t\t\t\t\treturnId: this.returnId,\n\t\t\t\t\tpartial\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t\tif (!toolCalls) return [];\n\t\tconst parsedToolCalls = [];\n\t\tfor (const toolCall of toolCalls) if (toolCall !== void 0) {\n\t\t\tconst backwardsCompatibleToolCall = {\n\t\t\t\ttype: toolCall.name,\n\t\t\t\targs: toolCall.args,\n\t\t\t\tid: toolCall.id\n\t\t\t};\n\t\t\tparsedToolCalls.push(backwardsCompatibleToolCall);\n\t\t}\n\t\treturn parsedToolCalls;\n\t}\n};\n/**\n* Class for parsing the output of a tool-calling LLM into a JSON object if you are\n* expecting only a single tool to be called.\n*/\nvar JsonOutputKeyToolsParser = class extends JsonOutputToolsParser {\n\tstatic lc_name() {\n\t\treturn \"JsonOutputKeyToolsParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"output_parsers\",\n\t\t\"openai_tools\"\n\t];\n\tlc_serializable = true;\n\treturnId = false;\n\t/** The type of tool calls to return. */\n\tkeyName;\n\t/** Whether to return only the first tool call. */\n\treturnSingle = false;\n\tzodSchema;\n\tconstructor(params) {\n\t\tsuper(params);\n\t\tthis.keyName = params.keyName;\n\t\tthis.returnSingle = params.returnSingle ?? this.returnSingle;\n\t\tthis.zodSchema = params.zodSchema;\n\t}\n\tasync _validateResult(result) {\n\t\tif (this.zodSchema === void 0) return result;\n\t\tconst zodParsedResult = await interopSafeParseAsync(this.zodSchema, result);\n\t\tif (zodParsedResult.success) return zodParsedResult.data;\n\t\telse throw new OutputParserException(`Failed to parse. Text: \"${JSON.stringify(result, null, 2)}\". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2));\n\t}\n\tasync parsePartialResult(generations) {\n\t\tconst results = await super.parsePartialResult(generations);\n\t\tconst matchingResults = results.filter((result) => result.type === this.keyName);\n\t\tlet returnedValues = matchingResults;\n\t\tif (!matchingResults.length) return void 0;\n\t\tif (!this.returnId) returnedValues = matchingResults.map((result) => result.args);\n\t\tif (this.returnSingle) return returnedValues[0];\n\t\treturn returnedValues;\n\t}\n\tasync parseResult(generations) {\n\t\tconst results = await super.parsePartialResult(generations, false);\n\t\tconst matchingResults = results.filter((result) => result.type === this.keyName);\n\t\tlet returnedValues = matchingResults;\n\t\tif (!matchingResults.length) return void 0;\n\t\tif (!this.returnId) returnedValues = matchingResults.map((result) => result.args);\n\t\tif (this.returnSingle) return this._validateResult(returnedValues[0]);\n\t\tconst toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value)));\n\t\treturn toolCallResults;\n\t}\n};\n\n//#endregion\nexport { JsonOutputKeyToolsParser, JsonOutputToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall };\n//# sourceMappingURL=json_output_tools_parsers.js.map","import { __export } from \"../../_virtual/rolldown_runtime.js\";\nimport { JsonOutputKeyToolsParser, JsonOutputToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall } from \"./json_output_tools_parsers.js\";\n\n//#region src/output_parsers/openai_tools/index.ts\nvar openai_tools_exports = {};\n__export(openai_tools_exports, {\n\tJsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser,\n\tJsonOutputToolsParser: () => JsonOutputToolsParser,\n\tconvertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI,\n\tmakeInvalidToolCall: () => makeInvalidToolCall,\n\tparseToolCall: () => parseToolCall\n});\n\n//#endregion\nexport { JsonOutputKeyToolsParser, JsonOutputToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, openai_tools_exports, parseToolCall };\n//# sourceMappingURL=index.js.map","import { parsePartialJson } from \"../../utils/json.js\";\nimport { compare } from \"../../utils/fast-json-patch/src/duplex.js\";\nimport { BaseLLMOutputParser } from \"../base.js\";\nimport { BaseCumulativeTransformOutputParser } from \"../transform.js\";\nimport \"../../utils/json_patch.js\";\nimport \"../json.js\";\n\n//#region src/output_parsers/openai_functions/json_output_functions_parsers.ts\n/**\n* Class for parsing the output of an LLM. Can be configured to return\n* only the arguments of the function call in the output.\n*/\nvar OutputFunctionsParser = class extends BaseLLMOutputParser {\n\tstatic lc_name() {\n\t\treturn \"OutputFunctionsParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"output_parsers\",\n\t\t\"openai_functions\"\n\t];\n\tlc_serializable = true;\n\targsOnly = true;\n\tconstructor(config) {\n\t\tsuper();\n\t\tthis.argsOnly = config?.argsOnly ?? this.argsOnly;\n\t}\n\t/**\n\t* Parses the output and returns a string representation of the function\n\t* call or its arguments.\n\t* @param generations The output of the LLM to parse.\n\t* @returns A string representation of the function call or its arguments.\n\t*/\n\tasync parseResult(generations) {\n\t\tif (\"message\" in generations[0]) {\n\t\t\tconst gen = generations[0];\n\t\t\tconst functionCall = gen.message.additional_kwargs.function_call;\n\t\t\tif (!functionCall) throw new Error(`No function_call in message ${JSON.stringify(generations)}`);\n\t\t\tif (!functionCall.arguments) throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`);\n\t\t\tif (this.argsOnly) return functionCall.arguments;\n\t\t\treturn JSON.stringify(functionCall);\n\t\t} else throw new Error(`No message in generations ${JSON.stringify(generations)}`);\n\t}\n};\n/**\n* Class for parsing the output of an LLM into a JSON object. Uses an\n* instance of `OutputFunctionsParser` to parse the output.\n*/\nvar JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser {\n\tstatic lc_name() {\n\t\treturn \"JsonOutputFunctionsParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"output_parsers\",\n\t\t\"openai_functions\"\n\t];\n\tlc_serializable = true;\n\toutputParser;\n\targsOnly = true;\n\tconstructor(config) {\n\t\tsuper(config);\n\t\tthis.argsOnly = config?.argsOnly ?? this.argsOnly;\n\t\tthis.outputParser = new OutputFunctionsParser(config);\n\t}\n\t_diff(prev, next) {\n\t\tif (!next) return void 0;\n\t\tconst ops = compare(prev ?? {}, next);\n\t\treturn ops;\n\t}\n\tasync parsePartialResult(generations) {\n\t\tconst generation = generations[0];\n\t\tif (!generation.message) return void 0;\n\t\tconst { message } = generation;\n\t\tconst functionCall = message.additional_kwargs.function_call;\n\t\tif (!functionCall) return void 0;\n\t\tif (this.argsOnly) return parsePartialJson(functionCall.arguments);\n\t\treturn {\n\t\t\t...functionCall,\n\t\t\targuments: parsePartialJson(functionCall.arguments)\n\t\t};\n\t}\n\t/**\n\t* Parses the output and returns a JSON object. If `argsOnly` is true,\n\t* only the arguments of the function call are returned.\n\t* @param generations The output of the LLM to parse.\n\t* @returns A JSON object representation of the function call or its arguments.\n\t*/\n\tasync parseResult(generations) {\n\t\tconst result = await this.outputParser.parseResult(generations);\n\t\tif (!result) throw new Error(`No result from \"OutputFunctionsParser\" ${JSON.stringify(generations)}`);\n\t\treturn this.parse(result);\n\t}\n\tasync parse(text) {\n\t\tconst parsedResult = JSON.parse(text);\n\t\tif (this.argsOnly) return parsedResult;\n\t\tparsedResult.arguments = JSON.parse(parsedResult.arguments);\n\t\treturn parsedResult;\n\t}\n\tgetFormatInstructions() {\n\t\treturn \"\";\n\t}\n};\n/**\n* Class for parsing the output of an LLM into a JSON object and returning\n* a specific attribute. Uses an instance of `JsonOutputFunctionsParser`\n* to parse the output.\n*/\nvar JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser {\n\tstatic lc_name() {\n\t\treturn \"JsonKeyOutputFunctionsParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"output_parsers\",\n\t\t\"openai_functions\"\n\t];\n\tlc_serializable = true;\n\toutputParser = new JsonOutputFunctionsParser();\n\tattrName;\n\tget lc_aliases() {\n\t\treturn { attrName: \"key_name\" };\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.attrName = fields.attrName;\n\t}\n\t/**\n\t* Parses the output and returns a specific attribute of the parsed JSON\n\t* object.\n\t* @param generations The output of the LLM to parse.\n\t* @returns The value of a specific attribute of the parsed JSON object.\n\t*/\n\tasync parseResult(generations) {\n\t\tconst result = await this.outputParser.parseResult(generations);\n\t\treturn result[this.attrName];\n\t}\n};\n\n//#endregion\nexport { JsonKeyOutputFunctionsParser, JsonOutputFunctionsParser, OutputFunctionsParser };\n//# sourceMappingURL=json_output_functions_parsers.js.map","import { __export } from \"../../_virtual/rolldown_runtime.js\";\nimport { JsonKeyOutputFunctionsParser, JsonOutputFunctionsParser, OutputFunctionsParser } from \"./json_output_functions_parsers.js\";\n\n//#region src/output_parsers/openai_functions/index.ts\nvar openai_functions_exports = {};\n__export(openai_functions_exports, {\n\tJsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser,\n\tJsonOutputFunctionsParser: () => JsonOutputFunctionsParser,\n\tOutputFunctionsParser: () => OutputFunctionsParser\n});\n\n//#endregion\nexport { JsonKeyOutputFunctionsParser, JsonOutputFunctionsParser, OutputFunctionsParser, openai_functions_exports };\n//# sourceMappingURL=index.js.map","import { Runnable } from \"../runnables/base.js\";\n\n//#region src/prompts/base.ts\n/**\n* Base class for prompt templates. Exposes a format method that returns a\n* string prompt given a set of input values.\n*/\nvar BasePromptTemplate = class extends Runnable {\n\tlc_serializable = true;\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"prompts\",\n\t\tthis._getPromptType()\n\t];\n\tget lc_attributes() {\n\t\treturn { partialVariables: void 0 };\n\t}\n\tinputVariables;\n\toutputParser;\n\tpartialVariables;\n\t/**\n\t* Metadata to be used for tracing.\n\t*/\n\tmetadata;\n\t/** Tags to be used for tracing. */\n\ttags;\n\tconstructor(input) {\n\t\tsuper(input);\n\t\tconst { inputVariables } = input;\n\t\tif (inputVariables.includes(\"stop\")) throw new Error(\"Cannot have an input variable named 'stop', as it is used internally, please rename.\");\n\t\tObject.assign(this, input);\n\t}\n\t/**\n\t* Merges partial variables and user variables.\n\t* @param userVariables The user variables to merge with the partial variables.\n\t* @returns A Promise that resolves to an object containing the merged variables.\n\t*/\n\tasync mergePartialAndUserVariables(userVariables) {\n\t\tconst partialVariables = this.partialVariables ?? {};\n\t\tconst partialValues = {};\n\t\tfor (const [key, value] of Object.entries(partialVariables)) if (typeof value === \"string\") partialValues[key] = value;\n\t\telse partialValues[key] = await value();\n\t\tconst allKwargs = {\n\t\t\t...partialValues,\n\t\t\t...userVariables\n\t\t};\n\t\treturn allKwargs;\n\t}\n\t/**\n\t* Invokes the prompt template with the given input and options.\n\t* @param input The input to invoke the prompt template with.\n\t* @param options Optional configuration for the callback.\n\t* @returns A Promise that resolves to the output of the prompt template.\n\t*/\n\tasync invoke(input, options) {\n\t\tconst metadata = {\n\t\t\t...this.metadata,\n\t\t\t...options?.metadata\n\t\t};\n\t\tconst tags = [...this.tags ?? [], ...options?.tags ?? []];\n\t\treturn this._callWithConfig((input$1) => this.formatPromptValue(input$1), input, {\n\t\t\t...options,\n\t\t\ttags,\n\t\t\tmetadata,\n\t\t\trunType: \"prompt\"\n\t\t});\n\t}\n};\n\n//#endregion\nexport { BasePromptTemplate };\n//# sourceMappingURL=base.js.map","import { StringPromptValue } from \"../prompt_values.js\";\nimport { BasePromptTemplate } from \"./base.js\";\n\n//#region src/prompts/string.ts\n/**\n* Base class for string prompt templates. It extends the\n* BasePromptTemplate class and overrides the formatPromptValue method to\n* return a StringPromptValue.\n*/\nvar BaseStringPromptTemplate = class extends BasePromptTemplate {\n\t/**\n\t* Formats the prompt given the input values and returns a formatted\n\t* prompt value.\n\t* @param values The input values to format the prompt.\n\t* @returns A Promise that resolves to a formatted prompt value.\n\t*/\n\tasync formatPromptValue(values) {\n\t\tconst formattedPrompt = await this.format(values);\n\t\treturn new StringPromptValue(formattedPrompt);\n\t}\n};\n\n//#endregion\nexport { BaseStringPromptTemplate };\n//# sourceMappingURL=string.js.map","/*!\n * mustache.js - Logic-less {{mustache}} templates with JavaScript\n * http://github.com/janl/mustache.js\n */\n\nvar objectToString = Object.prototype.toString;\nvar isArray = Array.isArray || function isArrayPolyfill (object) {\n return objectToString.call(object) === '[object Array]';\n};\n\nfunction isFunction (object) {\n return typeof object === 'function';\n}\n\n/**\n * More correct typeof string handling array\n * which normally returns typeof 'object'\n */\nfunction typeStr (obj) {\n return isArray(obj) ? 'array' : typeof obj;\n}\n\nfunction escapeRegExp (string) {\n return string.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, '\\\\$&');\n}\n\n/**\n * Null safe way of checking whether or not an object,\n * including its prototype, has a given property\n */\nfunction hasProperty (obj, propName) {\n return obj != null && typeof obj === 'object' && (propName in obj);\n}\n\n/**\n * Safe way of detecting whether or not the given thing is a primitive and\n * whether it has the given property\n */\nfunction primitiveHasOwnProperty (primitive, propName) {\n return (\n primitive != null\n && typeof primitive !== 'object'\n && primitive.hasOwnProperty\n && primitive.hasOwnProperty(propName)\n );\n}\n\n// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577\n// See https://github.com/janl/mustache.js/issues/189\nvar regExpTest = RegExp.prototype.test;\nfunction testRegExp (re, string) {\n return regExpTest.call(re, string);\n}\n\nvar nonSpaceRe = /\\S/;\nfunction isWhitespace (string) {\n return !testRegExp(nonSpaceRe, string);\n}\n\nvar entityMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/',\n '`': '`',\n '=': '='\n};\n\nfunction escapeHtml (string) {\n return String(string).replace(/[&<>\"'`=\\/]/g, function fromEntityMap (s) {\n return entityMap[s];\n });\n}\n\nvar whiteRe = /\\s*/;\nvar spaceRe = /\\s+/;\nvar equalsRe = /\\s*=/;\nvar curlyRe = /\\s*\\}/;\nvar tagRe = /#|\\^|\\/|>|\\{|&|=|!/;\n\n/**\n * Breaks up the given `template` string into a tree of tokens. If the `tags`\n * argument is given here it must be an array with two string values: the\n * opening and closing tags used in the template (e.g. [ \"<%\", \"%>\" ]). Of\n * course, the default is to use mustaches (i.e. mustache.tags).\n *\n * A token is an array with at least 4 elements. The first element is the\n * mustache symbol that was used inside the tag, e.g. \"#\" or \"&\". If the tag\n * did not contain a symbol (i.e. {{myValue}}) this element is \"name\". For\n * all text that appears outside a symbol this element is \"text\".\n *\n * The second element of a token is its \"value\". For mustache tags this is\n * whatever else was inside the tag besides the opening symbol. For text tokens\n * this is the text itself.\n *\n * The third and fourth elements of the token are the start and end indices,\n * respectively, of the token in the original template.\n *\n * Tokens that are the root node of a subtree contain two more elements: 1) an\n * array of tokens in the subtree and 2) the index in the original template at\n * which the closing tag for that section begins.\n *\n * Tokens for partials also contain two more elements: 1) a string value of\n * indendation prior to that tag and 2) the index of that tag on that line -\n * eg a value of 2 indicates the partial is the third tag on this line.\n */\nfunction parseTemplate (template, tags) {\n if (!template)\n return [];\n var lineHasNonSpace = false;\n var sections = []; // Stack to hold section tokens\n var tokens = []; // Buffer to hold the tokens\n var spaces = []; // Indices of whitespace tokens on the current line\n var hasTag = false; // Is there a {{tag}} on the current line?\n var nonSpace = false; // Is there a non-space char on the current line?\n var indentation = ''; // Tracks indentation for tags that use it\n var tagIndex = 0; // Stores a count of number of tags encountered on a line\n\n // Strips all whitespace tokens array for the current line\n // if there was a {{#tag}} on it and otherwise only space.\n function stripSpace () {\n if (hasTag && !nonSpace) {\n while (spaces.length)\n delete tokens[spaces.pop()];\n } else {\n spaces = [];\n }\n\n hasTag = false;\n nonSpace = false;\n }\n\n var openingTagRe, closingTagRe, closingCurlyRe;\n function compileTags (tagsToCompile) {\n if (typeof tagsToCompile === 'string')\n tagsToCompile = tagsToCompile.split(spaceRe, 2);\n\n if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)\n throw new Error('Invalid tags: ' + tagsToCompile);\n\n openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\\\s*');\n closingTagRe = new RegExp('\\\\s*' + escapeRegExp(tagsToCompile[1]));\n closingCurlyRe = new RegExp('\\\\s*' + escapeRegExp('}' + tagsToCompile[1]));\n }\n\n compileTags(tags || mustache.tags);\n\n var scanner = new Scanner(template);\n\n var start, type, value, chr, token, openSection;\n while (!scanner.eos()) {\n start = scanner.pos;\n\n // Match any text between tags.\n value = scanner.scanUntil(openingTagRe);\n\n if (value) {\n for (var i = 0, valueLength = value.length; i < valueLength; ++i) {\n chr = value.charAt(i);\n\n if (isWhitespace(chr)) {\n spaces.push(tokens.length);\n indentation += chr;\n } else {\n nonSpace = true;\n lineHasNonSpace = true;\n indentation += ' ';\n }\n\n tokens.push([ 'text', chr, start, start + 1 ]);\n start += 1;\n\n // Check for whitespace on the current line.\n if (chr === '\\n') {\n stripSpace();\n indentation = '';\n tagIndex = 0;\n lineHasNonSpace = false;\n }\n }\n }\n\n // Match the opening tag.\n if (!scanner.scan(openingTagRe))\n break;\n\n hasTag = true;\n\n // Get the tag type.\n type = scanner.scan(tagRe) || 'name';\n scanner.scan(whiteRe);\n\n // Get the tag value.\n if (type === '=') {\n value = scanner.scanUntil(equalsRe);\n scanner.scan(equalsRe);\n scanner.scanUntil(closingTagRe);\n } else if (type === '{') {\n value = scanner.scanUntil(closingCurlyRe);\n scanner.scan(curlyRe);\n scanner.scanUntil(closingTagRe);\n type = '&';\n } else {\n value = scanner.scanUntil(closingTagRe);\n }\n\n // Match the closing tag.\n if (!scanner.scan(closingTagRe))\n throw new Error('Unclosed tag at ' + scanner.pos);\n\n if (type == '>') {\n token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ];\n } else {\n token = [ type, value, start, scanner.pos ];\n }\n tagIndex++;\n tokens.push(token);\n\n if (type === '#' || type === '^') {\n sections.push(token);\n } else if (type === '/') {\n // Check section nesting.\n openSection = sections.pop();\n\n if (!openSection)\n throw new Error('Unopened section \"' + value + '\" at ' + start);\n\n if (openSection[1] !== value)\n throw new Error('Unclosed section \"' + openSection[1] + '\" at ' + start);\n } else if (type === 'name' || type === '{' || type === '&') {\n nonSpace = true;\n } else if (type === '=') {\n // Set the tags for the next time around.\n compileTags(value);\n }\n }\n\n stripSpace();\n\n // Make sure there are no open sections when we're done.\n openSection = sections.pop();\n\n if (openSection)\n throw new Error('Unclosed section \"' + openSection[1] + '\" at ' + scanner.pos);\n\n return nestTokens(squashTokens(tokens));\n}\n\n/**\n * Combines the values of consecutive text tokens in the given `tokens` array\n * to a single token.\n */\nfunction squashTokens (tokens) {\n var squashedTokens = [];\n\n var token, lastToken;\n for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {\n token = tokens[i];\n\n if (token) {\n if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {\n lastToken[1] += token[1];\n lastToken[3] = token[3];\n } else {\n squashedTokens.push(token);\n lastToken = token;\n }\n }\n }\n\n return squashedTokens;\n}\n\n/**\n * Forms the given array of `tokens` into a nested tree structure where\n * tokens that represent a section have two additional items: 1) an array of\n * all tokens that appear in that section and 2) the index in the original\n * template that represents the end of that section.\n */\nfunction nestTokens (tokens) {\n var nestedTokens = [];\n var collector = nestedTokens;\n var sections = [];\n\n var token, section;\n for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {\n token = tokens[i];\n\n switch (token[0]) {\n case '#':\n case '^':\n collector.push(token);\n sections.push(token);\n collector = token[4] = [];\n break;\n case '/':\n section = sections.pop();\n section[5] = token[2];\n collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;\n break;\n default:\n collector.push(token);\n }\n }\n\n return nestedTokens;\n}\n\n/**\n * A simple string scanner that is used by the template parser to find\n * tokens in template strings.\n */\nfunction Scanner (string) {\n this.string = string;\n this.tail = string;\n this.pos = 0;\n}\n\n/**\n * Returns `true` if the tail is empty (end of string).\n */\nScanner.prototype.eos = function eos () {\n return this.tail === '';\n};\n\n/**\n * Tries to match the given regular expression at the current position.\n * Returns the matched text if it can match, the empty string otherwise.\n */\nScanner.prototype.scan = function scan (re) {\n var match = this.tail.match(re);\n\n if (!match || match.index !== 0)\n return '';\n\n var string = match[0];\n\n this.tail = this.tail.substring(string.length);\n this.pos += string.length;\n\n return string;\n};\n\n/**\n * Skips all text until the given regular expression can be matched. Returns\n * the skipped string, which is the entire tail if no match can be made.\n */\nScanner.prototype.scanUntil = function scanUntil (re) {\n var index = this.tail.search(re), match;\n\n switch (index) {\n case -1:\n match = this.tail;\n this.tail = '';\n break;\n case 0:\n match = '';\n break;\n default:\n match = this.tail.substring(0, index);\n this.tail = this.tail.substring(index);\n }\n\n this.pos += match.length;\n\n return match;\n};\n\n/**\n * Represents a rendering context by wrapping a view object and\n * maintaining a reference to the parent context.\n */\nfunction Context (view, parentContext) {\n this.view = view;\n this.cache = { '.': this.view };\n this.parent = parentContext;\n}\n\n/**\n * Creates a new context using the given view with this context\n * as the parent.\n */\nContext.prototype.push = function push (view) {\n return new Context(view, this);\n};\n\n/**\n * Returns the value of the given name in this context, traversing\n * up the context hierarchy if the value is absent in this context's view.\n */\nContext.prototype.lookup = function lookup (name) {\n var cache = this.cache;\n\n var value;\n if (cache.hasOwnProperty(name)) {\n value = cache[name];\n } else {\n var context = this, intermediateValue, names, index, lookupHit = false;\n\n while (context) {\n if (name.indexOf('.') > 0) {\n intermediateValue = context.view;\n names = name.split('.');\n index = 0;\n\n /**\n * Using the dot notion path in `name`, we descend through the\n * nested objects.\n *\n * To be certain that the lookup has been successful, we have to\n * check if the last object in the path actually has the property\n * we are looking for. We store the result in `lookupHit`.\n *\n * This is specially necessary for when the value has been set to\n * `undefined` and we want to avoid looking up parent contexts.\n *\n * In the case where dot notation is used, we consider the lookup\n * to be successful even if the last \"object\" in the path is\n * not actually an object but a primitive (e.g., a string, or an\n * integer), because it is sometimes useful to access a property\n * of an autoboxed primitive, such as the length of a string.\n **/\n while (intermediateValue != null && index < names.length) {\n if (index === names.length - 1)\n lookupHit = (\n hasProperty(intermediateValue, names[index])\n || primitiveHasOwnProperty(intermediateValue, names[index])\n );\n\n intermediateValue = intermediateValue[names[index++]];\n }\n } else {\n intermediateValue = context.view[name];\n\n /**\n * Only checking against `hasProperty`, which always returns `false` if\n * `context.view` is not an object. Deliberately omitting the check\n * against `primitiveHasOwnProperty` if dot notation is not used.\n *\n * Consider this example:\n * ```\n * Mustache.render(\"The length of a football field is {{#length}}{{length}}{{/length}}.\", {length: \"100 yards\"})\n * ```\n *\n * If we were to check also against `primitiveHasOwnProperty`, as we do\n * in the dot notation case, then render call would return:\n *\n * \"The length of a football field is 9.\"\n *\n * rather than the expected:\n *\n * \"The length of a football field is 100 yards.\"\n **/\n lookupHit = hasProperty(context.view, name);\n }\n\n if (lookupHit) {\n value = intermediateValue;\n break;\n }\n\n context = context.parent;\n }\n\n cache[name] = value;\n }\n\n if (isFunction(value))\n value = value.call(this.view);\n\n return value;\n};\n\n/**\n * A Writer knows how to take a stream of tokens and render them to a\n * string, given a context. It also maintains a cache of templates to\n * avoid the need to parse the same template twice.\n */\nfunction Writer () {\n this.templateCache = {\n _cache: {},\n set: function set (key, value) {\n this._cache[key] = value;\n },\n get: function get (key) {\n return this._cache[key];\n },\n clear: function clear () {\n this._cache = {};\n }\n };\n}\n\n/**\n * Clears all cached templates in this writer.\n */\nWriter.prototype.clearCache = function clearCache () {\n if (typeof this.templateCache !== 'undefined') {\n this.templateCache.clear();\n }\n};\n\n/**\n * Parses and caches the given `template` according to the given `tags` or\n * `mustache.tags` if `tags` is omitted, and returns the array of tokens\n * that is generated from the parse.\n */\nWriter.prototype.parse = function parse (template, tags) {\n var cache = this.templateCache;\n var cacheKey = template + ':' + (tags || mustache.tags).join(':');\n var isCacheEnabled = typeof cache !== 'undefined';\n var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;\n\n if (tokens == undefined) {\n tokens = parseTemplate(template, tags);\n isCacheEnabled && cache.set(cacheKey, tokens);\n }\n return tokens;\n};\n\n/**\n * High-level method that is used to render the given `template` with\n * the given `view`.\n *\n * The optional `partials` argument may be an object that contains the\n * names and templates of partials that are used in the template. It may\n * also be a function that is used to load partial templates on the fly\n * that takes a single argument: the name of the partial.\n *\n * If the optional `config` argument is given here, then it should be an\n * object with a `tags` attribute or an `escape` attribute or both.\n * If an array is passed, then it will be interpreted the same way as\n * a `tags` attribute on a `config` object.\n *\n * The `tags` attribute of a `config` object must be an array with two\n * string values: the opening and closing tags used in the template (e.g.\n * [ \"<%\", \"%>\" ]). The default is to mustache.tags.\n *\n * The `escape` attribute of a `config` object must be a function which\n * accepts a string as input and outputs a safely escaped string.\n * If an `escape` function is not provided, then an HTML-safe string\n * escaping function is used as the default.\n */\nWriter.prototype.render = function render (template, view, partials, config) {\n var tags = this.getConfigTags(config);\n var tokens = this.parse(template, tags);\n var context = (view instanceof Context) ? view : new Context(view, undefined);\n return this.renderTokens(tokens, context, partials, template, config);\n};\n\n/**\n * Low-level method that renders the given array of `tokens` using\n * the given `context` and `partials`.\n *\n * Note: The `originalTemplate` is only ever used to extract the portion\n * of the original template that was contained in a higher-order section.\n * If the template doesn't use higher-order sections, this argument may\n * be omitted.\n */\nWriter.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) {\n var buffer = '';\n\n var token, symbol, value;\n for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {\n value = undefined;\n token = tokens[i];\n symbol = token[0];\n\n if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config);\n else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config);\n else if (symbol === '>') value = this.renderPartial(token, context, partials, config);\n else if (symbol === '&') value = this.unescapedValue(token, context);\n else if (symbol === 'name') value = this.escapedValue(token, context, config);\n else if (symbol === 'text') value = this.rawValue(token);\n\n if (value !== undefined)\n buffer += value;\n }\n\n return buffer;\n};\n\nWriter.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) {\n var self = this;\n var buffer = '';\n var value = context.lookup(token[1]);\n\n // This function is used to render an arbitrary template\n // in the current context by higher-order sections.\n function subRender (template) {\n return self.render(template, context, partials, config);\n }\n\n if (!value) return;\n\n if (isArray(value)) {\n for (var j = 0, valueLength = value.length; j < valueLength; ++j) {\n buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config);\n }\n } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {\n buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);\n } else if (isFunction(value)) {\n if (typeof originalTemplate !== 'string')\n throw new Error('Cannot use higher-order sections without the original template');\n\n // Extract the portion of the original template that the section contains.\n value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);\n\n if (value != null)\n buffer += value;\n } else {\n buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);\n }\n return buffer;\n};\n\nWriter.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) {\n var value = context.lookup(token[1]);\n\n // Use JavaScript's definition of falsy. Include empty arrays.\n // See https://github.com/janl/mustache.js/issues/186\n if (!value || (isArray(value) && value.length === 0))\n return this.renderTokens(token[4], context, partials, originalTemplate, config);\n};\n\nWriter.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {\n var filteredIndentation = indentation.replace(/[^ \\t]/g, '');\n var partialByNl = partial.split('\\n');\n for (var i = 0; i < partialByNl.length; i++) {\n if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {\n partialByNl[i] = filteredIndentation + partialByNl[i];\n }\n }\n return partialByNl.join('\\n');\n};\n\nWriter.prototype.renderPartial = function renderPartial (token, context, partials, config) {\n if (!partials) return;\n var tags = this.getConfigTags(config);\n\n var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];\n if (value != null) {\n var lineHasNonSpace = token[6];\n var tagIndex = token[5];\n var indentation = token[4];\n var indentedValue = value;\n if (tagIndex == 0 && indentation) {\n indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);\n }\n var tokens = this.parse(indentedValue, tags);\n return this.renderTokens(tokens, context, partials, indentedValue, config);\n }\n};\n\nWriter.prototype.unescapedValue = function unescapedValue (token, context) {\n var value = context.lookup(token[1]);\n if (value != null)\n return value;\n};\n\nWriter.prototype.escapedValue = function escapedValue (token, context, config) {\n var escape = this.getConfigEscape(config) || mustache.escape;\n var value = context.lookup(token[1]);\n if (value != null)\n return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value);\n};\n\nWriter.prototype.rawValue = function rawValue (token) {\n return token[1];\n};\n\nWriter.prototype.getConfigTags = function getConfigTags (config) {\n if (isArray(config)) {\n return config;\n }\n else if (config && typeof config === 'object') {\n return config.tags;\n }\n else {\n return undefined;\n }\n};\n\nWriter.prototype.getConfigEscape = function getConfigEscape (config) {\n if (config && typeof config === 'object' && !isArray(config)) {\n return config.escape;\n }\n else {\n return undefined;\n }\n};\n\nvar mustache = {\n name: 'mustache.js',\n version: '4.2.0',\n tags: [ '{{', '}}' ],\n clearCache: undefined,\n escape: undefined,\n parse: undefined,\n render: undefined,\n Scanner: undefined,\n Context: undefined,\n Writer: undefined,\n /**\n * Allows a user to override the default caching strategy, by providing an\n * object with set, get and clear methods. This can also be used to disable\n * the cache by setting it to the literal `undefined`.\n */\n set templateCache (cache) {\n defaultWriter.templateCache = cache;\n },\n /**\n * Gets the default or overridden caching object from the default writer.\n */\n get templateCache () {\n return defaultWriter.templateCache;\n }\n};\n\n// All high-level mustache.* functions use this writer.\nvar defaultWriter = new Writer();\n\n/**\n * Clears all cached templates in the default writer.\n */\nmustache.clearCache = function clearCache () {\n return defaultWriter.clearCache();\n};\n\n/**\n * Parses and caches the given template in the default writer and returns the\n * array of tokens it contains. Doing this ahead of time avoids the need to\n * parse templates on the fly as they are rendered.\n */\nmustache.parse = function parse (template, tags) {\n return defaultWriter.parse(template, tags);\n};\n\n/**\n * Renders the `template` with the given `view`, `partials`, and `config`\n * using the default writer.\n */\nmustache.render = function render (template, view, partials, config) {\n if (typeof template !== 'string') {\n throw new TypeError('Invalid template! Template should be a \"string\" ' +\n 'but \"' + typeStr(template) + '\" was given as the first ' +\n 'argument for mustache#render(template, view, partials)');\n }\n\n return defaultWriter.render(template, view, partials, config);\n};\n\n// Export the escaping function so that the user may override it.\n// See https://github.com/janl/mustache.js/issues/244\nmustache.escape = escapeHtml;\n\n// Export these mainly for testing, but also for advanced usage.\nmustache.Scanner = Scanner;\nmustache.Context = Context;\nmustache.Writer = Writer;\n\nexport default mustache;\n","import { addLangChainErrorFields } from \"../errors/index.js\";\nimport mustache from \"mustache\";\n\n//#region src/prompts/template.ts\nfunction configureMustache() {\n\tmustache.escape = (text) => text;\n}\nconst parseFString = (template) => {\n\tconst chars = template.split(\"\");\n\tconst nodes = [];\n\tconst nextBracket = (bracket, start) => {\n\t\tfor (let i$1 = start; i$1 < chars.length; i$1 += 1) if (bracket.includes(chars[i$1])) return i$1;\n\t\treturn -1;\n\t};\n\tlet i = 0;\n\twhile (i < chars.length) if (chars[i] === \"{\" && i + 1 < chars.length && chars[i + 1] === \"{\") {\n\t\tnodes.push({\n\t\t\ttype: \"literal\",\n\t\t\ttext: \"{\"\n\t\t});\n\t\ti += 2;\n\t} else if (chars[i] === \"}\" && i + 1 < chars.length && chars[i + 1] === \"}\") {\n\t\tnodes.push({\n\t\t\ttype: \"literal\",\n\t\t\ttext: \"}\"\n\t\t});\n\t\ti += 2;\n\t} else if (chars[i] === \"{\") {\n\t\tconst j = nextBracket(\"}\", i);\n\t\tif (j < 0) throw new Error(\"Unclosed '{' in template.\");\n\t\tnodes.push({\n\t\t\ttype: \"variable\",\n\t\t\tname: chars.slice(i + 1, j).join(\"\")\n\t\t});\n\t\ti = j + 1;\n\t} else if (chars[i] === \"}\") throw new Error(\"Single '}' in template.\");\n\telse {\n\t\tconst next = nextBracket(\"{}\", i);\n\t\tconst text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(\"\");\n\t\tnodes.push({\n\t\t\ttype: \"literal\",\n\t\t\ttext\n\t\t});\n\t\ti = next < 0 ? chars.length : next;\n\t}\n\treturn nodes;\n};\n/**\n* Convert the result of mustache.parse into an array of ParsedTemplateNode,\n* to make it compatible with other LangChain string parsing template formats.\n*\n* @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library.\n* @param {string[]} context Array of section variable names for nested context\n* @returns {ParsedTemplateNode[]}\n*/\nconst mustacheTemplateToNodes = (template, context = []) => {\n\tconst nodes = [];\n\tfor (const temp of template) if (temp[0] === \"name\") {\n\t\tconst name = temp[1].includes(\".\") ? temp[1].split(\".\")[0] : temp[1];\n\t\tnodes.push({\n\t\t\ttype: \"variable\",\n\t\t\tname\n\t\t});\n\t} else if ([\n\t\t\"#\",\n\t\t\"&\",\n\t\t\"^\",\n\t\t\">\"\n\t].includes(temp[0])) {\n\t\tnodes.push({\n\t\t\ttype: \"variable\",\n\t\t\tname: temp[1]\n\t\t});\n\t\tif (temp[0] === \"#\" && temp.length > 4 && Array.isArray(temp[4])) {\n\t\t\tconst newContext = [...context, temp[1]];\n\t\t\tconst nestedNodes = mustacheTemplateToNodes(temp[4], newContext);\n\t\t\tnodes.push(...nestedNodes);\n\t\t}\n\t} else nodes.push({\n\t\ttype: \"literal\",\n\t\ttext: temp[1]\n\t});\n\treturn nodes;\n};\nconst parseMustache = (template) => {\n\tconfigureMustache();\n\tconst parsed = mustache.parse(template);\n\treturn mustacheTemplateToNodes(parsed);\n};\nconst interpolateFString = (template, values) => {\n\treturn parseFString(template).reduce((res, node) => {\n\t\tif (node.type === \"variable\") {\n\t\t\tif (node.name in values) {\n\t\t\t\tconst stringValue = typeof values[node.name] === \"string\" ? values[node.name] : JSON.stringify(values[node.name]);\n\t\t\t\treturn res + stringValue;\n\t\t\t}\n\t\t\tthrow new Error(`(f-string) Missing value for input ${node.name}`);\n\t\t}\n\t\treturn res + node.text;\n\t}, \"\");\n};\nconst interpolateMustache = (template, values) => {\n\tconfigureMustache();\n\treturn mustache.render(template, values);\n};\nconst DEFAULT_FORMATTER_MAPPING = {\n\t\"f-string\": interpolateFString,\n\tmustache: interpolateMustache\n};\nconst DEFAULT_PARSER_MAPPING = {\n\t\"f-string\": parseFString,\n\tmustache: parseMustache\n};\nconst renderTemplate = (template, templateFormat, inputValues) => {\n\ttry {\n\t\treturn DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);\n\t} catch (e) {\n\t\tconst error = addLangChainErrorFields(e, \"INVALID_PROMPT_INPUT\");\n\t\tthrow error;\n\t}\n};\nconst parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template);\nconst checkValidTemplate = (template, templateFormat, inputVariables) => {\n\tif (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) {\n\t\tconst validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING);\n\t\tthrow new Error(`Invalid template format. Got \\`${templateFormat}\\`;\n should be one of ${validFormats}`);\n\t}\n\ttry {\n\t\tconst dummyInputs = inputVariables.reduce((acc, v) => {\n\t\t\tacc[v] = \"foo\";\n\t\t\treturn acc;\n\t\t}, {});\n\t\tif (Array.isArray(template)) template.forEach((message) => {\n\t\t\tif (message.type === \"text\" && \"text\" in message && typeof message.text === \"string\") renderTemplate(message.text, templateFormat, dummyInputs);\n\t\t\telse if (message.type === \"image_url\") {\n\t\t\t\tif (typeof message.image_url === \"string\") renderTemplate(message.image_url, templateFormat, dummyInputs);\n\t\t\t\telse if (typeof message.image_url === \"object\" && message.image_url !== null && \"url\" in message.image_url && typeof message.image_url.url === \"string\") {\n\t\t\t\t\tconst imageUrl = message.image_url.url;\n\t\t\t\t\trenderTemplate(imageUrl, templateFormat, dummyInputs);\n\t\t\t\t}\n\t\t\t} else throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`);\n\t\t});\n\t\telse renderTemplate(template, templateFormat, dummyInputs);\n\t} catch (e) {\n\t\tthrow new Error(`Invalid prompt schema: ${e.message}`);\n\t}\n};\n\n//#endregion\nexport { DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, checkValidTemplate, interpolateFString, interpolateMustache, parseFString, parseMustache, parseTemplate, renderTemplate };\n//# sourceMappingURL=template.js.map","import { BaseStringPromptTemplate } from \"./string.js\";\nimport { checkValidTemplate, parseTemplate, renderTemplate } from \"./template.js\";\n\n//#region src/prompts/prompt.ts\n/**\n* Schema to represent a basic prompt for an LLM.\n* @augments BasePromptTemplate\n* @augments PromptTemplateInput\n*\n* @example\n* ```ts\n* import { PromptTemplate } from \"langchain/prompts\";\n*\n* const prompt = new PromptTemplate({\n* inputVariables: [\"foo\"],\n* template: \"Say {foo}\",\n* });\n* ```\n*/\nvar PromptTemplate = class PromptTemplate extends BaseStringPromptTemplate {\n\tstatic lc_name() {\n\t\treturn \"PromptTemplate\";\n\t}\n\ttemplate;\n\ttemplateFormat = \"f-string\";\n\tvalidateTemplate = true;\n\t/**\n\t* Additional fields which should be included inside\n\t* the message content array if using a complex message\n\t* content.\n\t*/\n\tadditionalContentFields;\n\tconstructor(input) {\n\t\tsuper(input);\n\t\tif (input.templateFormat === \"mustache\" && input.validateTemplate === void 0) this.validateTemplate = false;\n\t\tObject.assign(this, input);\n\t\tif (this.validateTemplate) {\n\t\t\tif (this.templateFormat === \"mustache\") throw new Error(\"Mustache templates cannot be validated.\");\n\t\t\tlet totalInputVariables = this.inputVariables;\n\t\t\tif (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));\n\t\t\tcheckValidTemplate(this.template, this.templateFormat, totalInputVariables);\n\t\t}\n\t}\n\t_getPromptType() {\n\t\treturn \"prompt\";\n\t}\n\t/**\n\t* Formats the prompt template with the provided values.\n\t* @param values The values to be used to format the prompt template.\n\t* @returns A promise that resolves to a string which is the formatted prompt.\n\t*/\n\tasync format(values) {\n\t\tconst allValues = await this.mergePartialAndUserVariables(values);\n\t\treturn renderTemplate(this.template, this.templateFormat, allValues);\n\t}\n\t/**\n\t* Take examples in list format with prefix and suffix to create a prompt.\n\t*\n\t* Intended to be used a a way to dynamically create a prompt from examples.\n\t*\n\t* @param examples - List of examples to use in the prompt.\n\t* @param suffix - String to go after the list of examples. Should generally set up the user's input.\n\t* @param inputVariables - A list of variable names the final prompt template will expect\n\t* @param exampleSeparator - The separator to use in between examples\n\t* @param prefix - String that should go before any examples. Generally includes examples.\n\t*\n\t* @returns The final prompt template generated.\n\t*/\n\tstatic fromExamples(examples, suffix, inputVariables, exampleSeparator = \"\\n\\n\", prefix = \"\") {\n\t\tconst template = [\n\t\t\tprefix,\n\t\t\t...examples,\n\t\t\tsuffix\n\t\t].join(exampleSeparator);\n\t\treturn new PromptTemplate({\n\t\t\tinputVariables,\n\t\t\ttemplate\n\t\t});\n\t}\n\tstatic fromTemplate(template, options) {\n\t\tconst { templateFormat = \"f-string\",...rest } = options ?? {};\n\t\tconst names = /* @__PURE__ */ new Set();\n\t\tparseTemplate(template, templateFormat).forEach((node) => {\n\t\t\tif (node.type === \"variable\") names.add(node.name);\n\t\t});\n\t\treturn new PromptTemplate({\n\t\t\tinputVariables: [...names],\n\t\t\ttemplateFormat,\n\t\t\ttemplate,\n\t\t\t...rest\n\t\t});\n\t}\n\t/**\n\t* Partially applies values to the prompt template.\n\t* @param values The values to be partially applied to the prompt template.\n\t* @returns A new instance of PromptTemplate with the partially applied values.\n\t*/\n\tasync partial(values) {\n\t\tconst newInputVariables = this.inputVariables.filter((iv) => !(iv in values));\n\t\tconst newPartialVariables = {\n\t\t\t...this.partialVariables ?? {},\n\t\t\t...values\n\t\t};\n\t\tconst promptDict = {\n\t\t\t...this,\n\t\t\tinputVariables: newInputVariables,\n\t\t\tpartialVariables: newPartialVariables\n\t\t};\n\t\treturn new PromptTemplate(promptDict);\n\t}\n\tserialize() {\n\t\tif (this.outputParser !== void 0) throw new Error(\"Cannot serialize a prompt template with an output parser\");\n\t\treturn {\n\t\t\t_type: this._getPromptType(),\n\t\t\tinput_variables: this.inputVariables,\n\t\t\ttemplate: this.template,\n\t\t\ttemplate_format: this.templateFormat\n\t\t};\n\t}\n\tstatic async deserialize(data) {\n\t\tif (!data.template) throw new Error(\"Prompt template must have a template\");\n\t\tconst res = new PromptTemplate({\n\t\t\tinputVariables: data.input_variables,\n\t\t\ttemplate: data.template,\n\t\t\ttemplateFormat: data.template_format\n\t\t});\n\t\treturn res;\n\t}\n};\n\n//#endregion\nexport { PromptTemplate };\n//# sourceMappingURL=prompt.js.map","import { ImagePromptValue } from \"../prompt_values.js\";\nimport { BasePromptTemplate } from \"./base.js\";\nimport { checkValidTemplate, renderTemplate } from \"./template.js\";\n\n//#region src/prompts/image.ts\n/**\n* An image prompt template for a multimodal model.\n*/\nvar ImagePromptTemplate = class ImagePromptTemplate extends BasePromptTemplate {\n\tstatic lc_name() {\n\t\treturn \"ImagePromptTemplate\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"prompts\",\n\t\t\"image\"\n\t];\n\ttemplate;\n\ttemplateFormat = \"f-string\";\n\tvalidateTemplate = true;\n\t/**\n\t* Additional fields which should be included inside\n\t* the message content array if using a complex message\n\t* content.\n\t*/\n\tadditionalContentFields;\n\tconstructor(input) {\n\t\tsuper(input);\n\t\tthis.template = input.template;\n\t\tthis.templateFormat = input.templateFormat ?? this.templateFormat;\n\t\tthis.validateTemplate = input.validateTemplate ?? this.validateTemplate;\n\t\tthis.additionalContentFields = input.additionalContentFields;\n\t\tif (this.validateTemplate) {\n\t\t\tlet totalInputVariables = this.inputVariables;\n\t\t\tif (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));\n\t\t\tcheckValidTemplate([{\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: this.template\n\t\t\t}], this.templateFormat, totalInputVariables);\n\t\t}\n\t}\n\t_getPromptType() {\n\t\treturn \"prompt\";\n\t}\n\t/**\n\t* Partially applies values to the prompt template.\n\t* @param values The values to be partially applied to the prompt template.\n\t* @returns A new instance of ImagePromptTemplate with the partially applied values.\n\t*/\n\tasync partial(values) {\n\t\tconst newInputVariables = this.inputVariables.filter((iv) => !(iv in values));\n\t\tconst newPartialVariables = {\n\t\t\t...this.partialVariables ?? {},\n\t\t\t...values\n\t\t};\n\t\tconst promptDict = {\n\t\t\t...this,\n\t\t\tinputVariables: newInputVariables,\n\t\t\tpartialVariables: newPartialVariables\n\t\t};\n\t\treturn new ImagePromptTemplate(promptDict);\n\t}\n\t/**\n\t* Formats the prompt template with the provided values.\n\t* @param values The values to be used to format the prompt template.\n\t* @returns A promise that resolves to a string which is the formatted prompt.\n\t*/\n\tasync format(values) {\n\t\tconst formatted = {};\n\t\tfor (const [key, value] of Object.entries(this.template)) if (typeof value === \"string\") formatted[key] = renderTemplate(value, this.templateFormat, values);\n\t\telse formatted[key] = value;\n\t\tconst url = values.url || formatted.url;\n\t\tconst detail = values.detail || formatted.detail;\n\t\tif (!url) throw new Error(\"Must provide either an image URL.\");\n\t\tif (typeof url !== \"string\") throw new Error(\"url must be a string.\");\n\t\tconst output = { url };\n\t\tif (detail) output.detail = detail;\n\t\treturn output;\n\t}\n\t/**\n\t* Formats the prompt given the input values and returns a formatted\n\t* prompt value.\n\t* @param values The input values to format the prompt.\n\t* @returns A Promise that resolves to a formatted prompt value.\n\t*/\n\tasync formatPromptValue(values) {\n\t\tconst formattedPrompt = await this.format(values);\n\t\treturn new ImagePromptValue(formattedPrompt);\n\t}\n};\n\n//#endregion\nexport { ImagePromptTemplate };\n//# sourceMappingURL=image.js.map","import { Runnable } from \"../runnables/base.js\";\nimport { parseTemplate, renderTemplate } from \"./template.js\";\n\n//#region src/prompts/dict.ts\nvar DictPromptTemplate = class extends Runnable {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"prompts\",\n\t\t\"dict\"\n\t];\n\tlc_serializable = true;\n\ttemplate;\n\ttemplateFormat;\n\tinputVariables;\n\tstatic lc_name() {\n\t\treturn \"DictPromptTemplate\";\n\t}\n\tconstructor(fields) {\n\t\tconst templateFormat = fields.templateFormat ?? \"f-string\";\n\t\tconst inputVariables = _getInputVariables(fields.template, templateFormat);\n\t\tsuper({\n\t\t\tinputVariables,\n\t\t\t...fields\n\t\t});\n\t\tthis.template = fields.template;\n\t\tthis.templateFormat = templateFormat;\n\t\tthis.inputVariables = inputVariables;\n\t}\n\tasync format(values) {\n\t\treturn _insertInputVariables(this.template, values, this.templateFormat);\n\t}\n\tasync invoke(values) {\n\t\treturn await this._callWithConfig(this.format.bind(this), values, { runType: \"prompt\" });\n\t}\n};\nfunction _getInputVariables(template, templateFormat) {\n\tconst inputVariables = [];\n\tfor (const v of Object.values(template)) if (typeof v === \"string\") parseTemplate(v, templateFormat).forEach((t) => {\n\t\tif (t.type === \"variable\") inputVariables.push(t.name);\n\t});\n\telse if (Array.isArray(v)) {\n\t\tfor (const x of v) if (typeof x === \"string\") parseTemplate(x, templateFormat).forEach((t) => {\n\t\t\tif (t.type === \"variable\") inputVariables.push(t.name);\n\t\t});\n\t\telse if (typeof x === \"object\") inputVariables.push(..._getInputVariables(x, templateFormat));\n\t} else if (typeof v === \"object\" && v !== null) inputVariables.push(..._getInputVariables(v, templateFormat));\n\treturn Array.from(new Set(inputVariables));\n}\nfunction _insertInputVariables(template, inputs, templateFormat) {\n\tconst formatted = {};\n\tfor (const [k, v] of Object.entries(template)) if (typeof v === \"string\") formatted[k] = renderTemplate(v, templateFormat, inputs);\n\telse if (Array.isArray(v)) {\n\t\tconst formattedV = [];\n\t\tfor (const x of v) if (typeof x === \"string\") formattedV.push(renderTemplate(x, templateFormat, inputs));\n\t\telse if (typeof x === \"object\") formattedV.push(_insertInputVariables(x, inputs, templateFormat));\n\t\tformatted[k] = formattedV;\n\t} else if (typeof v === \"object\" && v !== null) formatted[k] = _insertInputVariables(v, inputs, templateFormat);\n\telse formatted[k] = v;\n\treturn formatted;\n}\n\n//#endregion\nexport { DictPromptTemplate };\n//# sourceMappingURL=dict.js.map","import { BaseMessage, isBaseMessage } from \"../messages/base.js\";\nimport { AIMessage } from \"../messages/ai.js\";\nimport { ChatMessage } from \"../messages/chat.js\";\nimport { HumanMessage } from \"../messages/human.js\";\nimport { SystemMessage } from \"../messages/system.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport \"../messages/index.js\";\nimport { ChatPromptValue } from \"../prompt_values.js\";\nimport { BasePromptTemplate } from \"./base.js\";\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport { parseFString, parseMustache } from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport { ImagePromptTemplate } from \"./image.js\";\nimport { DictPromptTemplate } from \"./dict.js\";\n\n//#region src/prompts/chat.ts\n/**\n* Abstract class that serves as a base for creating message prompt\n* templates. It defines how to format messages for different roles in a\n* conversation.\n*/\nvar BaseMessagePromptTemplate = class extends Runnable {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"prompts\",\n\t\t\"chat\"\n\t];\n\tlc_serializable = true;\n\t/**\n\t* Calls the formatMessages method with the provided input and options.\n\t* @param input Input for the formatMessages method\n\t* @param options Optional BaseCallbackConfig\n\t* @returns Formatted output messages\n\t*/\n\tasync invoke(input, options) {\n\t\treturn this._callWithConfig((input$1) => this.formatMessages(input$1), input, {\n\t\t\t...options,\n\t\t\trunType: \"prompt\"\n\t\t});\n\t}\n};\n/**\n* Class that represents a placeholder for messages in a chat prompt. It\n* extends the BaseMessagePromptTemplate.\n*/\nvar MessagesPlaceholder = class extends BaseMessagePromptTemplate {\n\tstatic lc_name() {\n\t\treturn \"MessagesPlaceholder\";\n\t}\n\tvariableName;\n\toptional;\n\tconstructor(fields) {\n\t\tif (typeof fields === \"string\") fields = { variableName: fields };\n\t\tsuper(fields);\n\t\tthis.variableName = fields.variableName;\n\t\tthis.optional = fields.optional ?? false;\n\t}\n\tget inputVariables() {\n\t\treturn [this.variableName];\n\t}\n\tasync formatMessages(values) {\n\t\tconst input = values[this.variableName];\n\t\tif (this.optional && !input) return [];\n\t\telse if (!input) {\n\t\t\tconst error = /* @__PURE__ */ new Error(`Field \"${this.variableName}\" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);\n\t\t\terror.name = \"InputFormatError\";\n\t\t\tthrow error;\n\t\t}\n\t\tlet formattedMessages;\n\t\ttry {\n\t\t\tif (Array.isArray(input)) formattedMessages = input.map(coerceMessageLikeToMessage);\n\t\t\telse formattedMessages = [coerceMessageLikeToMessage(input)];\n\t\t} catch (e) {\n\t\t\tconst readableInput = typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n\t\t\tconst error = new Error([\n\t\t\t\t`Field \"${this.variableName}\" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,\n\t\t\t\t`Received value: ${readableInput}`,\n\t\t\t\t`Additional message: ${e.message}`\n\t\t\t].join(\"\\n\\n\"));\n\t\t\terror.name = \"InputFormatError\";\n\t\t\terror.lc_error_code = e.lc_error_code;\n\t\t\tthrow error;\n\t\t}\n\t\treturn formattedMessages;\n\t}\n};\n/**\n* Abstract class that serves as a base for creating message string prompt\n* templates. It extends the BaseMessagePromptTemplate.\n*/\nvar BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate {\n\tprompt;\n\tconstructor(fields) {\n\t\tif (!(\"prompt\" in fields)) fields = { prompt: fields };\n\t\tsuper(fields);\n\t\tthis.prompt = fields.prompt;\n\t}\n\tget inputVariables() {\n\t\treturn this.prompt.inputVariables;\n\t}\n\tasync formatMessages(values) {\n\t\treturn [await this.format(values)];\n\t}\n};\n/**\n* Abstract class that serves as a base for creating chat prompt\n* templates. It extends the BasePromptTemplate.\n*/\nvar BaseChatPromptTemplate = class extends BasePromptTemplate {\n\tconstructor(input) {\n\t\tsuper(input);\n\t}\n\tasync format(values) {\n\t\treturn (await this.formatPromptValue(values)).toString();\n\t}\n\tasync formatPromptValue(values) {\n\t\tconst resultMessages = await this.formatMessages(values);\n\t\treturn new ChatPromptValue(resultMessages);\n\t}\n};\n/**\n* Class that represents a chat message prompt template. It extends the\n* BaseMessageStringPromptTemplate.\n*/\nvar ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate {\n\tstatic lc_name() {\n\t\treturn \"ChatMessagePromptTemplate\";\n\t}\n\trole;\n\tconstructor(fields, role) {\n\t\tif (!(\"prompt\" in fields)) fields = {\n\t\t\tprompt: fields,\n\t\t\trole\n\t\t};\n\t\tsuper(fields);\n\t\tthis.role = fields.role;\n\t}\n\tasync format(values) {\n\t\treturn new ChatMessage(await this.prompt.format(values), this.role);\n\t}\n\tstatic fromTemplate(template, role, options) {\n\t\treturn new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role);\n\t}\n};\nfunction isTextTemplateParam(param) {\n\tif (param === null || typeof param !== \"object\" || Array.isArray(param)) return false;\n\treturn Object.keys(param).length === 1 && \"text\" in param && typeof param.text === \"string\";\n}\nfunction isImageTemplateParam(param) {\n\tif (param === null || typeof param !== \"object\" || Array.isArray(param)) return false;\n\treturn \"image_url\" in param && (typeof param.image_url === \"string\" || typeof param.image_url === \"object\" && param.image_url !== null && \"url\" in param.image_url && typeof param.image_url.url === \"string\");\n}\nvar _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"prompts\",\n\t\t\"chat\"\n\t];\n\tlc_serializable = true;\n\tinputVariables = [];\n\tadditionalOptions = {};\n\tprompt;\n\tmessageClass;\n\tstatic _messageClass() {\n\t\tthrow new Error(\"Can not invoke _messageClass from inside _StringImageMessagePromptTemplate\");\n\t}\n\tchatMessageClass;\n\tconstructor(fields, additionalOptions) {\n\t\tif (!(\"prompt\" in fields)) fields = { prompt: fields };\n\t\tsuper(fields);\n\t\tthis.prompt = fields.prompt;\n\t\tif (Array.isArray(this.prompt)) {\n\t\t\tlet inputVariables = [];\n\t\t\tthis.prompt.forEach((prompt) => {\n\t\t\t\tif (\"inputVariables\" in prompt) inputVariables = inputVariables.concat(prompt.inputVariables);\n\t\t\t});\n\t\t\tthis.inputVariables = inputVariables;\n\t\t} else this.inputVariables = this.prompt.inputVariables;\n\t\tthis.additionalOptions = additionalOptions ?? this.additionalOptions;\n\t}\n\tcreateMessage(content) {\n\t\tconst constructor = this.constructor;\n\t\tif (constructor._messageClass()) {\n\t\t\tconst MsgClass = constructor._messageClass();\n\t\t\treturn new MsgClass({ content });\n\t\t} else if (constructor.chatMessageClass) {\n\t\t\tconst MsgClass = constructor.chatMessageClass();\n\t\t\treturn new MsgClass({\n\t\t\t\tcontent,\n\t\t\t\trole: this.getRoleFromMessageClass(MsgClass.lc_name())\n\t\t\t});\n\t\t} else throw new Error(\"No message class defined\");\n\t}\n\tgetRoleFromMessageClass(name) {\n\t\tswitch (name) {\n\t\t\tcase \"HumanMessage\": return \"human\";\n\t\t\tcase \"AIMessage\": return \"ai\";\n\t\t\tcase \"SystemMessage\": return \"system\";\n\t\t\tcase \"ChatMessage\": return \"chat\";\n\t\t\tdefault: throw new Error(\"Invalid message class name\");\n\t\t}\n\t}\n\tstatic fromTemplate(template, additionalOptions) {\n\t\tif (typeof template === \"string\") return new this(PromptTemplate.fromTemplate(template, additionalOptions));\n\t\tconst prompt = [];\n\t\tfor (const item of template) if (typeof item === \"string\") prompt.push(PromptTemplate.fromTemplate(item, additionalOptions));\n\t\telse if (item === null) {} else if (isTextTemplateParam(item)) {\n\t\t\tlet text = \"\";\n\t\t\tif (typeof item.text === \"string\") text = item.text ?? \"\";\n\t\t\tconst options = {\n\t\t\t\t...additionalOptions,\n\t\t\t\tadditionalContentFields: item\n\t\t\t};\n\t\t\tprompt.push(PromptTemplate.fromTemplate(text, options));\n\t\t} else if (isImageTemplateParam(item)) {\n\t\t\tlet imgTemplate = item.image_url ?? \"\";\n\t\t\tlet imgTemplateObject;\n\t\t\tlet inputVariables = [];\n\t\t\tif (typeof imgTemplate === \"string\") {\n\t\t\t\tlet parsedTemplate;\n\t\t\t\tif (additionalOptions?.templateFormat === \"mustache\") parsedTemplate = parseMustache(imgTemplate);\n\t\t\t\telse parsedTemplate = parseFString(imgTemplate);\n\t\t\t\tconst variables = parsedTemplate.flatMap((item$1) => item$1.type === \"variable\" ? [item$1.name] : []);\n\t\t\t\tif ((variables?.length ?? 0) > 0) {\n\t\t\t\t\tif (variables.length > 1) throw new Error(`Only one format variable allowed per image template.\\nGot: ${variables}\\nFrom: ${imgTemplate}`);\n\t\t\t\t\tinputVariables = [variables[0]];\n\t\t\t\t} else inputVariables = [];\n\t\t\t\timgTemplate = { url: imgTemplate };\n\t\t\t\timgTemplateObject = new ImagePromptTemplate({\n\t\t\t\t\ttemplate: imgTemplate,\n\t\t\t\t\tinputVariables,\n\t\t\t\t\ttemplateFormat: additionalOptions?.templateFormat,\n\t\t\t\t\tadditionalContentFields: item\n\t\t\t\t});\n\t\t\t} else if (typeof imgTemplate === \"object\") {\n\t\t\t\tif (\"url\" in imgTemplate) {\n\t\t\t\t\tlet parsedTemplate;\n\t\t\t\t\tif (additionalOptions?.templateFormat === \"mustache\") parsedTemplate = parseMustache(imgTemplate.url);\n\t\t\t\t\telse parsedTemplate = parseFString(imgTemplate.url);\n\t\t\t\t\tinputVariables = parsedTemplate.flatMap((item$1) => item$1.type === \"variable\" ? [item$1.name] : []);\n\t\t\t\t} else inputVariables = [];\n\t\t\t\timgTemplateObject = new ImagePromptTemplate({\n\t\t\t\t\ttemplate: imgTemplate,\n\t\t\t\t\tinputVariables,\n\t\t\t\t\ttemplateFormat: additionalOptions?.templateFormat,\n\t\t\t\t\tadditionalContentFields: item\n\t\t\t\t});\n\t\t\t} else throw new Error(\"Invalid image template\");\n\t\t\tprompt.push(imgTemplateObject);\n\t\t} else if (typeof item === \"object\") prompt.push(new DictPromptTemplate({\n\t\t\ttemplate: item,\n\t\t\ttemplateFormat: additionalOptions?.templateFormat\n\t\t}));\n\t\treturn new this({\n\t\t\tprompt,\n\t\t\tadditionalOptions\n\t\t});\n\t}\n\tasync format(input) {\n\t\tif (this.prompt instanceof BaseStringPromptTemplate) {\n\t\t\tconst text = await this.prompt.format(input);\n\t\t\treturn this.createMessage(text);\n\t\t} else {\n\t\t\tconst content = [];\n\t\t\tfor (const prompt of this.prompt) {\n\t\t\t\tlet inputs = {};\n\t\t\t\tif (!(\"inputVariables\" in prompt)) throw new Error(`Prompt ${prompt} does not have inputVariables defined.`);\n\t\t\t\tfor (const item of prompt.inputVariables) {\n\t\t\t\t\tif (!inputs) inputs = { [item]: input[item] };\n\t\t\t\t\tinputs = {\n\t\t\t\t\t\t...inputs,\n\t\t\t\t\t\t[item]: input[item]\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (prompt instanceof BaseStringPromptTemplate) {\n\t\t\t\t\tconst formatted = await prompt.format(inputs);\n\t\t\t\t\tlet additionalContentFields;\n\t\t\t\t\tif (\"additionalContentFields\" in prompt) additionalContentFields = prompt.additionalContentFields;\n\t\t\t\t\tif (formatted !== \"\") content.push({\n\t\t\t\t\t\t...additionalContentFields,\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: formatted\n\t\t\t\t\t});\n\t\t\t\t} else if (prompt instanceof ImagePromptTemplate) {\n\t\t\t\t\tconst formatted = await prompt.format(inputs);\n\t\t\t\t\tlet additionalContentFields;\n\t\t\t\t\tif (\"additionalContentFields\" in prompt) additionalContentFields = prompt.additionalContentFields;\n\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t...additionalContentFields,\n\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\timage_url: formatted\n\t\t\t\t\t});\n\t\t\t\t} else if (prompt instanceof DictPromptTemplate) {\n\t\t\t\t\tconst formatted = await prompt.format(inputs);\n\t\t\t\t\tlet additionalContentFields;\n\t\t\t\t\tif (\"additionalContentFields\" in prompt) additionalContentFields = prompt.additionalContentFields;\n\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t...additionalContentFields,\n\t\t\t\t\t\t...formatted\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this.createMessage(content);\n\t\t}\n\t}\n\tasync formatMessages(values) {\n\t\treturn [await this.format(values)];\n\t}\n};\n/**\n* Class that represents a human message prompt template. It extends the\n* BaseMessageStringPromptTemplate.\n* @example\n* ```typescript\n* const message = HumanMessagePromptTemplate.fromTemplate(\"{text}\");\n* const formatted = await message.format({ text: \"Hello world!\" });\n*\n* const chatPrompt = ChatPromptTemplate.fromMessages([message]);\n* const formattedChatPrompt = await chatPrompt.invoke({\n* text: \"Hello world!\",\n* });\n* ```\n*/\nvar HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate {\n\tstatic _messageClass() {\n\t\treturn HumanMessage;\n\t}\n\tstatic lc_name() {\n\t\treturn \"HumanMessagePromptTemplate\";\n\t}\n};\n/**\n* Class that represents an AI message prompt template. It extends the\n* BaseMessageStringPromptTemplate.\n*/\nvar AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate {\n\tstatic _messageClass() {\n\t\treturn AIMessage;\n\t}\n\tstatic lc_name() {\n\t\treturn \"AIMessagePromptTemplate\";\n\t}\n};\n/**\n* Class that represents a system message prompt template. It extends the\n* BaseMessageStringPromptTemplate.\n* @example\n* ```typescript\n* const message = SystemMessagePromptTemplate.fromTemplate(\"{text}\");\n* const formatted = await message.format({ text: \"Hello world!\" });\n*\n* const chatPrompt = ChatPromptTemplate.fromMessages([message]);\n* const formattedChatPrompt = await chatPrompt.invoke({\n* text: \"Hello world!\",\n* });\n* ```\n*/\nvar SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate {\n\tstatic _messageClass() {\n\t\treturn SystemMessage;\n\t}\n\tstatic lc_name() {\n\t\treturn \"SystemMessagePromptTemplate\";\n\t}\n};\nfunction _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) {\n\treturn typeof baseMessagePromptTemplateLike.formatMessages === \"function\";\n}\nfunction _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) {\n\tif (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) return messagePromptTemplateLike;\n\tif (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === \"placeholder\") {\n\t\tconst messageContent = messagePromptTemplateLike[1];\n\t\tif (extra?.templateFormat === \"mustache\" && typeof messageContent === \"string\" && messageContent.slice(0, 2) === \"{{\" && messageContent.slice(-2) === \"}}\") {\n\t\t\tconst variableName = messageContent.slice(2, -2);\n\t\t\treturn new MessagesPlaceholder({\n\t\t\t\tvariableName,\n\t\t\t\toptional: true\n\t\t\t});\n\t\t} else if (typeof messageContent === \"string\" && messageContent[0] === \"{\" && messageContent[messageContent.length - 1] === \"}\") {\n\t\t\tconst variableName = messageContent.slice(1, -1);\n\t\t\treturn new MessagesPlaceholder({\n\t\t\t\tvariableName,\n\t\t\t\toptional: true\n\t\t\t});\n\t\t}\n\t\tthrow new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `\"f-string\"`}: \"${messagePromptTemplateLike[1]}\". Expected a variable name surrounded by ${extra?.templateFormat === \"mustache\" ? \"double\" : \"single\"} curly braces.`);\n\t}\n\tconst message = coerceMessageLikeToMessage(messagePromptTemplateLike);\n\tlet templateData;\n\tif (typeof message.content === \"string\") templateData = message.content;\n\telse templateData = message.content.map((item) => {\n\t\tif (\"text\" in item) return {\n\t\t\t...item,\n\t\t\ttext: item.text\n\t\t};\n\t\telse if (\"image_url\" in item) return {\n\t\t\t...item,\n\t\t\timage_url: item.image_url\n\t\t};\n\t\telse return item;\n\t});\n\tif (message._getType() === \"human\") return HumanMessagePromptTemplate.fromTemplate(templateData, extra);\n\telse if (message._getType() === \"ai\") return AIMessagePromptTemplate.fromTemplate(templateData, extra);\n\telse if (message._getType() === \"system\") return SystemMessagePromptTemplate.fromTemplate(templateData, extra);\n\telse if (ChatMessage.isInstance(message)) return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra);\n\telse throw new Error(`Could not coerce message prompt template from input. Received message type: \"${message._getType()}\".`);\n}\nfunction isMessagesPlaceholder(x) {\n\treturn x.constructor.lc_name() === \"MessagesPlaceholder\";\n}\n/**\n* Class that represents a chat prompt. It extends the\n* BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate\n* instances to format a series of messages for a conversation.\n* @example\n* ```typescript\n* const message = SystemMessagePromptTemplate.fromTemplate(\"{text}\");\n* const chatPrompt = ChatPromptTemplate.fromMessages([\n* [\"ai\", \"You are a helpful assistant.\"],\n* message,\n* ]);\n* const formattedChatPrompt = await chatPrompt.invoke({\n* text: \"Hello world!\",\n* });\n* ```\n*/\nvar ChatPromptTemplate = class ChatPromptTemplate extends BaseChatPromptTemplate {\n\tstatic lc_name() {\n\t\treturn \"ChatPromptTemplate\";\n\t}\n\tget lc_aliases() {\n\t\treturn { promptMessages: \"messages\" };\n\t}\n\tpromptMessages;\n\tvalidateTemplate = true;\n\ttemplateFormat = \"f-string\";\n\tconstructor(input) {\n\t\tsuper(input);\n\t\tif (input.templateFormat === \"mustache\" && input.validateTemplate === void 0) this.validateTemplate = false;\n\t\tObject.assign(this, input);\n\t\tif (this.validateTemplate) {\n\t\t\tconst inputVariablesMessages = /* @__PURE__ */ new Set();\n\t\t\tfor (const promptMessage of this.promptMessages) {\n\t\t\t\tif (promptMessage instanceof BaseMessage) continue;\n\t\t\t\tfor (const inputVariable of promptMessage.inputVariables) inputVariablesMessages.add(inputVariable);\n\t\t\t}\n\t\t\tconst totalInputVariables = this.inputVariables;\n\t\t\tconst inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables);\n\t\t\tconst difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x)));\n\t\t\tif (difference.size > 0) throw new Error(`Input variables \\`${[...difference]}\\` are not used in any of the prompt messages.`);\n\t\t\tconst otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x)));\n\t\t\tif (otherDifference.size > 0) throw new Error(`Input variables \\`${[...otherDifference]}\\` are used in prompt messages but not in the prompt template.`);\n\t\t}\n\t}\n\t_getPromptType() {\n\t\treturn \"chat\";\n\t}\n\tasync _parseImagePrompts(message, inputValues) {\n\t\tif (typeof message.content === \"string\") return message;\n\t\tconst formattedMessageContent = await Promise.all(message.content.map(async (item) => {\n\t\t\tif (item.type !== \"image_url\") return item;\n\t\t\tlet imageUrl = \"\";\n\t\t\tif (typeof item.image_url === \"string\") imageUrl = item.image_url;\n\t\t\telse if (typeof item.image_url === \"object\" && item.image_url !== null && \"url\" in item.image_url && typeof item.image_url.url === \"string\") imageUrl = item.image_url.url;\n\t\t\tconst promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat });\n\t\t\tconst formattedUrl = await promptTemplatePlaceholder.format(inputValues);\n\t\t\tif (typeof item.image_url === \"object\" && item.image_url !== null && \"url\" in item.image_url) item.image_url.url = formattedUrl;\n\t\t\telse item.image_url = formattedUrl;\n\t\t\treturn item;\n\t\t}));\n\t\tmessage.content = formattedMessageContent;\n\t\treturn message;\n\t}\n\tasync formatMessages(values) {\n\t\tconst allValues = await this.mergePartialAndUserVariables(values);\n\t\tlet resultMessages = [];\n\t\tfor (const promptMessage of this.promptMessages) if (promptMessage instanceof BaseMessage) resultMessages.push(await this._parseImagePrompts(promptMessage, allValues));\n\t\telse {\n\t\t\tlet inputValues;\n\t\t\tif (this.templateFormat === \"mustache\") inputValues = { ...allValues };\n\t\t\telse inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => {\n\t\t\t\tif (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) {\n\t\t\t\t\tconst error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \\`${inputVariable.toString()}\\``), \"INVALID_PROMPT_INPUT\");\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tacc[inputVariable] = allValues[inputVariable];\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t\t\tconst message = await promptMessage.formatMessages(inputValues);\n\t\t\tresultMessages = resultMessages.concat(message);\n\t\t}\n\t\treturn resultMessages;\n\t}\n\tasync partial(values) {\n\t\tconst newInputVariables = this.inputVariables.filter((iv) => !(iv in values));\n\t\tconst newPartialVariables = {\n\t\t\t...this.partialVariables ?? {},\n\t\t\t...values\n\t\t};\n\t\tconst promptDict = {\n\t\t\t...this,\n\t\t\tinputVariables: newInputVariables,\n\t\t\tpartialVariables: newPartialVariables\n\t\t};\n\t\treturn new ChatPromptTemplate(promptDict);\n\t}\n\tstatic fromTemplate(template, options) {\n\t\tconst prompt = PromptTemplate.fromTemplate(template, options);\n\t\tconst humanTemplate = new HumanMessagePromptTemplate({ prompt });\n\t\treturn this.fromMessages([humanTemplate]);\n\t}\n\t/**\n\t* Create a chat model-specific prompt from individual chat messages\n\t* or message-like tuples.\n\t* @param promptMessages Messages to be passed to the chat model\n\t* @returns A new ChatPromptTemplate\n\t*/\n\tstatic fromMessages(promptMessages, extra) {\n\t\tconst flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []);\n\t\tconst flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null));\n\t\tconst inputVariables = /* @__PURE__ */ new Set();\n\t\tfor (const promptMessage of flattenedMessages) {\n\t\t\tif (promptMessage instanceof BaseMessage) continue;\n\t\t\tfor (const inputVariable of promptMessage.inputVariables) {\n\t\t\t\tif (inputVariable in flattenedPartialVariables) continue;\n\t\t\t\tinputVariables.add(inputVariable);\n\t\t\t}\n\t\t}\n\t\treturn new this({\n\t\t\t...extra,\n\t\t\tinputVariables: [...inputVariables],\n\t\t\tpromptMessages: flattenedMessages,\n\t\t\tpartialVariables: flattenedPartialVariables,\n\t\t\ttemplateFormat: extra?.templateFormat\n\t\t});\n\t}\n};\n\n//#endregion\nexport { AIMessagePromptTemplate, BaseChatPromptTemplate, BaseMessagePromptTemplate, BaseMessageStringPromptTemplate, ChatMessagePromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate };\n//# sourceMappingURL=chat.js.map","import { BaseStringPromptTemplate } from \"./string.js\";\nimport { checkValidTemplate, renderTemplate } from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport { BaseChatPromptTemplate } from \"./chat.js\";\n\n//#region src/prompts/few_shot.ts\n/**\n* Prompt template that contains few-shot examples.\n* @augments BasePromptTemplate\n* @augments FewShotPromptTemplateInput\n* @example\n* ```typescript\n* const examplePrompt = PromptTemplate.fromTemplate(\n* \"Input: {input}\\nOutput: {output}\",\n* );\n*\n* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n* [\n* { input: \"happy\", output: \"sad\" },\n* { input: \"tall\", output: \"short\" },\n* { input: \"energetic\", output: \"lethargic\" },\n* { input: \"sunny\", output: \"gloomy\" },\n* { input: \"windy\", output: \"calm\" },\n* ],\n* new OpenAIEmbeddings(),\n* HNSWLib,\n* { k: 1 },\n* );\n*\n* const dynamicPrompt = new FewShotPromptTemplate({\n* exampleSelector,\n* examplePrompt,\n* prefix: \"Give the antonym of every input\",\n* suffix: \"Input: {adjective}\\nOutput:\",\n* inputVariables: [\"adjective\"],\n* });\n*\n* // Format the dynamic prompt with the input 'rainy'\n* console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n*\n* ```\n*/\nvar FewShotPromptTemplate = class FewShotPromptTemplate extends BaseStringPromptTemplate {\n\tlc_serializable = false;\n\texamples;\n\texampleSelector;\n\texamplePrompt;\n\tsuffix = \"\";\n\texampleSeparator = \"\\n\\n\";\n\tprefix = \"\";\n\ttemplateFormat = \"f-string\";\n\tvalidateTemplate = true;\n\tconstructor(input) {\n\t\tsuper(input);\n\t\tObject.assign(this, input);\n\t\tif (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error(\"Only one of 'examples' and 'example_selector' should be provided\");\n\t\tif (this.examples === void 0 && this.exampleSelector === void 0) throw new Error(\"One of 'examples' and 'example_selector' should be provided\");\n\t\tif (this.validateTemplate) {\n\t\t\tlet totalInputVariables = this.inputVariables;\n\t\t\tif (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));\n\t\t\tcheckValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables);\n\t\t}\n\t}\n\t_getPromptType() {\n\t\treturn \"few_shot\";\n\t}\n\tstatic lc_name() {\n\t\treturn \"FewShotPromptTemplate\";\n\t}\n\tasync getExamples(inputVariables) {\n\t\tif (this.examples !== void 0) return this.examples;\n\t\tif (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables);\n\t\tthrow new Error(\"One of 'examples' and 'example_selector' should be provided\");\n\t}\n\tasync partial(values) {\n\t\tconst newInputVariables = this.inputVariables.filter((iv) => !(iv in values));\n\t\tconst newPartialVariables = {\n\t\t\t...this.partialVariables ?? {},\n\t\t\t...values\n\t\t};\n\t\tconst promptDict = {\n\t\t\t...this,\n\t\t\tinputVariables: newInputVariables,\n\t\t\tpartialVariables: newPartialVariables\n\t\t};\n\t\treturn new FewShotPromptTemplate(promptDict);\n\t}\n\t/**\n\t* Formats the prompt with the given values.\n\t* @param values The values to format the prompt with.\n\t* @returns A promise that resolves to a string representing the formatted prompt.\n\t*/\n\tasync format(values) {\n\t\tconst allValues = await this.mergePartialAndUserVariables(values);\n\t\tconst examples = await this.getExamples(allValues);\n\t\tconst exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example)));\n\t\tconst template = [\n\t\t\tthis.prefix,\n\t\t\t...exampleStrings,\n\t\t\tthis.suffix\n\t\t].join(this.exampleSeparator);\n\t\treturn renderTemplate(template, this.templateFormat, allValues);\n\t}\n\tserialize() {\n\t\tif (this.exampleSelector || !this.examples) throw new Error(\"Serializing an example selector is not currently supported\");\n\t\tif (this.outputParser !== void 0) throw new Error(\"Serializing an output parser is not currently supported\");\n\t\treturn {\n\t\t\t_type: this._getPromptType(),\n\t\t\tinput_variables: this.inputVariables,\n\t\t\texample_prompt: this.examplePrompt.serialize(),\n\t\t\texample_separator: this.exampleSeparator,\n\t\t\tsuffix: this.suffix,\n\t\t\tprefix: this.prefix,\n\t\t\ttemplate_format: this.templateFormat,\n\t\t\texamples: this.examples\n\t\t};\n\t}\n\tstatic async deserialize(data) {\n\t\tconst { example_prompt } = data;\n\t\tif (!example_prompt) throw new Error(\"Missing example prompt\");\n\t\tconst examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\t\tlet examples;\n\t\tif (Array.isArray(data.examples)) examples = data.examples;\n\t\telse throw new Error(\"Invalid examples format. Only list or string are supported.\");\n\t\treturn new FewShotPromptTemplate({\n\t\t\tinputVariables: data.input_variables,\n\t\t\texamplePrompt,\n\t\t\texamples,\n\t\t\texampleSeparator: data.example_separator,\n\t\t\tprefix: data.prefix,\n\t\t\tsuffix: data.suffix,\n\t\t\ttemplateFormat: data.template_format\n\t\t});\n\t}\n};\n/**\n* Chat prompt template that contains few-shot examples.\n* @augments BasePromptTemplateInput\n* @augments FewShotChatMessagePromptTemplateInput\n*/\nvar FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate extends BaseChatPromptTemplate {\n\tlc_serializable = true;\n\texamples;\n\texampleSelector;\n\texamplePrompt;\n\tsuffix = \"\";\n\texampleSeparator = \"\\n\\n\";\n\tprefix = \"\";\n\ttemplateFormat = \"f-string\";\n\tvalidateTemplate = true;\n\t_getPromptType() {\n\t\treturn \"few_shot_chat\";\n\t}\n\tstatic lc_name() {\n\t\treturn \"FewShotChatMessagePromptTemplate\";\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.examples = fields.examples;\n\t\tthis.examplePrompt = fields.examplePrompt;\n\t\tthis.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n\t\tthis.exampleSelector = fields.exampleSelector;\n\t\tthis.prefix = fields.prefix ?? \"\";\n\t\tthis.suffix = fields.suffix ?? \"\";\n\t\tthis.templateFormat = fields.templateFormat ?? \"f-string\";\n\t\tthis.validateTemplate = fields.validateTemplate ?? true;\n\t\tif (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error(\"Only one of 'examples' and 'example_selector' should be provided\");\n\t\tif (this.examples === void 0 && this.exampleSelector === void 0) throw new Error(\"One of 'examples' and 'example_selector' should be provided\");\n\t\tif (this.validateTemplate) {\n\t\t\tlet totalInputVariables = this.inputVariables;\n\t\t\tif (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));\n\t\t\tcheckValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables);\n\t\t}\n\t}\n\tasync getExamples(inputVariables) {\n\t\tif (this.examples !== void 0) return this.examples;\n\t\tif (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables);\n\t\tthrow new Error(\"One of 'examples' and 'example_selector' should be provided\");\n\t}\n\t/**\n\t* Formats the list of values and returns a list of formatted messages.\n\t* @param values The values to format the prompt with.\n\t* @returns A promise that resolves to a string representing the formatted prompt.\n\t*/\n\tasync formatMessages(values) {\n\t\tconst allValues = await this.mergePartialAndUserVariables(values);\n\t\tlet examples = await this.getExamples(allValues);\n\t\texamples = examples.map((example) => {\n\t\t\tconst result = {};\n\t\t\tthis.examplePrompt.inputVariables.forEach((inputVariable) => {\n\t\t\t\tresult[inputVariable] = example[inputVariable];\n\t\t\t});\n\t\t\treturn result;\n\t\t});\n\t\tconst messages = [];\n\t\tfor (const example of examples) {\n\t\t\tconst exampleMessages = await this.examplePrompt.formatMessages(example);\n\t\t\tmessages.push(...exampleMessages);\n\t\t}\n\t\treturn messages;\n\t}\n\t/**\n\t* Formats the prompt with the given values.\n\t* @param values The values to format the prompt with.\n\t* @returns A promise that resolves to a string representing the formatted prompt.\n\t*/\n\tasync format(values) {\n\t\tconst allValues = await this.mergePartialAndUserVariables(values);\n\t\tconst examples = await this.getExamples(allValues);\n\t\tconst exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example)));\n\t\tconst exampleStrings = exampleMessages.flat().map((message) => message.content);\n\t\tconst template = [\n\t\t\tthis.prefix,\n\t\t\t...exampleStrings,\n\t\t\tthis.suffix\n\t\t].join(this.exampleSeparator);\n\t\treturn renderTemplate(template, this.templateFormat, allValues);\n\t}\n\t/**\n\t* Partially formats the prompt with the given values.\n\t* @param values The values to partially format the prompt with.\n\t* @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n\t*/\n\tasync partial(values) {\n\t\tconst newInputVariables = this.inputVariables.filter((variable) => !(variable in values));\n\t\tconst newPartialVariables = {\n\t\t\t...this.partialVariables ?? {},\n\t\t\t...values\n\t\t};\n\t\tconst promptDict = {\n\t\t\t...this,\n\t\t\tinputVariables: newInputVariables,\n\t\t\tpartialVariables: newPartialVariables\n\t\t};\n\t\treturn new FewShotChatMessagePromptTemplate(promptDict);\n\t}\n};\n\n//#endregion\nexport { FewShotChatMessagePromptTemplate, FewShotPromptTemplate };\n//# sourceMappingURL=few_shot.js.map","import { BasePromptTemplate } from \"./base.js\";\nimport { ChatPromptTemplate } from \"./chat.js\";\n\n//#region src/prompts/pipeline.ts\n/**\n* Class that handles a sequence of prompts, each of which may require\n* different input variables. Includes methods for formatting these\n* prompts, extracting required input values, and handling partial\n* prompts.\n* @example\n* ```typescript\n* const composedPrompt = new PipelinePromptTemplate({\n* pipelinePrompts: [\n* {\n* name: \"introduction\",\n* prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`),\n* },\n* {\n* name: \"example\",\n* prompt: PromptTemplate.fromTemplate(\n* `Here's an example of an interaction:\n* Q: {example_q}\n* A: {example_a}`,\n* ),\n* },\n* {\n* name: \"start\",\n* prompt: PromptTemplate.fromTemplate(\n* `Now, do this for real!\n* Q: {input}\n* A:`,\n* ),\n* },\n* ],\n* finalPrompt: PromptTemplate.fromTemplate(\n* `{introduction}\n* {example}\n* {start}`,\n* ),\n* });\n*\n* const formattedPrompt = await composedPrompt.format({\n* person: \"Elon Musk\",\n* example_q: `What's your favorite car?`,\n* example_a: \"Tesla\",\n* input: `What's your favorite social media site?`,\n* });\n* ```\n*/\nvar PipelinePromptTemplate = class PipelinePromptTemplate extends BasePromptTemplate {\n\tstatic lc_name() {\n\t\treturn \"PipelinePromptTemplate\";\n\t}\n\tpipelinePrompts;\n\tfinalPrompt;\n\tconstructor(input) {\n\t\tsuper({\n\t\t\t...input,\n\t\t\tinputVariables: []\n\t\t});\n\t\tthis.pipelinePrompts = input.pipelinePrompts;\n\t\tthis.finalPrompt = input.finalPrompt;\n\t\tthis.inputVariables = this.computeInputValues();\n\t}\n\t/**\n\t* Computes the input values required by the pipeline prompts.\n\t* @returns Array of input values required by the pipeline prompts.\n\t*/\n\tcomputeInputValues() {\n\t\tconst intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name);\n\t\tconst inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat();\n\t\treturn [...new Set(inputValues)];\n\t}\n\tstatic extractRequiredInputValues(allValues, requiredValueNames) {\n\t\treturn requiredValueNames.reduce((requiredValues, valueName) => {\n\t\t\trequiredValues[valueName] = allValues[valueName];\n\t\t\treturn requiredValues;\n\t\t}, {});\n\t}\n\t/**\n\t* Formats the pipeline prompts based on the provided input values.\n\t* @param values Input values to format the pipeline prompts.\n\t* @returns Promise that resolves with the formatted input values.\n\t*/\n\tasync formatPipelinePrompts(values) {\n\t\tconst allValues = await this.mergePartialAndUserVariables(values);\n\t\tfor (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) {\n\t\t\tconst pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables);\n\t\t\tif (pipelinePrompt instanceof ChatPromptTemplate) allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues);\n\t\t\telse allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues);\n\t\t}\n\t\treturn PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables);\n\t}\n\t/**\n\t* Formats the final prompt value based on the provided input values.\n\t* @param values Input values to format the final prompt value.\n\t* @returns Promise that resolves with the formatted final prompt value.\n\t*/\n\tasync formatPromptValue(values) {\n\t\treturn this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values));\n\t}\n\tasync format(values) {\n\t\treturn this.finalPrompt.format(await this.formatPipelinePrompts(values));\n\t}\n\t/**\n\t* Handles partial prompts, which are prompts that have been partially\n\t* filled with input values.\n\t* @param values Partial input values.\n\t* @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables.\n\t*/\n\tasync partial(values) {\n\t\tconst promptDict = { ...this };\n\t\tpromptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values));\n\t\tpromptDict.partialVariables = {\n\t\t\t...this.partialVariables ?? {},\n\t\t\t...values\n\t\t};\n\t\treturn new PipelinePromptTemplate(promptDict);\n\t}\n\tserialize() {\n\t\tthrow new Error(\"Not implemented.\");\n\t}\n\t_getPromptType() {\n\t\treturn \"pipeline\";\n\t}\n};\n\n//#endregion\nexport { PipelinePromptTemplate };\n//# sourceMappingURL=pipeline.js.map","import { RunnableBinding } from \"../runnables/base.js\";\nimport { ChatPromptTemplate } from \"./chat.js\";\n\n//#region src/prompts/structured.ts\nfunction isWithStructuredOutput(x) {\n\treturn typeof x === \"object\" && x != null && \"withStructuredOutput\" in x && typeof x.withStructuredOutput === \"function\";\n}\nfunction isRunnableBinding(x) {\n\treturn typeof x === \"object\" && x != null && \"lc_id\" in x && Array.isArray(x.lc_id) && x.lc_id.join(\"/\") === \"langchain_core/runnables/RunnableBinding\";\n}\nvar StructuredPrompt = class StructuredPrompt extends ChatPromptTemplate {\n\tschema;\n\tmethod;\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"prompts\",\n\t\t\"structured\"\n\t];\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\tschema: \"schema_\"\n\t\t};\n\t}\n\tconstructor(input) {\n\t\tsuper(input);\n\t\tthis.schema = input.schema;\n\t\tthis.method = input.method;\n\t}\n\tpipe(coerceable) {\n\t\tif (isWithStructuredOutput(coerceable)) return super.pipe(coerceable.withStructuredOutput(this.schema));\n\t\tif (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) return super.pipe(new RunnableBinding({\n\t\t\tbound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []),\n\t\t\tkwargs: coerceable.kwargs ?? {},\n\t\t\tconfig: coerceable.config,\n\t\t\tconfigFactories: coerceable.configFactories\n\t\t}));\n\t\tthrow new Error(`Structured prompts need to be piped to a language model that supports the \"withStructuredOutput()\" method.`);\n\t}\n\tstatic fromMessagesAndSchema(promptMessages, schema, method) {\n\t\treturn StructuredPrompt.fromMessages(promptMessages, {\n\t\t\tschema,\n\t\t\tmethod\n\t\t});\n\t}\n};\n\n//#endregion\nexport { StructuredPrompt };\n//# sourceMappingURL=structured.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BasePromptTemplate } from \"./base.js\";\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport { DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, checkValidTemplate, interpolateFString, interpolateMustache, parseFString, parseMustache, parseTemplate, renderTemplate } from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport { ImagePromptTemplate } from \"./image.js\";\nimport { DictPromptTemplate } from \"./dict.js\";\nimport { AIMessagePromptTemplate, BaseChatPromptTemplate, BaseMessagePromptTemplate, BaseMessageStringPromptTemplate, ChatMessagePromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate } from \"./chat.js\";\nimport { FewShotChatMessagePromptTemplate, FewShotPromptTemplate } from \"./few_shot.js\";\nimport { PipelinePromptTemplate } from \"./pipeline.js\";\nimport { StructuredPrompt } from \"./structured.js\";\n\n//#region src/prompts/index.ts\nvar prompts_exports = {};\n__export(prompts_exports, {\n\tAIMessagePromptTemplate: () => AIMessagePromptTemplate,\n\tBaseChatPromptTemplate: () => BaseChatPromptTemplate,\n\tBaseMessagePromptTemplate: () => BaseMessagePromptTemplate,\n\tBaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate,\n\tBasePromptTemplate: () => BasePromptTemplate,\n\tBaseStringPromptTemplate: () => BaseStringPromptTemplate,\n\tChatMessagePromptTemplate: () => ChatMessagePromptTemplate,\n\tChatPromptTemplate: () => ChatPromptTemplate,\n\tDEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING,\n\tDEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING,\n\tDictPromptTemplate: () => DictPromptTemplate,\n\tFewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate,\n\tFewShotPromptTemplate: () => FewShotPromptTemplate,\n\tHumanMessagePromptTemplate: () => HumanMessagePromptTemplate,\n\tImagePromptTemplate: () => ImagePromptTemplate,\n\tMessagesPlaceholder: () => MessagesPlaceholder,\n\tPipelinePromptTemplate: () => PipelinePromptTemplate,\n\tPromptTemplate: () => PromptTemplate,\n\tStructuredPrompt: () => StructuredPrompt,\n\tSystemMessagePromptTemplate: () => SystemMessagePromptTemplate,\n\tcheckValidTemplate: () => checkValidTemplate,\n\tinterpolateFString: () => interpolateFString,\n\tinterpolateMustache: () => interpolateMustache,\n\tparseFString: () => parseFString,\n\tparseMustache: () => parseMustache,\n\tparseTemplate: () => parseTemplate,\n\trenderTemplate: () => renderTemplate\n});\n\n//#endregion\nexport { AIMessagePromptTemplate, BaseChatPromptTemplate, BaseMessagePromptTemplate, BaseMessageStringPromptTemplate, BasePromptTemplate, BaseStringPromptTemplate, ChatMessagePromptTemplate, ChatPromptTemplate, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, DictPromptTemplate, FewShotChatMessagePromptTemplate, FewShotPromptTemplate, HumanMessagePromptTemplate, ImagePromptTemplate, MessagesPlaceholder, PipelinePromptTemplate, PromptTemplate, StructuredPrompt, SystemMessagePromptTemplate, checkValidTemplate, interpolateFString, interpolateMustache, parseFString, parseMustache, parseTemplate, prompts_exports, renderTemplate };\n//# sourceMappingURL=index.js.map","import { __export } from \"../../_virtual/rolldown_runtime.js\";\n\n//#region src/retrievers/document_compressors/base.ts\nvar base_exports = {};\n__export(base_exports, { BaseDocumentCompressor: () => BaseDocumentCompressor });\n/**\n* Base Document Compression class. All compressors should extend this class.\n*/\nvar BaseDocumentCompressor = class {\n\tstatic isBaseDocumentCompressor(x) {\n\t\treturn x?.compressDocuments !== void 0;\n\t}\n};\n\n//#endregion\nexport { BaseDocumentCompressor, base_exports };\n//# sourceMappingURL=base.js.map","//#region src/structured_query/ir.ts\nconst Operators = {\n\tand: \"and\",\n\tor: \"or\",\n\tnot: \"not\"\n};\nconst Comparators = {\n\teq: \"eq\",\n\tne: \"ne\",\n\tlt: \"lt\",\n\tgt: \"gt\",\n\tlte: \"lte\",\n\tgte: \"gte\"\n};\n/**\n* Abstract class for visiting expressions. Subclasses must implement\n* visitOperation, visitComparison, and visitStructuredQuery methods.\n*/\nvar Visitor = class {};\n/**\n* Abstract class representing an expression. Subclasses must implement\n* the exprName property and the accept method.\n*/\nvar Expression = class {\n\taccept(visitor) {\n\t\tif (this.exprName === \"Operation\") return visitor.visitOperation(this);\n\t\telse if (this.exprName === \"Comparison\") return visitor.visitComparison(this);\n\t\telse if (this.exprName === \"StructuredQuery\") return visitor.visitStructuredQuery(this);\n\t\telse throw new Error(\"Unknown Expression type\");\n\t}\n};\n/**\n* Abstract class representing a filter directive. It extends the\n* Expression class.\n*/\nvar FilterDirective = class extends Expression {};\n/**\n* Class representing a comparison filter directive. It extends the\n* FilterDirective class.\n*/\nvar Comparison = class extends FilterDirective {\n\texprName = \"Comparison\";\n\tconstructor(comparator, attribute, value) {\n\t\tsuper();\n\t\tthis.comparator = comparator;\n\t\tthis.attribute = attribute;\n\t\tthis.value = value;\n\t}\n};\n/**\n* Class representing an operation filter directive. It extends the\n* FilterDirective class.\n*/\nvar Operation = class extends FilterDirective {\n\texprName = \"Operation\";\n\tconstructor(operator, args) {\n\t\tsuper();\n\t\tthis.operator = operator;\n\t\tthis.args = args;\n\t}\n};\n/**\n* Class representing a structured query expression. It extends the\n* Expression class.\n*/\nvar StructuredQuery = class extends Expression {\n\texprName = \"StructuredQuery\";\n\tconstructor(query, filter) {\n\t\tsuper();\n\t\tthis.query = query;\n\t\tthis.filter = filter;\n\t}\n};\n\n//#endregion\nexport { Comparators, Comparison, Expression, FilterDirective, Operation, Operators, StructuredQuery, Visitor };\n//# sourceMappingURL=ir.js.map","//#region src/structured_query/utils.ts\n/**\n* Checks if the provided argument is an object and not an array.\n*/\nfunction isObject(obj) {\n\treturn obj && typeof obj === \"object\" && !Array.isArray(obj);\n}\n/**\n* Checks if a provided filter is empty. The filter can be a function, an\n* object, a string, or undefined.\n*/\nfunction isFilterEmpty(filter) {\n\tif (!filter) return true;\n\tif (typeof filter === \"string\" && filter.length > 0) return false;\n\tif (typeof filter === \"function\") return false;\n\treturn isObject(filter) && Object.keys(filter).length === 0;\n}\n/**\n* Checks if the provided value is an integer.\n*/\nfunction isInt(value) {\n\tif (typeof value === \"number\") return value % 1 === 0;\n\telse if (typeof value === \"string\") {\n\t\tconst numberValue = parseInt(value, 10);\n\t\treturn !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value;\n\t}\n\treturn false;\n}\n/**\n* Checks if the provided value is a floating-point number.\n*/\nfunction isFloat(value) {\n\tif (typeof value === \"number\") return value % 1 !== 0;\n\telse if (typeof value === \"string\") {\n\t\tconst numberValue = parseFloat(value);\n\t\treturn !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value;\n\t}\n\treturn false;\n}\n/**\n* Checks if the provided value is a string that cannot be parsed into a\n* number.\n*/\nfunction isString(value) {\n\treturn typeof value === \"string\" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value);\n}\n/**\n* Checks if the provided value is a boolean.\n*/\nfunction isBoolean(value) {\n\treturn typeof value === \"boolean\";\n}\n/**\n* Casts a value that might be string or number to actual string or number.\n* Since LLM might return back an integer/float as a string, we need to cast\n* it back to a number, as many vector databases can't handle number as string\n* values as a comparator.\n*/\nfunction castValue(input) {\n\tlet value;\n\tif (isString(input)) value = input;\n\telse if (isInt(input)) value = parseInt(input, 10);\n\telse if (isFloat(input)) value = parseFloat(input);\n\telse if (isBoolean(input)) value = Boolean(input);\n\telse throw new Error(\"Unsupported value type\");\n\treturn value;\n}\n\n//#endregion\nexport { castValue, isBoolean, isFilterEmpty, isFloat, isInt, isObject, isString };\n//# sourceMappingURL=utils.js.map","import { Comparators, Operators, Visitor } from \"./ir.js\";\nimport { castValue, isFilterEmpty } from \"./utils.js\";\n\n//#region src/structured_query/base.ts\n/**\n* Abstract class that provides a blueprint for creating specific\n* translator classes. Defines two abstract methods: formatFunction and\n* mergeFilters.\n*/\nvar BaseTranslator = class extends Visitor {};\n/**\n* Class that extends the BaseTranslator class and provides concrete\n* implementations for the abstract methods. Also declares three types:\n* VisitOperationOutput, VisitComparisonOutput, and\n* VisitStructuredQueryOutput, which are used as the return types for the\n* visitOperation, visitComparison, and visitStructuredQuery methods\n* respectively.\n*/\nvar BasicTranslator = class extends BaseTranslator {\n\tallowedOperators;\n\tallowedComparators;\n\tconstructor(opts) {\n\t\tsuper();\n\t\tthis.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or];\n\t\tthis.allowedComparators = opts?.allowedComparators ?? [\n\t\t\tComparators.eq,\n\t\t\tComparators.ne,\n\t\t\tComparators.gt,\n\t\t\tComparators.gte,\n\t\t\tComparators.lt,\n\t\t\tComparators.lte\n\t\t];\n\t}\n\tformatFunction(func) {\n\t\tif (func in Comparators) {\n\t\t\tif (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(\", \")}`);\n\t\t} else if (func in Operators) {\n\t\t\tif (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(\", \")}`);\n\t\t} else throw new Error(\"Unknown comparator or operator\");\n\t\treturn `$${func}`;\n\t}\n\t/**\n\t* Visits an operation and returns a result.\n\t* @param operation The operation to visit.\n\t* @returns The result of visiting the operation.\n\t*/\n\tvisitOperation(operation) {\n\t\tconst args = operation.args?.map((arg) => arg.accept(this));\n\t\treturn { [this.formatFunction(operation.operator)]: args };\n\t}\n\t/**\n\t* Visits a comparison and returns a result.\n\t* @param comparison The comparison to visit.\n\t* @returns The result of visiting the comparison.\n\t*/\n\tvisitComparison(comparison) {\n\t\treturn { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } };\n\t}\n\t/**\n\t* Visits a structured query and returns a result.\n\t* @param query The structured query to visit.\n\t* @returns The result of visiting the structured query.\n\t*/\n\tvisitStructuredQuery(query) {\n\t\tlet nextArg = {};\n\t\tif (query.filter) nextArg = { filter: query.filter.accept(this) };\n\t\treturn nextArg;\n\t}\n\tmergeFilters(defaultFilter, generatedFilter, mergeType = \"and\", forceDefaultFilter = false) {\n\t\tif (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0;\n\t\tif (isFilterEmpty(defaultFilter) || mergeType === \"replace\") {\n\t\t\tif (isFilterEmpty(generatedFilter)) return void 0;\n\t\t\treturn generatedFilter;\n\t\t}\n\t\tif (isFilterEmpty(generatedFilter)) {\n\t\t\tif (forceDefaultFilter) return defaultFilter;\n\t\t\tif (mergeType === \"and\") return void 0;\n\t\t\treturn defaultFilter;\n\t\t}\n\t\tif (mergeType === \"and\") return { $and: [defaultFilter, generatedFilter] };\n\t\telse if (mergeType === \"or\") return { $or: [defaultFilter, generatedFilter] };\n\t\telse throw new Error(\"Unknown merge type\");\n\t}\n};\n\n//#endregion\nexport { BaseTranslator, BasicTranslator };\n//# sourceMappingURL=base.js.map","import { Comparators, Operators } from \"./ir.js\";\nimport { castValue, isFilterEmpty } from \"./utils.js\";\nimport { BaseTranslator } from \"./base.js\";\n\n//#region src/structured_query/functional.ts\n/**\n* A class that extends `BaseTranslator` to translate structured queries\n* into functional filters.\n* @example\n* ```typescript\n* const functionalTranslator = new FunctionalTranslator();\n* const relevantDocuments = await functionalTranslator.getRelevantDocuments(\n* \"Which movies are rated higher than 8.5?\",\n* );\n* ```\n*/\nvar FunctionalTranslator = class extends BaseTranslator {\n\tallowedOperators = [Operators.and, Operators.or];\n\tallowedComparators = [\n\t\tComparators.eq,\n\t\tComparators.ne,\n\t\tComparators.gt,\n\t\tComparators.gte,\n\t\tComparators.lt,\n\t\tComparators.lte\n\t];\n\tformatFunction() {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\t/**\n\t* Returns the allowed comparators for a given data type.\n\t* @param input The input value to get the allowed comparators for.\n\t* @returns An array of allowed comparators for the input data type.\n\t*/\n\tgetAllowedComparatorsForType(inputType) {\n\t\tswitch (inputType) {\n\t\t\tcase \"string\": return [\n\t\t\t\tComparators.eq,\n\t\t\t\tComparators.ne,\n\t\t\t\tComparators.gt,\n\t\t\t\tComparators.gte,\n\t\t\t\tComparators.lt,\n\t\t\t\tComparators.lte\n\t\t\t];\n\t\t\tcase \"number\": return [\n\t\t\t\tComparators.eq,\n\t\t\t\tComparators.ne,\n\t\t\t\tComparators.gt,\n\t\t\t\tComparators.gte,\n\t\t\t\tComparators.lt,\n\t\t\t\tComparators.lte\n\t\t\t];\n\t\t\tcase \"boolean\": return [Comparators.eq, Comparators.ne];\n\t\t\tdefault: throw new Error(`Unsupported data type: ${inputType}`);\n\t\t}\n\t}\n\t/**\n\t* Returns a function that performs a comparison based on the provided\n\t* comparator.\n\t* @param comparator The comparator to base the comparison function on.\n\t* @returns A function that takes two arguments and returns a boolean based on the comparison.\n\t*/\n\tgetComparatorFunction(comparator) {\n\t\tswitch (comparator) {\n\t\t\tcase Comparators.eq: return (a, b) => a === b;\n\t\t\tcase Comparators.ne: return (a, b) => a !== b;\n\t\t\tcase Comparators.gt: return (a, b) => a > b;\n\t\t\tcase Comparators.gte: return (a, b) => a >= b;\n\t\t\tcase Comparators.lt: return (a, b) => a < b;\n\t\t\tcase Comparators.lte: return (a, b) => a <= b;\n\t\t\tdefault: throw new Error(\"Unknown comparator\");\n\t\t}\n\t}\n\t/**\n\t* Returns a function that performs an operation based on the provided\n\t* operator.\n\t* @param operator The operator to base the operation function on.\n\t* @returns A function that takes two boolean arguments and returns a boolean based on the operation.\n\t*/\n\tgetOperatorFunction(operator) {\n\t\tswitch (operator) {\n\t\t\tcase Operators.and: return (a, b) => a && b;\n\t\t\tcase Operators.or: return (a, b) => a || b;\n\t\t\tdefault: throw new Error(\"Unknown operator\");\n\t\t}\n\t}\n\t/**\n\t* Visits the operation part of a structured query and translates it into\n\t* a functional filter.\n\t* @param operation The operation part of a structured query.\n\t* @returns A function that takes a `Document` as an argument and returns a boolean based on the operation.\n\t*/\n\tvisitOperation(operation) {\n\t\tconst { operator, args } = operation;\n\t\tif (this.allowedOperators.includes(operator)) {\n\t\t\tconst operatorFunction = this.getOperatorFunction(operator);\n\t\t\treturn (document) => {\n\t\t\t\tif (!args) return true;\n\t\t\t\treturn args.reduce((acc, arg) => {\n\t\t\t\t\tconst result = arg.accept(this);\n\t\t\t\t\tif (typeof result === \"function\") return operatorFunction(acc, result(document));\n\t\t\t\t\telse throw new Error(\"Filter is not a function\");\n\t\t\t\t}, true);\n\t\t\t};\n\t\t} else throw new Error(\"Operator not allowed\");\n\t}\n\t/**\n\t* Visits the comparison part of a structured query and translates it into\n\t* a functional filter.\n\t* @param comparison The comparison part of a structured query.\n\t* @returns A function that takes a `Document` as an argument and returns a boolean based on the comparison.\n\t*/\n\tvisitComparison(comparison) {\n\t\tconst { comparator, attribute, value } = comparison;\n\t\tconst undefinedTrue = [Comparators.ne];\n\t\tif (this.allowedComparators.includes(comparator)) {\n\t\t\tif (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`);\n\t\t\tconst comparatorFunction = this.getComparatorFunction(comparator);\n\t\t\treturn (document) => {\n\t\t\t\tconst documentValue = document.metadata[attribute];\n\t\t\t\tif (documentValue === void 0) {\n\t\t\t\t\tif (undefinedTrue.includes(comparator)) return true;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn comparatorFunction(documentValue, castValue(value));\n\t\t\t};\n\t\t} else throw new Error(\"Comparator not allowed\");\n\t}\n\t/**\n\t* Visits a structured query and translates it into a functional filter.\n\t* @param query The structured query to translate.\n\t* @returns An object containing a `filter` property, which is a function that takes a `Document` as an argument and returns a boolean based on the structured query.\n\t*/\n\tvisitStructuredQuery(query) {\n\t\tif (!query.filter) return {};\n\t\tconst filterFunction = query.filter?.accept(this);\n\t\tif (typeof filterFunction !== \"function\") throw new Error(\"Structured query filter is not a function\");\n\t\treturn { filter: filterFunction };\n\t}\n\t/**\n\t* Merges two filters into one, based on the specified merge type.\n\t* @param defaultFilter The default filter function.\n\t* @param generatedFilter The generated filter function.\n\t* @param mergeType The type of merge to perform. Can be 'and', 'or', or 'replace'. Default is 'and'.\n\t* @returns A function that takes a `Document` as an argument and returns a boolean based on the merged filters, or `undefined` if both filters are empty.\n\t*/\n\tmergeFilters(defaultFilter, generatedFilter, mergeType = \"and\") {\n\t\tif (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0;\n\t\tif (isFilterEmpty(defaultFilter) || mergeType === \"replace\") {\n\t\t\tif (isFilterEmpty(generatedFilter)) return void 0;\n\t\t\treturn generatedFilter;\n\t\t}\n\t\tif (isFilterEmpty(generatedFilter)) {\n\t\t\tif (mergeType === \"and\") return void 0;\n\t\t\treturn defaultFilter;\n\t\t}\n\t\tif (mergeType === \"and\") return (document) => defaultFilter(document) && generatedFilter(document);\n\t\telse if (mergeType === \"or\") return (document) => defaultFilter(document) || generatedFilter(document);\n\t\telse throw new Error(\"Unknown merge type\");\n\t}\n};\n\n//#endregion\nexport { FunctionalTranslator };\n//# sourceMappingURL=functional.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { Comparators, Comparison, Expression, FilterDirective, Operation, Operators, StructuredQuery, Visitor } from \"./ir.js\";\nimport { castValue, isBoolean, isFilterEmpty, isFloat, isInt, isObject, isString } from \"./utils.js\";\nimport { BaseTranslator, BasicTranslator } from \"./base.js\";\nimport { FunctionalTranslator } from \"./functional.js\";\n\n//#region src/structured_query/index.ts\nvar structured_query_exports = {};\n__export(structured_query_exports, {\n\tBaseTranslator: () => BaseTranslator,\n\tBasicTranslator: () => BasicTranslator,\n\tComparators: () => Comparators,\n\tComparison: () => Comparison,\n\tExpression: () => Expression,\n\tFilterDirective: () => FilterDirective,\n\tFunctionalTranslator: () => FunctionalTranslator,\n\tOperation: () => Operation,\n\tOperators: () => Operators,\n\tStructuredQuery: () => StructuredQuery,\n\tVisitor: () => Visitor,\n\tcastValue: () => castValue,\n\tisBoolean: () => isBoolean,\n\tisFilterEmpty: () => isFilterEmpty,\n\tisFloat: () => isFloat,\n\tisInt: () => isInt,\n\tisObject: () => isObject,\n\tisString: () => isString\n});\n\n//#endregion\nexport { BaseTranslator, BasicTranslator, Comparators, Comparison, Expression, FilterDirective, FunctionalTranslator, Operation, Operators, StructuredQuery, Visitor, castValue, isBoolean, isFilterEmpty, isFloat, isInt, isObject, isString, structured_query_exports };\n//# sourceMappingURL=index.js.map","import { isInteropZodSchema } from \"../utils/types/zod.js\";\nimport { Runnable } from \"../runnables/base.js\";\n\n//#region src/tools/types.ts\n/**\n* Confirm whether the inputted tool is an instance of `StructuredToolInterface`.\n*\n* @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.\n* @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.\n*/\nfunction isStructuredTool(tool) {\n\treturn tool !== void 0 && Array.isArray(tool.lc_namespace);\n}\n/**\n* Confirm whether the inputted tool is an instance of `RunnableToolLike`.\n*\n* @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.\n* @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.\n*/\nfunction isRunnableToolLike(tool) {\n\treturn tool !== void 0 && Runnable.isRunnable(tool) && \"lc_name\" in tool.constructor && typeof tool.constructor.lc_name === \"function\" && tool.constructor.lc_name() === \"RunnableToolLike\";\n}\n/**\n* Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`.\n*\n* @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`.\n* @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`.\n*/\nfunction isStructuredToolParams(tool) {\n\treturn !!tool && typeof tool === \"object\" && \"name\" in tool && \"schema\" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === \"object\" && \"type\" in tool.schema && typeof tool.schema.type === \"string\" && [\n\t\t\"null\",\n\t\t\"boolean\",\n\t\t\"object\",\n\t\t\"array\",\n\t\t\"number\",\n\t\t\"string\"\n\t].includes(tool.schema.type));\n}\n/**\n* Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.\n* It returns `is StructuredToolParams` since that is the most minimal interface of the three,\n* while still containing the necessary properties to be passed to a LLM for tool calling.\n*\n* @param {unknown | undefined} tool The tool to check if it is a LangChain tool.\n* @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool.\n*/\nfunction isLangChainTool(tool) {\n\treturn isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool);\n}\n\n//#endregion\nexport { isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams };\n//# sourceMappingURL=types.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { ToolMessage, isDirectToolOutput } from \"../messages/tool.js\";\nimport { ToolInputParsingException, _configHasToolCallId, _isToolCall } from \"./utils.js\";\nimport { CallbackManager, parseCallbackConfigArg } from \"../callbacks/manager.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/async_local_storage/index.js\";\nimport \"../singletons/index.js\";\nimport { ensureConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys } from \"../runnables/config.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport { interopParseAsync, isInteropZodSchema, isSimpleStringZodSchema } from \"../utils/types/zod.js\";\nimport { validatesOnlyStrings } from \"../utils/json_schema.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport { isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams } from \"./types.js\";\nimport { z } from \"zod/v3\";\nimport { validate } from \"@cfworker/json-schema\";\nimport { z as z$1 } from \"zod/v4\";\n\n//#region src/tools/index.ts\nvar tools_exports = {};\n__export(tools_exports, {\n\tBaseToolkit: () => BaseToolkit,\n\tDynamicStructuredTool: () => DynamicStructuredTool,\n\tDynamicTool: () => DynamicTool,\n\tStructuredTool: () => StructuredTool,\n\tTool: () => Tool,\n\tToolInputParsingException: () => ToolInputParsingException,\n\tisLangChainTool: () => isLangChainTool,\n\tisRunnableToolLike: () => isRunnableToolLike,\n\tisStructuredTool: () => isStructuredTool,\n\tisStructuredToolParams: () => isStructuredToolParams,\n\ttool: () => tool\n});\n/**\n* Base class for Tools that accept input of any shape defined by a Zod schema.\n*/\nvar StructuredTool = class extends BaseLangChain {\n\t/**\n\t* Whether to return the tool's output directly.\n\t*\n\t* Setting this to true means that after the tool is called,\n\t* an agent should stop looping.\n\t*/\n\treturnDirect = false;\n\tverboseParsingErrors = false;\n\tget lc_namespace() {\n\t\treturn [\"langchain\", \"tools\"];\n\t}\n\t/**\n\t* The tool response format.\n\t*\n\t* If \"content\" then the output of the tool is interpreted as the contents of a\n\t* ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n\t* two-tuple corresponding to the (content, artifact) of a ToolMessage.\n\t*\n\t* @default \"content\"\n\t*/\n\tresponseFormat = \"content\";\n\t/**\n\t* Default config object for the tool runnable.\n\t*/\n\tdefaultConfig;\n\tconstructor(fields) {\n\t\tsuper(fields ?? {});\n\t\tthis.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n\t\tthis.responseFormat = fields?.responseFormat ?? this.responseFormat;\n\t\tthis.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n\t\tthis.metadata = fields?.metadata ?? this.metadata;\n\t}\n\t/**\n\t* Invokes the tool with the provided input and configuration.\n\t* @param input The input for the tool.\n\t* @param config Optional configuration for the tool.\n\t* @returns A Promise that resolves with the tool's output.\n\t*/\n\tasync invoke(input, config) {\n\t\tlet toolInput;\n\t\tlet enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config));\n\t\tif (_isToolCall(input)) {\n\t\t\ttoolInput = input.args;\n\t\t\tenrichedConfig = {\n\t\t\t\t...enrichedConfig,\n\t\t\t\ttoolCall: input\n\t\t\t};\n\t\t} else toolInput = input;\n\t\treturn this.call(toolInput, enrichedConfig);\n\t}\n\t/**\n\t* @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n\t*\n\t* Calls the tool with the provided argument, configuration, and tags. It\n\t* parses the input according to the schema, handles any errors, and\n\t* manages callbacks.\n\t* @param arg The input argument for the tool.\n\t* @param configArg Optional configuration or callbacks for the tool.\n\t* @param tags Optional tags for the tool.\n\t* @returns A Promise that resolves with a string.\n\t*/\n\tasync call(arg, configArg, tags) {\n\t\tconst inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\t\tlet parsed;\n\t\tif (isInteropZodSchema(this.schema)) try {\n\t\t\tparsed = await interopParseAsync(this.schema, inputForValidation);\n\t\t} catch (e) {\n\t\t\tlet message = `Received tool input did not match expected schema`;\n\t\t\tif (this.verboseParsingErrors) message = `${message}\\nDetails: ${e.message}`;\n\t\t\tif (e instanceof Error && e.constructor.name === \"ZodError\") message = `${message}\\n\\n${z$1.prettifyError(e)}`;\n\t\t\tthrow new ToolInputParsingException(message, JSON.stringify(arg));\n\t\t}\n\t\telse {\n\t\t\tconst result$1 = validate(inputForValidation, this.schema);\n\t\t\tif (!result$1.valid) {\n\t\t\t\tlet message = `Received tool input did not match expected schema`;\n\t\t\t\tif (this.verboseParsingErrors) message = `${message}\\nDetails: ${result$1.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join(\"\\n\")}`;\n\t\t\t\tthrow new ToolInputParsingException(message, JSON.stringify(arg));\n\t\t\t}\n\t\t\tparsed = inputForValidation;\n\t\t}\n\t\tconst config = parseCallbackConfigArg(configArg);\n\t\tconst callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });\n\t\tconst runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === \"string\" ? arg : JSON.stringify(arg), config.runId, void 0, void 0, void 0, config.runName);\n\t\tdelete config.runId;\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this._call(parsed, runManager, config);\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleToolError(e);\n\t\t\tthrow e;\n\t\t}\n\t\tlet content;\n\t\tlet artifact;\n\t\tif (this.responseFormat === \"content_and_artifact\") if (Array.isArray(result) && result.length === 2) [content, artifact] = result;\n\t\telse throw new Error(`Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(result)}`);\n\t\telse content = result;\n\t\tlet toolCallId;\n\t\tif (_isToolCall(arg)) toolCallId = arg.id;\n\t\tif (!toolCallId && _configHasToolCallId(config)) toolCallId = config.toolCall.id;\n\t\tconst formattedOutput = _formatToolOutput({\n\t\t\tcontent,\n\t\t\tartifact,\n\t\t\ttoolCallId,\n\t\t\tname: this.name,\n\t\t\tmetadata: this.metadata\n\t\t});\n\t\tawait runManager?.handleToolEnd(formattedOutput);\n\t\treturn formattedOutput;\n\t}\n};\n/**\n* Base class for Tools that accept input as a string.\n*/\nvar Tool = class extends StructuredTool {\n\tschema = z.object({ input: z.string().optional() }).transform((obj) => obj.input);\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t}\n\t/**\n\t* @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n\t*\n\t* Calls the tool with the provided argument and callbacks. It handles\n\t* string inputs specifically.\n\t* @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n\t* @param callbacks Optional callbacks for the tool.\n\t* @returns A Promise that resolves with a string.\n\t*/\n\tcall(arg, callbacks) {\n\t\tconst structuredArg = typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\t\treturn super.call(structuredArg, callbacks);\n\t}\n};\n/**\n* A tool that can be created dynamically from a function, name, and description.\n*/\nvar DynamicTool = class extends Tool {\n\tstatic lc_name() {\n\t\treturn \"DynamicTool\";\n\t}\n\tname;\n\tdescription;\n\tfunc;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.name = fields.name;\n\t\tthis.description = fields.description;\n\t\tthis.func = fields.func;\n\t\tthis.returnDirect = fields.returnDirect ?? this.returnDirect;\n\t}\n\t/**\n\t* @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n\t*/\n\tasync call(arg, configArg) {\n\t\tconst config = parseCallbackConfigArg(configArg);\n\t\tif (config.runName === void 0) config.runName = this.name;\n\t\treturn super.call(arg, config);\n\t}\n\t/** @ignore */\n\tasync _call(input, runManager, parentConfig) {\n\t\treturn this.func(input, runManager, parentConfig);\n\t}\n};\n/**\n* A tool that can be created dynamically from a function, name, and\n* description, designed to work with structured data. It extends the\n* StructuredTool class and overrides the _call method to execute the\n* provided function when the tool is called.\n*\n* Schema can be passed as Zod or JSON schema. The tool will not validate\n* input if JSON schema is passed.\n*/\nvar DynamicStructuredTool = class extends StructuredTool {\n\tstatic lc_name() {\n\t\treturn \"DynamicStructuredTool\";\n\t}\n\tname;\n\tdescription;\n\tfunc;\n\tschema;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.name = fields.name;\n\t\tthis.description = fields.description;\n\t\tthis.func = fields.func;\n\t\tthis.returnDirect = fields.returnDirect ?? this.returnDirect;\n\t\tthis.schema = fields.schema;\n\t}\n\t/**\n\t* @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n\t*/\n\tasync call(arg, configArg, tags) {\n\t\tconst config = parseCallbackConfigArg(configArg);\n\t\tif (config.runName === void 0) config.runName = this.name;\n\t\treturn super.call(arg, config, tags);\n\t}\n\t_call(arg, runManager, parentConfig) {\n\t\treturn this.func(arg, runManager, parentConfig);\n\t}\n};\n/**\n* Abstract base class for toolkits in LangChain. Toolkits are collections\n* of tools that agents can use. Subclasses must implement the `tools`\n* property to provide the specific tools for the toolkit.\n*/\nvar BaseToolkit = class {\n\tgetTools() {\n\t\treturn this.tools;\n\t}\n};\nfunction tool(func, fields) {\n\tconst isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n\tconst isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\tif (!fields.schema || isSimpleStringSchema || isStringJSONSchema) return new DynamicTool({\n\t\t...fields,\n\t\tdescription: fields.description ?? fields.schema?.description ?? `${fields.name} tool`,\n\t\tfunc: async (input, runManager, config) => {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tconst childConfig = patchConfig(config, { callbacks: runManager?.getChild() });\n\t\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolve(func(input, childConfig));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\treject(e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t});\n\tconst schema = fields.schema;\n\tconst description = fields.description ?? fields.schema.description ?? `${fields.name} tool`;\n\treturn new DynamicStructuredTool({\n\t\t...fields,\n\t\tdescription,\n\t\tschema,\n\t\tfunc: async (input, runManager, config) => {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (config?.signal) config.signal.addEventListener(\"abort\", () => {\n\t\t\t\t\treturn reject(getAbortSignalError(config.signal));\n\t\t\t\t});\n\t\t\t\tconst childConfig = patchConfig(config, { callbacks: runManager?.getChild() });\n\t\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await func(input, childConfig);\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t* If the signal is aborted, we don't want to resolve the promise\n\t\t\t\t\t\t* as the promise is already rejected.\n\t\t\t\t\t\t*/\n\t\t\t\t\t\tif (config?.signal?.aborted) return;\n\t\t\t\t\t\tresolve(result);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\treject(e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t});\n}\nfunction _formatToolOutput(params) {\n\tconst { content, artifact, toolCallId, metadata } = params;\n\tif (toolCallId && !isDirectToolOutput(content)) if (typeof content === \"string\" || Array.isArray(content) && content.every((item) => typeof item === \"object\")) return new ToolMessage({\n\t\tstatus: \"success\",\n\t\tcontent,\n\t\tartifact,\n\t\ttool_call_id: toolCallId,\n\t\tname: params.name,\n\t\tmetadata\n\t});\n\telse return new ToolMessage({\n\t\tstatus: \"success\",\n\t\tcontent: _stringify(content),\n\t\tartifact,\n\t\ttool_call_id: toolCallId,\n\t\tname: params.name,\n\t\tmetadata\n\t});\n\telse return content;\n}\nfunction _stringify(content) {\n\ttry {\n\t\treturn JSON.stringify(content, null, 2) ?? \"\";\n\t} catch (_noOp) {\n\t\treturn `${content}`;\n\t}\n}\n\n//#endregion\nexport { BaseToolkit, DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolInputParsingException, isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams, tool, tools_exports };\n//# sourceMappingURL=index.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { BaseTracer } from \"./base.js\";\n\n//#region src/tracers/run_collector.ts\nvar run_collector_exports = {};\n__export(run_collector_exports, { RunCollectorCallbackHandler: () => RunCollectorCallbackHandler });\n/**\n* A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object.\n* For instance, it makes it easy to fetch the run ID and then do things with that, such as log feedback.\n*/\nvar RunCollectorCallbackHandler = class extends BaseTracer {\n\t/** The name of the callback handler. */\n\tname = \"run_collector\";\n\t/** The ID of the example. */\n\texampleId;\n\t/** An array of traced runs. */\n\ttracedRuns;\n\t/**\n\t* Creates a new instance of the RunCollectorCallbackHandler class.\n\t* @param exampleId The ID of the example.\n\t*/\n\tconstructor({ exampleId } = {}) {\n\t\tsuper({ _awaitHandler: true });\n\t\tthis.exampleId = exampleId;\n\t\tthis.tracedRuns = [];\n\t}\n\t/**\n\t* Persists the given run object.\n\t* @param run The run object to persist.\n\t*/\n\tasync persistRun(run) {\n\t\tconst run_ = { ...run };\n\t\trun_.reference_example_id = this.exampleId;\n\t\tthis.tracedRuns.push(run_);\n\t}\n};\n\n//#endregion\nexport { RunCollectorCallbackHandler, run_collector_exports };\n//# sourceMappingURL=run_collector.js.map","//#region src/types/stream.ts\nvar stream_exports = {};\n\n//#endregion\nexport { stream_exports };\n//# sourceMappingURL=stream.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\n\n//#region src/utils/chunk_array.ts\nvar chunk_array_exports = {};\n__export(chunk_array_exports, { chunkArray: () => chunkArray });\nconst chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => {\n\tconst chunkIndex = Math.floor(index / chunkSize);\n\tconst chunk = chunks[chunkIndex] || [];\n\tchunks[chunkIndex] = chunk.concat([elem]);\n\treturn chunks;\n}, []);\n\n//#endregion\nexport { chunkArray, chunk_array_exports };\n//# sourceMappingURL=chunk_array.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { IterableReadableStream } from \"./stream.js\";\n\n//#region src/utils/event_source_parse.ts\nvar event_source_parse_exports = {};\n__export(event_source_parse_exports, {\n\tEventStreamContentType: () => EventStreamContentType,\n\tconvertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream,\n\tgetBytes: () => getBytes,\n\tgetLines: () => getLines,\n\tgetMessages: () => getMessages\n});\nconst EventStreamContentType = \"text/event-stream\";\n/**\n* Converts a ReadableStream into a callback pattern.\n* @param stream The input ReadableStream.\n* @param onChunk A function that will be called on each new byte chunk in the stream.\n* @returns {Promise} A promise that will be resolved when the stream closes.\n*/\nasync function getBytes(stream, onChunk) {\n\tif (stream instanceof ReadableStream) {\n\t\tconst reader = stream.getReader();\n\t\twhile (true) {\n\t\t\tconst result = await reader.read();\n\t\t\tif (result.done) {\n\t\t\t\tonChunk(new Uint8Array(), true);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tonChunk(result.value);\n\t\t}\n\t} else try {\n\t\tfor await (const chunk of stream) onChunk(new Uint8Array(chunk));\n\t\tonChunk(new Uint8Array(), true);\n\t} catch (e) {\n\t\tthrow new Error([\n\t\t\t\"Parsing event source stream failed.\",\n\t\t\t\"Ensure your implementation of fetch returns a web or Node readable stream.\",\n\t\t\t`Error: ${e.message}`\n\t\t].join(\"\\n\"));\n\t}\n}\nvar ControlChars = /* @__PURE__ */ function(ControlChars$1) {\n\tControlChars$1[ControlChars$1[\"NewLine\"] = 10] = \"NewLine\";\n\tControlChars$1[ControlChars$1[\"CarriageReturn\"] = 13] = \"CarriageReturn\";\n\tControlChars$1[ControlChars$1[\"Space\"] = 32] = \"Space\";\n\tControlChars$1[ControlChars$1[\"Colon\"] = 58] = \"Colon\";\n\treturn ControlChars$1;\n}(ControlChars || {});\n/**\n* Parses arbitary byte chunks into EventSource line buffers.\n* Each line should be of the format \"field: value\" and ends with \\r, \\n, or \\r\\n.\n* @param onLine A function that will be called on each new EventSource line.\n* @returns A function that should be called for each incoming byte chunk.\n*/\nfunction getLines(onLine) {\n\tlet buffer;\n\tlet position;\n\tlet fieldLength;\n\tlet discardTrailingNewline = false;\n\treturn function onChunk(arr, flush) {\n\t\tif (flush) {\n\t\t\tonLine(arr, 0, true);\n\t\t\treturn;\n\t\t}\n\t\tif (buffer === void 0) {\n\t\t\tbuffer = arr;\n\t\t\tposition = 0;\n\t\t\tfieldLength = -1;\n\t\t} else buffer = concat(buffer, arr);\n\t\tconst bufLength = buffer.length;\n\t\tlet lineStart = 0;\n\t\twhile (position < bufLength) {\n\t\t\tif (discardTrailingNewline) {\n\t\t\t\tif (buffer[position] === ControlChars.NewLine) lineStart = ++position;\n\t\t\t\tdiscardTrailingNewline = false;\n\t\t\t}\n\t\t\tlet lineEnd = -1;\n\t\t\tfor (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) {\n\t\t\t\tcase ControlChars.Colon:\n\t\t\t\t\tif (fieldLength === -1) fieldLength = position - lineStart;\n\t\t\t\t\tbreak;\n\t\t\t\tcase ControlChars.CarriageReturn: discardTrailingNewline = true;\n\t\t\t\tcase ControlChars.NewLine:\n\t\t\t\t\tlineEnd = position;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (lineEnd === -1) break;\n\t\t\tonLine(buffer.subarray(lineStart, lineEnd), fieldLength);\n\t\t\tlineStart = position;\n\t\t\tfieldLength = -1;\n\t\t}\n\t\tif (lineStart === bufLength) buffer = void 0;\n\t\telse if (lineStart !== 0) {\n\t\t\tbuffer = buffer.subarray(lineStart);\n\t\t\tposition -= lineStart;\n\t\t}\n\t};\n}\n/**\n* Parses line buffers into EventSourceMessages.\n* @param onId A function that will be called on each `id` field.\n* @param onRetry A function that will be called on each `retry` field.\n* @param onMessage A function that will be called on each message.\n* @returns A function that should be called for each incoming line buffer.\n*/\nfunction getMessages(onMessage, onId, onRetry) {\n\tlet message = newMessage();\n\tconst decoder = new TextDecoder();\n\treturn function onLine(line, fieldLength, flush) {\n\t\tif (flush) {\n\t\t\tif (!isEmpty(message)) {\n\t\t\t\tonMessage?.(message);\n\t\t\t\tmessage = newMessage();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tonMessage?.(message);\n\t\t\tmessage = newMessage();\n\t\t} else if (fieldLength > 0) {\n\t\t\tconst field = decoder.decode(line.subarray(0, fieldLength));\n\t\t\tconst valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);\n\t\t\tconst value = decoder.decode(line.subarray(valueOffset));\n\t\t\tswitch (field) {\n\t\t\t\tcase \"data\":\n\t\t\t\t\tmessage.data = message.data ? message.data + \"\\n\" + value : value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"event\":\n\t\t\t\t\tmessage.event = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"id\":\n\t\t\t\t\tonId?.(message.id = value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"retry\": {\n\t\t\t\t\tconst retry = parseInt(value, 10);\n\t\t\t\t\tif (!Number.isNaN(retry)) onRetry?.(message.retry = retry);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\nfunction concat(a, b) {\n\tconst res = new Uint8Array(a.length + b.length);\n\tres.set(a);\n\tres.set(b, a.length);\n\treturn res;\n}\nfunction newMessage() {\n\treturn {\n\t\tdata: \"\",\n\t\tevent: \"\",\n\t\tid: \"\",\n\t\tretry: void 0\n\t};\n}\nfunction convertEventStreamToIterableReadableDataStream(stream, onMetadataEvent) {\n\tconst dataStream = new ReadableStream({ async start(controller) {\n\t\tconst enqueueLine = getMessages((msg) => {\n\t\t\tif (msg.event === \"error\") throw new Error(msg.data ?? \"Unspecified event streaming error.\");\n\t\t\telse if (msg.event === \"metadata\") onMetadataEvent?.(msg);\n\t\t\telse if (msg.data) controller.enqueue(msg.data);\n\t\t});\n\t\tconst onLine = (line, fieldLength, flush) => {\n\t\t\tenqueueLine(line, fieldLength, flush);\n\t\t\tif (flush) controller.close();\n\t\t};\n\t\tawait getBytes(stream, getLines(onLine));\n\t} });\n\treturn IterableReadableStream.fromReadableStream(dataStream);\n}\nfunction isEmpty(message) {\n\treturn message.data === \"\" && message.event === \"\" && message.id === \"\" && message.retry === void 0;\n}\n\n//#endregion\nexport { EventStreamContentType, convertEventStreamToIterableReadableDataStream, event_source_parse_exports, getBytes, getLines, getMessages };\n//# sourceMappingURL=event_source_parse.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { toJsonSchema } from \"./json_schema.js\";\nimport { isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams } from \"../tools/types.js\";\n\n//#region src/utils/function_calling.ts\nvar function_calling_exports = {};\n__export(function_calling_exports, {\n\tconvertToOpenAIFunction: () => convertToOpenAIFunction,\n\tconvertToOpenAITool: () => convertToOpenAITool,\n\tisLangChainTool: () => isLangChainTool,\n\tisRunnableToolLike: () => isRunnableToolLike,\n\tisStructuredTool: () => isStructuredTool,\n\tisStructuredToolParams: () => isStructuredToolParams\n});\n/**\n* Formats a `StructuredTool` or `RunnableToolLike` instance into a format\n* that is compatible with OpenAI function calling. If `StructuredTool` or\n* `RunnableToolLike` has a zod schema, the output will be converted into a\n* JSON schema, which is then used as the parameters for the OpenAI tool.\n*\n* @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function.\n* @returns {FunctionDefinition} The inputted tool in OpenAI function format.\n*/\nfunction convertToOpenAIFunction(tool, fields) {\n\tconst fieldsCopy = typeof fields === \"number\" ? void 0 : fields;\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: toJsonSchema(tool.schema),\n\t\t...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {}\n\t};\n}\n/**\n* Formats a `StructuredTool` or `RunnableToolLike` instance into a\n* format that is compatible with OpenAI tool calling. If `StructuredTool` or\n* `RunnableToolLike` has a zod schema, the output will be converted into a\n* JSON schema, which is then used as the parameters for the OpenAI tool.\n*\n* @param {StructuredToolInterface | Record | RunnableToolLike} tool The tool to convert to an OpenAI tool.\n* @returns {ToolDefinition} The inputted tool in OpenAI tool format.\n*/\nfunction convertToOpenAITool(tool, fields) {\n\tconst fieldsCopy = typeof fields === \"number\" ? void 0 : fields;\n\tlet toolDef;\n\tif (isLangChainTool(tool)) toolDef = {\n\t\ttype: \"function\",\n\t\tfunction: convertToOpenAIFunction(tool)\n\t};\n\telse toolDef = tool;\n\tif (fieldsCopy?.strict !== void 0) toolDef.function.strict = fieldsCopy.strict;\n\treturn toolDef;\n}\n\n//#endregion\nexport { convertToOpenAIFunction, convertToOpenAITool, function_calling_exports, isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams };\n//# sourceMappingURL=function_calling.js.map","//#region src/utils/ml-distance/similarities.ts\n/**\n* Returns the average of cosine distances between vectors a and b\n* @param a - first vector\n* @param b - second vector\n*\n*/\nfunction cosine(a, b) {\n\tlet p = 0;\n\tlet p2 = 0;\n\tlet q2 = 0;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tp += a[i] * b[i];\n\t\tp2 += a[i] * a[i];\n\t\tq2 += b[i] * b[i];\n\t}\n\treturn p / (Math.sqrt(p2) * Math.sqrt(q2));\n}\n\n//#endregion\nexport { cosine };\n//# sourceMappingURL=similarities.js.map","//#region src/utils/ml-distance/distances.ts\n/**\n*Returns the Inner Product similarity between vectors a and b\n* @link [Inner Product Similarity algorithm](https://www.naun.org/main/NAUN/ijmmas/mmmas-49.pdf)\n* @param a - first vector\n* @param b - second vector\n*\n*/\nfunction innerProduct(a, b) {\n\tlet ans = 0;\n\tfor (let i = 0; i < a.length; i++) ans += a[i] * b[i];\n\treturn ans;\n}\n\n//#endregion\nexport { innerProduct };\n//# sourceMappingURL=distances.js.map","//#region src/utils/ml-distance-euclidean/euclidean.ts\nfunction squaredEuclidean(p, q) {\n\tlet d = 0;\n\tfor (let i = 0; i < p.length; i++) d += (p[i] - q[i]) * (p[i] - q[i]);\n\treturn d;\n}\nfunction euclidean(p, q) {\n\treturn Math.sqrt(squaredEuclidean(p, q));\n}\n\n//#endregion\nexport { euclidean };\n//# sourceMappingURL=euclidean.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { cosine } from \"./ml-distance/similarities.js\";\nimport { innerProduct } from \"./ml-distance/distances.js\";\nimport { euclidean } from \"./ml-distance-euclidean/euclidean.js\";\n\n//#region src/utils/math.ts\nvar math_exports = {};\n__export(math_exports, {\n\tcosineSimilarity: () => cosineSimilarity,\n\teuclideanDistance: () => euclideanDistance,\n\tinnerProduct: () => innerProduct$1,\n\tmatrixFunc: () => matrixFunc,\n\tmaximalMarginalRelevance: () => maximalMarginalRelevance,\n\tnormalize: () => normalize\n});\n/**\n* Apply a row-wise function between two matrices with the same number of columns.\n*\n* @param {number[][]} X - The first matrix.\n* @param {number[][]} Y - The second matrix.\n* @param {VectorFunction} func - The function to apply.\n*\n* @throws {Error} If the number of columns in X and Y are not the same.\n*\n* @returns {number[][] | [[]]} A matrix where each row represents the result of applying the function between the corresponding rows of X and Y.\n*/\nfunction matrixFunc(X, Y, func) {\n\tif (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) return [[]];\n\tif (X[0].length !== Y[0].length) throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`);\n\treturn X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity));\n}\nfunction normalize(M, similarity = false) {\n\tconst max = matrixMaxVal(M);\n\treturn M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max));\n}\n/**\n* This function calculates the row-wise cosine similarity between two matrices with the same number of columns.\n*\n* @param {number[][]} X - The first matrix.\n* @param {number[][]} Y - The second matrix.\n*\n* @throws {Error} If the number of columns in X and Y are not the same.\n*\n* @returns {number[][] | [[]]} A matrix where each row represents the cosine similarity values between the corresponding rows of X and Y.\n*/\nfunction cosineSimilarity(X, Y) {\n\treturn matrixFunc(X, Y, cosine);\n}\nfunction innerProduct$1(X, Y) {\n\treturn matrixFunc(X, Y, innerProduct);\n}\nfunction euclideanDistance(X, Y) {\n\treturn matrixFunc(X, Y, euclidean);\n}\n/**\n* This function implements the Maximal Marginal Relevance algorithm\n* to select a set of embeddings that maximizes the diversity and relevance to a query embedding.\n*\n* @param {number[]|number[][]} queryEmbedding - The query embedding.\n* @param {number[][]} embeddingList - The list of embeddings to select from.\n* @param {number} [lambda=0.5] - The trade-off parameter between relevance and diversity.\n* @param {number} [k=4] - The maximum number of embeddings to select.\n*\n* @returns {number[]} The indexes of the selected embeddings in the embeddingList.\n*/\nfunction maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = .5, k = 4) {\n\tif (Math.min(k, embeddingList.length) <= 0) return [];\n\tconst queryEmbeddingExpanded = Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding];\n\tconst similarityToQuery = cosineSimilarity(queryEmbeddingExpanded, embeddingList)[0];\n\tconst mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex;\n\tconst selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]];\n\tconst selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex];\n\twhile (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) {\n\t\tlet bestScore = -Infinity;\n\t\tlet bestIndex = -1;\n\t\tconst similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings);\n\t\tsimilarityToQuery.forEach((queryScore, queryScoreIndex) => {\n\t\t\tif (selectedEmbeddingsIndexes.includes(queryScoreIndex)) return;\n\t\t\tconst maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]);\n\t\t\tconst score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected;\n\t\t\tif (score > bestScore) {\n\t\t\t\tbestScore = score;\n\t\t\t\tbestIndex = queryScoreIndex;\n\t\t\t}\n\t\t});\n\t\tselectedEmbeddings.push(embeddingList[bestIndex]);\n\t\tselectedEmbeddingsIndexes.push(bestIndex);\n\t}\n\treturn selectedEmbeddingsIndexes;\n}\n/**\n* Finds the index of the maximum value in the given array.\n* @param {number[]} array - The input array.\n*\n* @returns {number} The index of the maximum value in the array. If the array is empty, returns -1.\n*/\nfunction argMax(array) {\n\tif (array.length === 0) return {\n\t\tmaxIndex: -1,\n\t\tmaxValue: NaN\n\t};\n\tlet maxValue = array[0];\n\tlet maxIndex = 0;\n\tfor (let i = 1; i < array.length; i += 1) if (array[i] > maxValue) {\n\t\tmaxIndex = i;\n\t\tmaxValue = array[i];\n\t}\n\treturn {\n\t\tmaxIndex,\n\t\tmaxValue\n\t};\n}\nfunction matrixMaxVal(arrays) {\n\treturn arrays.reduce((acc, array) => Math.max(acc, argMax(array).maxValue), 0);\n}\n\n//#endregion\nexport { cosineSimilarity, euclideanDistance, innerProduct$1 as innerProduct, math_exports, matrixFunc, maximalMarginalRelevance, normalize };\n//# sourceMappingURL=math.js.map","import { AIMessage, AIMessageChunk } from \"../../messages/ai.js\";\nimport { ChatGenerationChunk } from \"../../outputs.js\";\nimport { toJsonSchema } from \"../json_schema.js\";\nimport { RunnableLambda } from \"../../runnables/base.js\";\nimport \"../../messages/index.js\";\nimport { BaseChatModel } from \"../../language_models/chat_models.js\";\n\n//#region src/utils/testing/chat_models.ts\nvar FakeChatModel = class extends BaseChatModel {\n\t_combineLLMOutput() {\n\t\treturn [];\n\t}\n\t_llmType() {\n\t\treturn \"fake\";\n\t}\n\tasync _generate(messages, options, runManager) {\n\t\tif (options?.stop?.length) return { generations: [{\n\t\t\tmessage: new AIMessage(options.stop[0]),\n\t\t\ttext: options.stop[0]\n\t\t}] };\n\t\tconst text = messages.map((m) => {\n\t\t\tif (typeof m.content === \"string\") return m.content;\n\t\t\treturn JSON.stringify(m.content, null, 2);\n\t\t}).join(\"\\n\");\n\t\tawait runManager?.handleLLMNewToken(text);\n\t\treturn {\n\t\t\tgenerations: [{\n\t\t\t\tmessage: new AIMessage(text),\n\t\t\t\ttext\n\t\t\t}],\n\t\t\tllmOutput: {}\n\t\t};\n\t}\n};\nvar FakeStreamingChatModel = class FakeStreamingChatModel extends BaseChatModel {\n\tsleep = 50;\n\tresponses = [];\n\tchunks = [];\n\ttoolStyle = \"openai\";\n\tthrownErrorString;\n\ttools = [];\n\tconstructor({ sleep = 50, responses = [], chunks = [], toolStyle = \"openai\", thrownErrorString,...rest }) {\n\t\tsuper(rest);\n\t\tthis.sleep = sleep;\n\t\tthis.responses = responses;\n\t\tthis.chunks = chunks;\n\t\tthis.toolStyle = toolStyle;\n\t\tthis.thrownErrorString = thrownErrorString;\n\t}\n\t_llmType() {\n\t\treturn \"fake\";\n\t}\n\tbindTools(tools) {\n\t\tconst merged = [...this.tools, ...tools];\n\t\tconst toolDicts = merged.map((t) => {\n\t\t\tswitch (this.toolStyle) {\n\t\t\t\tcase \"openai\": return {\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\tdescription: t.description,\n\t\t\t\t\t\tparameters: toJsonSchema(t.schema)\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tcase \"anthropic\": return {\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinput_schema: toJsonSchema(t.schema)\n\t\t\t\t};\n\t\t\t\tcase \"bedrock\": return { toolSpec: {\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinputSchema: toJsonSchema(t.schema)\n\t\t\t\t} };\n\t\t\t\tcase \"google\": return {\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tparameters: toJsonSchema(t.schema)\n\t\t\t\t};\n\t\t\t\tdefault: throw new Error(`Unsupported tool style: ${this.toolStyle}`);\n\t\t\t}\n\t\t});\n\t\tconst wrapped = this.toolStyle === \"google\" ? [{ functionDeclarations: toolDicts }] : toolDicts;\n\t\tconst next = new FakeStreamingChatModel({\n\t\t\tsleep: this.sleep,\n\t\t\tresponses: this.responses,\n\t\t\tchunks: this.chunks,\n\t\t\ttoolStyle: this.toolStyle,\n\t\t\tthrownErrorString: this.thrownErrorString\n\t\t});\n\t\tnext.tools = merged;\n\t\treturn next.withConfig({ tools: wrapped });\n\t}\n\tasync _generate(messages, _options, _runManager) {\n\t\tif (this.thrownErrorString) throw new Error(this.thrownErrorString);\n\t\tconst content = this.responses?.[0]?.content ?? messages[0].content ?? \"\";\n\t\tconst generation = { generations: [{\n\t\t\ttext: \"\",\n\t\t\tmessage: new AIMessage({\n\t\t\t\tcontent,\n\t\t\t\ttool_calls: this.chunks?.[0]?.tool_calls\n\t\t\t})\n\t\t}] };\n\t\treturn generation;\n\t}\n\tasync *_streamResponseChunks(_messages, _options, runManager) {\n\t\tif (this.thrownErrorString) throw new Error(this.thrownErrorString);\n\t\tif (this.chunks?.length) {\n\t\t\tfor (const msgChunk of this.chunks) {\n\t\t\t\tconst cg = new ChatGenerationChunk({\n\t\t\t\t\tmessage: new AIMessageChunk({\n\t\t\t\t\t\tcontent: msgChunk.content,\n\t\t\t\t\t\ttool_calls: msgChunk.tool_calls,\n\t\t\t\t\t\tadditional_kwargs: msgChunk.additional_kwargs ?? {}\n\t\t\t\t\t}),\n\t\t\t\t\ttext: msgChunk.content?.toString() ?? \"\"\n\t\t\t\t});\n\t\t\t\tyield cg;\n\t\t\t\tawait runManager?.handleLLMNewToken(msgChunk.content, void 0, void 0, void 0, void 0, { chunk: cg });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === \"string\" ? _messages[0].content : \"\");\n\t\tconst text = typeof fallback.content === \"string\" ? fallback.content : \"\";\n\t\tfor (const ch of text) {\n\t\t\tawait new Promise((r) => setTimeout(r, this.sleep));\n\t\t\tconst cg = new ChatGenerationChunk({\n\t\t\t\tmessage: new AIMessageChunk({ content: ch }),\n\t\t\t\ttext: ch\n\t\t\t});\n\t\t\tyield cg;\n\t\t\tawait runManager?.handleLLMNewToken(ch, void 0, void 0, void 0, void 0, { chunk: cg });\n\t\t}\n\t}\n};\n/**\n* A fake Chat Model that returns a predefined list of responses. It can be used\n* for testing purposes.\n* @example\n* ```typescript\n* const chat = new FakeListChatModel({\n* responses: [\"I'll callback later.\", \"You 'console' them!\"]\n* });\n*\n* const firstMessage = new HumanMessage(\"You want to hear a JavaScript joke?\");\n* const secondMessage = new HumanMessage(\"How do you cheer up a JavaScript developer?\");\n*\n* // Call the chat model with a message and log the response\n* const firstResponse = await chat.call([firstMessage]);\n* console.log({ firstResponse });\n*\n* const secondResponse = await chat.call([secondMessage]);\n* console.log({ secondResponse });\n* ```\n*/\nvar FakeListChatModel = class extends BaseChatModel {\n\tstatic lc_name() {\n\t\treturn \"FakeListChatModel\";\n\t}\n\tlc_serializable = true;\n\tresponses;\n\ti = 0;\n\tsleep;\n\temitCustomEvent = false;\n\tconstructor(params) {\n\t\tsuper(params);\n\t\tconst { responses, sleep, emitCustomEvent } = params;\n\t\tthis.responses = responses;\n\t\tthis.sleep = sleep;\n\t\tthis.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent;\n\t}\n\t_combineLLMOutput() {\n\t\treturn [];\n\t}\n\t_llmType() {\n\t\treturn \"fake-list\";\n\t}\n\tasync _generate(_messages, options, runManager) {\n\t\tawait this._sleepIfRequested();\n\t\tif (options?.thrownErrorString) throw new Error(options.thrownErrorString);\n\t\tif (this.emitCustomEvent) await runManager?.handleCustomEvent(\"some_test_event\", { someval: true });\n\t\tif (options?.stop?.length) return { generations: [this._formatGeneration(options.stop[0])] };\n\t\telse {\n\t\t\tconst response = this._currentResponse();\n\t\t\tthis._incrementResponse();\n\t\t\treturn {\n\t\t\t\tgenerations: [this._formatGeneration(response)],\n\t\t\t\tllmOutput: {}\n\t\t\t};\n\t\t}\n\t}\n\t_formatGeneration(text) {\n\t\treturn {\n\t\t\tmessage: new AIMessage(text),\n\t\t\ttext\n\t\t};\n\t}\n\tasync *_streamResponseChunks(_messages, options, runManager) {\n\t\tconst response = this._currentResponse();\n\t\tthis._incrementResponse();\n\t\tif (this.emitCustomEvent) await runManager?.handleCustomEvent(\"some_test_event\", { someval: true });\n\t\tfor await (const text of response) {\n\t\t\tawait this._sleepIfRequested();\n\t\t\tif (options?.thrownErrorString) throw new Error(options.thrownErrorString);\n\t\t\tconst chunk = this._createResponseChunk(text);\n\t\t\tyield chunk;\n\t\t\trunManager?.handleLLMNewToken(text);\n\t\t}\n\t}\n\tasync _sleepIfRequested() {\n\t\tif (this.sleep !== void 0) await this._sleep();\n\t}\n\tasync _sleep() {\n\t\treturn new Promise((resolve) => {\n\t\t\tsetTimeout(() => resolve(), this.sleep);\n\t\t});\n\t}\n\t_createResponseChunk(text) {\n\t\treturn new ChatGenerationChunk({\n\t\t\tmessage: new AIMessageChunk({ content: text }),\n\t\t\ttext\n\t\t});\n\t}\n\t_currentResponse() {\n\t\treturn this.responses[this.i];\n\t}\n\t_incrementResponse() {\n\t\tif (this.i < this.responses.length - 1) this.i += 1;\n\t\telse this.i = 0;\n\t}\n\twithStructuredOutput(_params, _config) {\n\t\treturn RunnableLambda.from(async (input) => {\n\t\t\tconst message = await this.invoke(input);\n\t\t\tif (message.tool_calls?.[0]?.args) return message.tool_calls[0].args;\n\t\t\tif (typeof message.content === \"string\") return JSON.parse(message.content);\n\t\t\tthrow new Error(\"No structured output found\");\n\t\t});\n\t}\n};\n\n//#endregion\nexport { FakeChatModel, FakeListChatModel, FakeStreamingChatModel };\n//# sourceMappingURL=chat_models.js.map","import { Embeddings } from \"../../embeddings.js\";\n\n//#region src/utils/testing/embeddings.ts\n/**\n* A class that provides synthetic embeddings by overriding the\n* embedDocuments and embedQuery methods to generate embeddings based on\n* the input documents. The embeddings are generated by converting each\n* document into chunks, calculating a numerical value for each chunk, and\n* returning an array of these values as the embedding.\n*/\nvar SyntheticEmbeddings = class extends Embeddings {\n\tvectorSize;\n\tconstructor(params) {\n\t\tsuper(params ?? {});\n\t\tthis.vectorSize = params?.vectorSize ?? 4;\n\t}\n\t/**\n\t* Generates synthetic embeddings for a list of documents.\n\t* @param documents List of documents to generate embeddings for.\n\t* @returns A promise that resolves with a list of synthetic embeddings for each document.\n\t*/\n\tasync embedDocuments(documents) {\n\t\treturn Promise.all(documents.map((doc) => this.embedQuery(doc)));\n\t}\n\t/**\n\t* Generates a synthetic embedding for a document. The document is\n\t* converted into chunks, a numerical value is calculated for each chunk,\n\t* and an array of these values is returned as the embedding.\n\t* @param document The document to generate an embedding for.\n\t* @returns A promise that resolves with a synthetic embedding for the document.\n\t*/\n\tasync embedQuery(document) {\n\t\tlet doc = document;\n\t\tdoc = doc.toLowerCase().replaceAll(/[^a-z ]/g, \"\");\n\t\tconst padMod = doc.length % this.vectorSize;\n\t\tconst padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod;\n\t\tconst padSize = doc.length + padGapSize;\n\t\tdoc = doc.padEnd(padSize, \" \");\n\t\tconst chunkSize = doc.length / this.vectorSize;\n\t\tconst docChunk = [];\n\t\tfor (let co = 0; co < doc.length; co += chunkSize) docChunk.push(doc.slice(co, co + chunkSize));\n\t\tconst ret = docChunk.map((s) => {\n\t\t\tlet sum = 0;\n\t\t\tfor (let co = 0; co < s.length; co += 1) sum += s === \" \" ? 0 : s.charCodeAt(co);\n\t\t\tconst ret$1 = sum % 26 / 26;\n\t\t\treturn ret$1;\n\t\t});\n\t\treturn ret;\n\t}\n};\n/**\n* A class that provides fake embeddings by overriding the embedDocuments\n* and embedQuery methods to return fixed values.\n*/\nvar FakeEmbeddings = class extends Embeddings {\n\tconstructor(params) {\n\t\tsuper(params ?? {});\n\t}\n\t/**\n\t* Generates fixed embeddings for a list of documents.\n\t* @param documents List of documents to generate embeddings for.\n\t* @returns A promise that resolves with a list of fixed embeddings for each document.\n\t*/\n\tembedDocuments(documents) {\n\t\treturn Promise.resolve(documents.map(() => [\n\t\t\t.1,\n\t\t\t.2,\n\t\t\t.3,\n\t\t\t.4\n\t\t]));\n\t}\n\t/**\n\t* Generates a fixed embedding for a query.\n\t* @param _ The query to generate an embedding for.\n\t* @returns A promise that resolves with a fixed embedding for the query.\n\t*/\n\tembedQuery(_) {\n\t\treturn Promise.resolve([\n\t\t\t.1,\n\t\t\t.2,\n\t\t\t.3,\n\t\t\t.4\n\t\t]);\n\t}\n};\n\n//#endregion\nexport { FakeEmbeddings, SyntheticEmbeddings };\n//# sourceMappingURL=embeddings.js.map","import { LLM } from \"../../language_models/llms.js\";\n\n//#region src/utils/testing/llms.ts\nvar FakeLLM = class extends LLM {\n\tresponse;\n\tthrownErrorString;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.response = fields.response;\n\t\tthis.thrownErrorString = fields.thrownErrorString;\n\t}\n\t_llmType() {\n\t\treturn \"fake\";\n\t}\n\tasync _call(prompt, _options, runManager) {\n\t\tif (this.thrownErrorString) throw new Error(this.thrownErrorString);\n\t\tconst response = this.response ?? prompt;\n\t\tawait runManager?.handleLLMNewToken(response);\n\t\treturn response;\n\t}\n};\nvar FakeStreamingLLM = class extends LLM {\n\tsleep = 50;\n\tresponses;\n\tthrownErrorString;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.sleep = fields.sleep ?? this.sleep;\n\t\tthis.responses = fields.responses;\n\t\tthis.thrownErrorString = fields.thrownErrorString;\n\t}\n\t_llmType() {\n\t\treturn \"fake\";\n\t}\n\tasync _call(prompt) {\n\t\tif (this.thrownErrorString) throw new Error(this.thrownErrorString);\n\t\tconst response = this.responses?.[0];\n\t\tthis.responses = this.responses?.slice(1);\n\t\treturn response ?? prompt;\n\t}\n\tasync *_streamResponseChunks(input, _options, runManager) {\n\t\tif (this.thrownErrorString) throw new Error(this.thrownErrorString);\n\t\tconst response = this.responses?.[0];\n\t\tthis.responses = this.responses?.slice(1);\n\t\tfor (const c of response ?? input) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, this.sleep));\n\t\t\tyield {\n\t\t\t\ttext: c,\n\t\t\t\tgenerationInfo: {}\n\t\t\t};\n\t\t\tawait runManager?.handleLLMNewToken(c);\n\t\t}\n\t}\n};\n\n//#endregion\nexport { FakeLLM, FakeStreamingLLM };\n//# sourceMappingURL=llms.js.map","import { AIMessage } from \"../../messages/ai.js\";\nimport { HumanMessage } from \"../../messages/human.js\";\nimport { BaseTracer } from \"../../tracers/base.js\";\nimport \"../../messages/index.js\";\nimport { BaseChatMessageHistory, BaseListChatMessageHistory } from \"../../chat_history.js\";\n\n//#region src/utils/testing/message_history.ts\nvar FakeChatMessageHistory = class extends BaseChatMessageHistory {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"message\",\n\t\t\"fake\"\n\t];\n\tmessages = [];\n\tconstructor() {\n\t\tsuper();\n\t}\n\tasync getMessages() {\n\t\treturn this.messages;\n\t}\n\tasync addMessage(message) {\n\t\tthis.messages.push(message);\n\t}\n\tasync addUserMessage(message) {\n\t\tthis.messages.push(new HumanMessage(message));\n\t}\n\tasync addAIMessage(message) {\n\t\tthis.messages.push(new AIMessage(message));\n\t}\n\tasync clear() {\n\t\tthis.messages = [];\n\t}\n};\nvar FakeListChatMessageHistory = class extends BaseListChatMessageHistory {\n\tlc_namespace = [\n\t\t\"langchain_core\",\n\t\t\"message\",\n\t\t\"fake\"\n\t];\n\tmessages = [];\n\tconstructor() {\n\t\tsuper();\n\t}\n\tasync addMessage(message) {\n\t\tthis.messages.push(message);\n\t}\n\tasync getMessages() {\n\t\treturn this.messages;\n\t}\n};\nvar FakeTracer = class extends BaseTracer {\n\tname = \"fake_tracer\";\n\truns = [];\n\tconstructor() {\n\t\tsuper();\n\t}\n\tpersistRun(run) {\n\t\tthis.runs.push(run);\n\t\treturn Promise.resolve();\n\t}\n};\n\n//#endregion\nexport { FakeChatMessageHistory, FakeListChatMessageHistory, FakeTracer };\n//# sourceMappingURL=message_history.js.map","import { BaseOutputParser } from \"../../output_parsers/base.js\";\n\n//#region src/utils/testing/output_parsers.ts\n/**\n* Parser for comma-separated values. It splits the input text by commas\n* and trims the resulting values.\n*/\nvar FakeSplitIntoListParser = class extends BaseOutputParser {\n\tlc_namespace = [\"tests\", \"fake\"];\n\tgetFormatInstructions() {\n\t\treturn \"\";\n\t}\n\tasync parse(text) {\n\t\treturn text.split(\",\").map((value) => value.trim());\n\t}\n};\n\n//#endregion\nexport { FakeSplitIntoListParser };\n//# sourceMappingURL=output_parsers.js.map","import { BaseRetriever } from \"../../retrievers/index.js\";\nimport { Document } from \"../../documents/document.js\";\n\n//#region src/utils/testing/retrievers.ts\nvar FakeRetriever = class extends BaseRetriever {\n\tlc_namespace = [\"test\", \"fake\"];\n\toutput = [new Document({ pageContent: \"foo\" }), new Document({ pageContent: \"bar\" })];\n\tconstructor(fields) {\n\t\tsuper();\n\t\tthis.output = fields?.output ?? this.output;\n\t}\n\tasync _getRelevantDocuments(_query) {\n\t\treturn this.output;\n\t}\n};\n\n//#endregion\nexport { FakeRetriever };\n//# sourceMappingURL=retrievers.js.map","import { Runnable } from \"../../runnables/base.js\";\n\n//#region src/utils/testing/runnables.ts\nvar FakeRunnable = class extends Runnable {\n\tlc_namespace = [\"tests\", \"fake\"];\n\treturnOptions;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.returnOptions = fields.returnOptions;\n\t}\n\tasync invoke(input, options) {\n\t\tif (this.returnOptions) return options ?? {};\n\t\treturn { input };\n\t}\n};\n\n//#endregion\nexport { FakeRunnable };\n//# sourceMappingURL=runnables.js.map","import { StructuredTool } from \"../../tools/index.js\";\n\n//#region src/utils/testing/tools.ts\nvar FakeTool = class extends StructuredTool {\n\tname;\n\tdescription;\n\tschema;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.name = fields.name;\n\t\tthis.description = fields.description;\n\t\tthis.schema = fields.schema;\n\t}\n\tasync _call(arg, _runManager) {\n\t\treturn JSON.stringify(arg);\n\t}\n};\n\n//#endregion\nexport { FakeTool };\n//# sourceMappingURL=tools.js.map","import { BaseTracer } from \"../../tracers/base.js\";\n\n//#region src/utils/testing/tracers.ts\nvar SingleRunExtractor = class extends BaseTracer {\n\trunPromiseResolver;\n\trunPromise;\n\t/** The name of the callback handler. */\n\tname = \"single_run_extractor\";\n\tconstructor() {\n\t\tsuper();\n\t\tthis.runPromise = new Promise((extract) => {\n\t\t\tthis.runPromiseResolver = extract;\n\t\t});\n\t}\n\tasync persistRun(run) {\n\t\tthis.runPromiseResolver(run);\n\t}\n\tasync extract() {\n\t\treturn this.runPromise;\n\t}\n};\n\n//#endregion\nexport { SingleRunExtractor };\n//# sourceMappingURL=tracers.js.map","import { VectorStore } from \"../../vectorstores.js\";\nimport { Document } from \"../../documents/document.js\";\nimport { cosine } from \"../ml-distance/similarities.js\";\n\n//#region src/utils/testing/vectorstores.ts\n/**\n* Class that extends `VectorStore` to store vectors in memory. Provides\n* methods for adding documents, performing similarity searches, and\n* creating instances from texts, documents, or an existing index.\n*/\nvar FakeVectorStore = class FakeVectorStore extends VectorStore {\n\tmemoryVectors = [];\n\tsimilarity;\n\t_vectorstoreType() {\n\t\treturn \"memory\";\n\t}\n\tconstructor(embeddings, { similarity,...rest } = {}) {\n\t\tsuper(embeddings, rest);\n\t\tthis.similarity = similarity ?? cosine;\n\t}\n\t/**\n\t* Method to add documents to the memory vector store. It extracts the\n\t* text from each document, generates embeddings for them, and adds the\n\t* resulting vectors to the store.\n\t* @param documents Array of `Document` instances to be added to the store.\n\t* @returns Promise that resolves when all documents have been added.\n\t*/\n\tasync addDocuments(documents) {\n\t\tconst texts = documents.map(({ pageContent }) => pageContent);\n\t\treturn this.addVectors(await this.embeddings.embedDocuments(texts), documents);\n\t}\n\t/**\n\t* Method to add vectors to the memory vector store. It creates\n\t* `MemoryVector` instances for each vector and document pair and adds\n\t* them to the store.\n\t* @param vectors Array of vectors to be added to the store.\n\t* @param documents Array of `Document` instances corresponding to the vectors.\n\t* @returns Promise that resolves when all vectors have been added.\n\t*/\n\tasync addVectors(vectors, documents) {\n\t\tconst memoryVectors = vectors.map((embedding, idx) => ({\n\t\t\tcontent: documents[idx].pageContent,\n\t\t\tembedding,\n\t\t\tmetadata: documents[idx].metadata\n\t\t}));\n\t\tthis.memoryVectors = this.memoryVectors.concat(memoryVectors);\n\t}\n\t/**\n\t* Method to perform a similarity search in the memory vector store. It\n\t* calculates the similarity between the query vector and each vector in\n\t* the store, sorts the results by similarity, and returns the top `k`\n\t* results along with their scores.\n\t* @param query Query vector to compare against the vectors in the store.\n\t* @param k Number of top results to return.\n\t* @param filter Optional filter function to apply to the vectors before performing the search.\n\t* @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.\n\t*/\n\tasync similaritySearchVectorWithScore(query, k, filter) {\n\t\tconst filterFunction = (memoryVector) => {\n\t\t\tif (!filter) return true;\n\t\t\tconst doc = new Document({\n\t\t\t\tmetadata: memoryVector.metadata,\n\t\t\t\tpageContent: memoryVector.content\n\t\t\t});\n\t\t\treturn filter(doc);\n\t\t};\n\t\tconst filteredMemoryVectors = this.memoryVectors.filter(filterFunction);\n\t\tconst searches = filteredMemoryVectors.map((vector, index) => ({\n\t\t\tsimilarity: this.similarity(query, vector.embedding),\n\t\t\tindex\n\t\t})).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k);\n\t\tconst result = searches.map((search) => [new Document({\n\t\t\tmetadata: filteredMemoryVectors[search.index].metadata,\n\t\t\tpageContent: filteredMemoryVectors[search.index].content\n\t\t}), search.similarity]);\n\t\treturn result;\n\t}\n\t/**\n\t* Static method to create a `FakeVectorStore` instance from an array of\n\t* texts. It creates a `Document` for each text and metadata pair, and\n\t* adds them to the store.\n\t* @param texts Array of texts to be added to the store.\n\t* @param metadatas Array or single object of metadata corresponding to the texts.\n\t* @param embeddings `Embeddings` instance used to generate embeddings for the texts.\n\t* @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.\n\t* @returns Promise that resolves with a new `FakeVectorStore` instance.\n\t*/\n\tstatic async fromTexts(texts, metadatas, embeddings, dbConfig) {\n\t\tconst docs = [];\n\t\tfor (let i = 0; i < texts.length; i += 1) {\n\t\t\tconst metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;\n\t\t\tconst newDoc = new Document({\n\t\t\t\tpageContent: texts[i],\n\t\t\t\tmetadata\n\t\t\t});\n\t\t\tdocs.push(newDoc);\n\t\t}\n\t\treturn FakeVectorStore.fromDocuments(docs, embeddings, dbConfig);\n\t}\n\t/**\n\t* Static method to create a `FakeVectorStore` instance from an array of\n\t* `Document` instances. It adds the documents to the store.\n\t* @param docs Array of `Document` instances to be added to the store.\n\t* @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n\t* @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.\n\t* @returns Promise that resolves with a new `FakeVectorStore` instance.\n\t*/\n\tstatic async fromDocuments(docs, embeddings, dbConfig) {\n\t\tconst instance = new this(embeddings, dbConfig);\n\t\tawait instance.addDocuments(docs);\n\t\treturn instance;\n\t}\n\t/**\n\t* Static method to create a `FakeVectorStore` instance from an existing\n\t* index. It creates a new `FakeVectorStore` instance without adding any\n\t* documents or vectors.\n\t* @param embeddings `Embeddings` instance used to generate embeddings for the documents.\n\t* @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.\n\t* @returns Promise that resolves with a new `FakeVectorStore` instance.\n\t*/\n\tstatic async fromExistingIndex(embeddings, dbConfig) {\n\t\tconst instance = new this(embeddings, dbConfig);\n\t\treturn instance;\n\t}\n};\n\n//#endregion\nexport { FakeVectorStore };\n//# sourceMappingURL=vectorstores.js.map","import { __export } from \"../../_virtual/rolldown_runtime.js\";\nimport { FakeChatModel, FakeListChatModel, FakeStreamingChatModel } from \"./chat_models.js\";\nimport { FakeEmbeddings, SyntheticEmbeddings } from \"./embeddings.js\";\nimport { FakeLLM, FakeStreamingLLM } from \"./llms.js\";\nimport { FakeChatMessageHistory, FakeListChatMessageHistory, FakeTracer } from \"./message_history.js\";\nimport { FakeSplitIntoListParser } from \"./output_parsers.js\";\nimport { FakeRetriever } from \"./retrievers.js\";\nimport { FakeRunnable } from \"./runnables.js\";\nimport { FakeTool } from \"./tools.js\";\nimport { SingleRunExtractor } from \"./tracers.js\";\nimport { FakeVectorStore } from \"./vectorstores.js\";\n\n//#region src/utils/testing/index.ts\nvar testing_exports = {};\n__export(testing_exports, {\n\tFakeChatMessageHistory: () => FakeChatMessageHistory,\n\tFakeChatModel: () => FakeChatModel,\n\tFakeEmbeddings: () => FakeEmbeddings,\n\tFakeLLM: () => FakeLLM,\n\tFakeListChatMessageHistory: () => FakeListChatMessageHistory,\n\tFakeListChatModel: () => FakeListChatModel,\n\tFakeRetriever: () => FakeRetriever,\n\tFakeRunnable: () => FakeRunnable,\n\tFakeSplitIntoListParser: () => FakeSplitIntoListParser,\n\tFakeStreamingChatModel: () => FakeStreamingChatModel,\n\tFakeStreamingLLM: () => FakeStreamingLLM,\n\tFakeTool: () => FakeTool,\n\tFakeTracer: () => FakeTracer,\n\tFakeVectorStore: () => FakeVectorStore,\n\tSingleRunExtractor: () => SingleRunExtractor,\n\tSyntheticEmbeddings: () => SyntheticEmbeddings\n});\n\n//#endregion\nexport { FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingLLM, FakeTool, FakeTracer, FakeVectorStore, SingleRunExtractor, SyntheticEmbeddings, testing_exports };\n//# sourceMappingURL=index.js.map","import { __export } from \"../../_virtual/rolldown_runtime.js\";\nimport { extendInteropZodObject, getInteropZodDefaultGetter, getInteropZodObjectShape, getSchemaDescription, interopParse, interopParseAsync, interopSafeParse, interopSafeParseAsync, interopZodObjectMakeFieldsOptional, interopZodObjectPartial, interopZodObjectPassthrough, interopZodObjectStrict, interopZodTransformInputSchema, isInteropZodLiteral, isInteropZodObject, isInteropZodSchema, isShapelessZodSchema, isSimpleStringZodSchema, isZodArrayV4, isZodLiteralV3, isZodLiteralV4, isZodObjectV3, isZodObjectV4, isZodSchema, isZodSchemaV3, isZodSchemaV4 } from \"./zod.js\";\n\n//#region src/utils/types/index.ts\nvar types_exports = {};\n__export(types_exports, {\n\textendInteropZodObject: () => extendInteropZodObject,\n\tgetInteropZodDefaultGetter: () => getInteropZodDefaultGetter,\n\tgetInteropZodObjectShape: () => getInteropZodObjectShape,\n\tgetSchemaDescription: () => getSchemaDescription,\n\tinteropParse: () => interopParse,\n\tinteropParseAsync: () => interopParseAsync,\n\tinteropSafeParse: () => interopSafeParse,\n\tinteropSafeParseAsync: () => interopSafeParseAsync,\n\tinteropZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional,\n\tinteropZodObjectPartial: () => interopZodObjectPartial,\n\tinteropZodObjectPassthrough: () => interopZodObjectPassthrough,\n\tinteropZodObjectStrict: () => interopZodObjectStrict,\n\tinteropZodTransformInputSchema: () => interopZodTransformInputSchema,\n\tisInteropZodLiteral: () => isInteropZodLiteral,\n\tisInteropZodObject: () => isInteropZodObject,\n\tisInteropZodSchema: () => isInteropZodSchema,\n\tisShapelessZodSchema: () => isShapelessZodSchema,\n\tisSimpleStringZodSchema: () => isSimpleStringZodSchema,\n\tisZodArrayV4: () => isZodArrayV4,\n\tisZodLiteralV3: () => isZodLiteralV3,\n\tisZodLiteralV4: () => isZodLiteralV4,\n\tisZodObjectV3: () => isZodObjectV3,\n\tisZodObjectV4: () => isZodObjectV4,\n\tisZodSchema: () => isZodSchema,\n\tisZodSchemaV3: () => isZodSchemaV3,\n\tisZodSchemaV4: () => isZodSchemaV4\n});\n\n//#endregion\nexport { extendInteropZodObject, getInteropZodDefaultGetter, getInteropZodObjectShape, getSchemaDescription, interopParse, interopParseAsync, interopSafeParse, interopSafeParseAsync, interopZodObjectMakeFieldsOptional, interopZodObjectPartial, interopZodObjectPassthrough, interopZodObjectStrict, interopZodTransformInputSchema, isInteropZodLiteral, isInteropZodObject, isInteropZodSchema, isShapelessZodSchema, isSimpleStringZodSchema, isZodArrayV4, isZodLiteralV3, isZodLiteralV4, isZodObjectV3, isZodObjectV4, isZodSchema, isZodSchemaV3, isZodSchemaV4, types_exports };\n//# sourceMappingURL=index.js.map","import { __export } from \"../_virtual/rolldown_runtime.js\";\nimport { agents_exports } from \"../agents.js\";\nimport { serializable_exports } from \"./serializable.js\";\nimport { tool_exports } from \"../messages/tool.js\";\nimport { env_exports } from \"../utils/env.js\";\nimport { base_exports } from \"../callbacks/base.js\";\nimport { base_exports as base_exports$1 } from \"../tracers/base.js\";\nimport { console_exports } from \"../tracers/console.js\";\nimport { tracer_langchain_exports } from \"../tracers/tracer_langchain.js\";\nimport { promises_exports } from \"../callbacks/promises.js\";\nimport { manager_exports } from \"../callbacks/manager.js\";\nimport { singletons_exports } from \"../singletons/index.js\";\nimport { stream_exports } from \"../utils/stream.js\";\nimport { log_stream_exports } from \"../tracers/log_stream.js\";\nimport { outputs_exports } from \"../outputs.js\";\nimport { async_caller_exports } from \"../utils/async_caller.js\";\nimport { json_schema_exports } from \"../utils/json_schema.js\";\nimport { graph_exports } from \"../runnables/graph.js\";\nimport { messages_exports } from \"../messages/index.js\";\nimport { chat_history_exports } from \"../chat_history.js\";\nimport { embeddings_exports } from \"../embeddings.js\";\nimport { src_exports } from \"../index.js\";\nimport { memory_exports } from \"../memory.js\";\nimport { prompt_values_exports } from \"../prompt_values.js\";\nimport { stores_exports } from \"../stores.js\";\nimport { retrievers_exports } from \"../retrievers/index.js\";\nimport { vectorstores_exports } from \"../vectorstores.js\";\nimport { hash_exports } from \"../utils/hash.js\";\nimport { base_exports as base_exports$2 } from \"../caches/base.js\";\nimport { base_exports as base_exports$3 } from \"../document_loaders/base.js\";\nimport { langsmith_exports } from \"../document_loaders/langsmith.js\";\nimport { documents_exports } from \"../documents/index.js\";\nimport { example_selectors_exports } from \"../example_selectors/index.js\";\nimport { indexing_exports } from \"../indexing/index.js\";\nimport { tiktoken_exports } from \"../utils/tiktoken.js\";\nimport { base_exports as base_exports$4 } from \"../language_models/base.js\";\nimport { chat_models_exports } from \"../language_models/chat_models.js\";\nimport { llms_exports } from \"../language_models/llms.js\";\nimport { runnables_exports } from \"../runnables/index.js\";\nimport { json_patch_exports } from \"../utils/json_patch.js\";\nimport { output_parsers_exports } from \"../output_parsers/index.js\";\nimport { openai_tools_exports } from \"../output_parsers/openai_tools/index.js\";\nimport { openai_functions_exports } from \"../output_parsers/openai_functions/index.js\";\nimport { prompts_exports } from \"../prompts/index.js\";\nimport { base_exports as base_exports$5 } from \"../retrievers/document_compressors/base.js\";\nimport { structured_query_exports } from \"../structured_query/index.js\";\nimport { tools_exports } from \"../tools/index.js\";\nimport { run_collector_exports } from \"../tracers/run_collector.js\";\nimport { stream_exports as stream_exports$1 } from \"../types/stream.js\";\nimport { chunk_array_exports } from \"../utils/chunk_array.js\";\nimport { event_source_parse_exports } from \"../utils/event_source_parse.js\";\nimport { function_calling_exports } from \"../utils/function_calling.js\";\nimport { math_exports } from \"../utils/math.js\";\nimport { testing_exports } from \"../utils/testing/index.js\";\nimport { types_exports } from \"../utils/types/index.js\";\n\n//#region src/load/import_map.ts\nvar import_map_exports = {};\n__export(import_map_exports, {\n\tagents: () => agents_exports,\n\tcaches: () => base_exports$2,\n\tcallbacks__base: () => base_exports,\n\tcallbacks__manager: () => manager_exports,\n\tcallbacks__promises: () => promises_exports,\n\tchat_history: () => chat_history_exports,\n\tdocument_loaders__base: () => base_exports$3,\n\tdocument_loaders__langsmith: () => langsmith_exports,\n\tdocuments: () => documents_exports,\n\tembeddings: () => embeddings_exports,\n\texample_selectors: () => example_selectors_exports,\n\tindex: () => src_exports,\n\tindexing: () => indexing_exports,\n\tlanguage_models__base: () => base_exports$4,\n\tlanguage_models__chat_models: () => chat_models_exports,\n\tlanguage_models__llms: () => llms_exports,\n\tload__serializable: () => serializable_exports,\n\tmemory: () => memory_exports,\n\tmessages: () => messages_exports,\n\tmessages__tool: () => tool_exports,\n\toutput_parsers: () => output_parsers_exports,\n\toutput_parsers__openai_functions: () => openai_functions_exports,\n\toutput_parsers__openai_tools: () => openai_tools_exports,\n\toutputs: () => outputs_exports,\n\tprompt_values: () => prompt_values_exports,\n\tprompts: () => prompts_exports,\n\tretrievers: () => retrievers_exports,\n\tretrievers__document_compressors: () => base_exports$5,\n\trunnables: () => runnables_exports,\n\trunnables__graph: () => graph_exports,\n\tsingletons: () => singletons_exports,\n\tstores: () => stores_exports,\n\tstructured_query: () => structured_query_exports,\n\ttools: () => tools_exports,\n\ttracers__base: () => base_exports$1,\n\ttracers__console: () => console_exports,\n\ttracers__log_stream: () => log_stream_exports,\n\ttracers__run_collector: () => run_collector_exports,\n\ttracers__tracer_langchain: () => tracer_langchain_exports,\n\ttypes__stream: () => stream_exports$1,\n\tutils__async_caller: () => async_caller_exports,\n\tutils__chunk_array: () => chunk_array_exports,\n\tutils__env: () => env_exports,\n\tutils__event_source_parse: () => event_source_parse_exports,\n\tutils__function_calling: () => function_calling_exports,\n\tutils__hash: () => hash_exports,\n\tutils__json_patch: () => json_patch_exports,\n\tutils__json_schema: () => json_schema_exports,\n\tutils__math: () => math_exports,\n\tutils__stream: () => stream_exports,\n\tutils__testing: () => testing_exports,\n\tutils__tiktoken: () => tiktoken_exports,\n\tutils__types: () => types_exports,\n\tvectorstores: () => vectorstores_exports\n});\n\n//#endregion\nexport { import_map_exports };\n//# sourceMappingURL=import_map.js.map","import { keyFromJson, mapKeys } from \"./map_keys.js\";\nimport { get_lc_unique_name } from \"./serializable.js\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\nimport { optionalImportEntrypoints } from \"./import_constants.js\";\nimport { import_map_exports } from \"./import_map.js\";\n\n//#region src/load/index.ts\nfunction combineAliasesAndInvert(constructor) {\n\tconst aliases = {};\n\tfor (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, \"lc_aliases\"));\n\treturn Object.entries(aliases).reduce((acc, [key, value]) => {\n\t\tacc[value] = key;\n\t\treturn acc;\n\t}, {});\n}\nasync function reviver(value) {\n\tconst { optionalImportsMap = {}, optionalImportEntrypoints: optionalImportEntrypoints$1 = [], importMap = {}, secretsMap = {}, path = [\"$\"] } = this;\n\tconst pathStr = path.join(\".\");\n\tif (typeof value === \"object\" && value !== null && !Array.isArray(value) && \"lc\" in value && \"type\" in value && \"id\" in value && value.lc === 1 && value.type === \"secret\") {\n\t\tconst serialized = value;\n\t\tconst [key] = serialized.id;\n\t\tif (key in secretsMap) return secretsMap[key];\n\t\telse {\n\t\t\tconst secretValueInEnv = getEnvironmentVariable(key);\n\t\t\tif (secretValueInEnv) return secretValueInEnv;\n\t\t\telse throw new Error(`Missing key \"${key}\" for ${pathStr} in load(secretsMap={})`);\n\t\t}\n\t} else if (typeof value === \"object\" && value !== null && !Array.isArray(value) && \"lc\" in value && \"type\" in value && \"id\" in value && value.lc === 1 && value.type === \"not_implemented\") {\n\t\tconst serialized = value;\n\t\tconst str = JSON.stringify(serialized);\n\t\tthrow new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`);\n\t} else if (typeof value === \"object\" && value !== null && !Array.isArray(value) && \"lc\" in value && \"type\" in value && \"id\" in value && \"kwargs\" in value && value.lc === 1) {\n\t\tconst serialized = value;\n\t\tconst str = JSON.stringify(serialized);\n\t\tconst [name, ...namespaceReverse] = serialized.id.slice().reverse();\n\t\tconst namespace = namespaceReverse.reverse();\n\t\tconst importMaps = {\n\t\t\tlangchain_core: import_map_exports,\n\t\t\tlangchain: importMap\n\t\t};\n\t\tlet module = null;\n\t\tconst optionalImportNamespaceAliases = [namespace.join(\"/\")];\n\t\tif (namespace[0] === \"langchain_community\") optionalImportNamespaceAliases.push([\"langchain\", ...namespace.slice(1)].join(\"/\"));\n\t\tconst matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap);\n\t\tif (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join(\"/\")) || matchingNamespaceAlias) if (matchingNamespaceAlias !== void 0) module = await optionalImportsMap[matchingNamespaceAlias];\n\t\telse throw new Error(`Missing key \"${namespace.join(\"/\")}\" for ${pathStr} in load(optionalImportsMap={})`);\n\t\telse {\n\t\t\tlet finalImportMap;\n\t\t\tif (namespace[0] === \"langchain\" || namespace[0] === \"langchain_core\") {\n\t\t\t\tfinalImportMap = importMaps[namespace[0]];\n\t\t\t\tnamespace.shift();\n\t\t\t} else throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n\t\t\tif (namespace.length === 0) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n\t\t\tlet importMapKey;\n\t\t\tdo {\n\t\t\t\timportMapKey = namespace.join(\"__\");\n\t\t\t\tif (importMapKey in finalImportMap) break;\n\t\t\t\telse namespace.pop();\n\t\t\t} while (namespace.length > 0);\n\t\t\tif (importMapKey in finalImportMap) module = finalImportMap[importMapKey];\n\t\t}\n\t\tif (typeof module !== \"object\" || module === null) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n\t\tconst builder = module[name] ?? Object.values(module).find((v) => typeof v === \"function\" && get_lc_unique_name(v) === name);\n\t\tif (typeof builder !== \"function\") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`);\n\t\tconst kwargs = await reviver.call({\n\t\t\t...this,\n\t\t\tpath: [...path, \"kwargs\"]\n\t\t}, serialized.kwargs);\n\t\tif (serialized.type === \"constructor\") {\n\t\t\tconst instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder)));\n\t\t\tObject.defineProperty(instance.constructor, \"name\", { value: name });\n\t\t\treturn instance;\n\t\t} else throw new Error(`Invalid type: ${pathStr} -> ${str}`);\n\t} else if (typeof value === \"object\" && value !== null) if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({\n\t\t...this,\n\t\tpath: [...path, `${i}`]\n\t}, v)));\n\telse return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, value$1]) => [key, await reviver.call({\n\t\t...this,\n\t\tpath: [...path, key]\n\t}, value$1)])));\n\treturn value;\n}\nasync function load(text, mappings) {\n\tconst json = JSON.parse(text);\n\treturn reviver.call({ ...mappings }, json);\n}\n\n//#endregion\nexport { load };\n//# sourceMappingURL=index.js.map","import { stringify } from \"./utils/fast-safe-stringify/index.js\";\nimport { load } from \"@langchain/core/load\";\n\n//#region src/serde/jsonplus.ts\nfunction isLangChainSerializedObject(value) {\n\treturn value !== null && value.lc === 1 && value.type === \"constructor\" && Array.isArray(value.id);\n}\n/**\n* The replacer in stringify does not allow delegation to built-in LangChain\n* serialization methods, and instead immediately calls `.toJSON()` and\n* continues to stringify subfields.\n*\n* We therefore must start from the most nested elements in the input and\n* deserialize upwards rather than top-down.\n*/\nasync function _reviver(value) {\n\tif (value && typeof value === \"object\") if (Array.isArray(value)) {\n\t\tconst revivedArray = await Promise.all(value.map((item) => _reviver(item)));\n\t\treturn revivedArray;\n\t} else {\n\t\tconst revivedObj = {};\n\t\tfor (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v);\n\t\tif (revivedObj.lc === 2 && revivedObj.type === \"undefined\") return void 0;\n\t\telse if (revivedObj.lc === 2 && revivedObj.type === \"constructor\" && Array.isArray(revivedObj.id)) try {\n\t\t\tconst constructorName = revivedObj.id[revivedObj.id.length - 1];\n\t\t\tlet constructor;\n\t\t\tswitch (constructorName) {\n\t\t\t\tcase \"Set\":\n\t\t\t\t\tconstructor = Set;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Map\":\n\t\t\t\t\tconstructor = Map;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"RegExp\":\n\t\t\t\t\tconstructor = RegExp;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Error\":\n\t\t\t\t\tconstructor = Error;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: return revivedObj;\n\t\t\t}\n\t\t\tif (revivedObj.method) return constructor[revivedObj.method](...revivedObj.args || []);\n\t\t\telse return new constructor(...revivedObj.args || []);\n\t\t} catch (error) {\n\t\t\treturn revivedObj;\n\t\t}\n\t\telse if (isLangChainSerializedObject(revivedObj)) return load(JSON.stringify(revivedObj));\n\t\treturn revivedObj;\n\t}\n\treturn value;\n}\nfunction _encodeConstructorArgs(constructor, method, args, kwargs) {\n\treturn {\n\t\tlc: 2,\n\t\ttype: \"constructor\",\n\t\tid: [constructor.name],\n\t\tmethod: method ?? null,\n\t\targs: args ?? [],\n\t\tkwargs: kwargs ?? {}\n\t};\n}\nfunction _default(obj) {\n\tif (obj === void 0) return {\n\t\tlc: 2,\n\t\ttype: \"undefined\"\n\t};\n\telse if (obj instanceof Set || obj instanceof Map) return _encodeConstructorArgs(obj.constructor, void 0, [Array.from(obj)]);\n\telse if (obj instanceof RegExp) return _encodeConstructorArgs(RegExp, void 0, [obj.source, obj.flags]);\n\telse if (obj instanceof Error) return _encodeConstructorArgs(obj.constructor, void 0, [obj.message]);\n\telse if (obj?.lg_name === \"Send\") return {\n\t\tnode: obj.node,\n\t\targs: obj.args\n\t};\n\telse return obj;\n}\nvar JsonPlusSerializer = class {\n\t_dumps(obj) {\n\t\tconst encoder = new TextEncoder();\n\t\treturn encoder.encode(stringify(obj, (_, value) => {\n\t\t\treturn _default(value);\n\t\t}));\n\t}\n\tasync dumpsTyped(obj) {\n\t\tif (obj instanceof Uint8Array) return [\"bytes\", obj];\n\t\telse return [\"json\", this._dumps(obj)];\n\t}\n\tasync _loads(data) {\n\t\tconst parsed = JSON.parse(data);\n\t\treturn _reviver(parsed);\n\t}\n\tasync loadsTyped(type, data) {\n\t\tif (type === \"bytes\") return typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n\t\telse if (type === \"json\") return this._loads(typeof data === \"string\" ? data : new TextDecoder().decode(data));\n\t\telse throw new Error(`Unknown serialization type: ${type}`);\n\t}\n};\n\n//#endregion\nexport { JsonPlusSerializer };\n//# sourceMappingURL=jsonplus.js.map","import { uuid6 } from \"./id.js\";\nimport { ERROR, INTERRUPT, RESUME, SCHEDULED } from \"./serde/types.js\";\nimport { JsonPlusSerializer } from \"./serde/jsonplus.js\";\n\n//#region src/base.ts\nfunction deepCopy(obj) {\n\tif (typeof obj !== \"object\" || obj === null) return obj;\n\tconst newObj = Array.isArray(obj) ? [] : {};\n\tfor (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]);\n\treturn newObj;\n}\n/** @hidden */\nfunction emptyCheckpoint() {\n\treturn {\n\t\tv: 4,\n\t\tid: uuid6(-2),\n\t\tts: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tchannel_values: {},\n\t\tchannel_versions: {},\n\t\tversions_seen: {}\n\t};\n}\n/** @hidden */\nfunction copyCheckpoint(checkpoint) {\n\treturn {\n\t\tv: checkpoint.v,\n\t\tid: checkpoint.id,\n\t\tts: checkpoint.ts,\n\t\tchannel_values: { ...checkpoint.channel_values },\n\t\tchannel_versions: { ...checkpoint.channel_versions },\n\t\tversions_seen: deepCopy(checkpoint.versions_seen)\n\t};\n}\nvar BaseCheckpointSaver = class {\n\tserde = new JsonPlusSerializer();\n\tconstructor(serde) {\n\t\tthis.serde = serde || this.serde;\n\t}\n\tasync get(config) {\n\t\tconst value = await this.getTuple(config);\n\t\treturn value ? value.checkpoint : void 0;\n\t}\n\t/**\n\t* Generate the next version ID for a channel.\n\t*\n\t* Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n\t* as long as they are monotonically increasing.\n\t*/\n\tgetNextVersion(current) {\n\t\tif (typeof current === \"string\") throw new Error(\"Please override this method to use string versions.\");\n\t\treturn current !== void 0 && typeof current === \"number\" ? current + 1 : 1;\n\t}\n};\nfunction compareChannelVersions(a, b) {\n\tif (typeof a === \"number\" && typeof b === \"number\") return Math.sign(a - b);\n\treturn String(a).localeCompare(String(b));\n}\nfunction maxChannelVersion(...versions) {\n\treturn versions.reduce((max, version, idx) => {\n\t\tif (idx === 0) return version;\n\t\treturn compareChannelVersions(max, version) >= 0 ? max : version;\n\t});\n}\n/**\n* Mapping from error type to error index.\n* Regular writes just map to their index in the list of writes being saved.\n* Special writes (e.g. errors) map to negative indices, to avoid those writes from\n* conflicting with regular writes.\n* Each Checkpointer implementation should use this mapping in put_writes.\n*/\nconst WRITES_IDX_MAP = {\n\t[ERROR]: -1,\n\t[SCHEDULED]: -2,\n\t[INTERRUPT]: -3,\n\t[RESUME]: -4\n};\nfunction getCheckpointId(config) {\n\treturn config.configurable?.checkpoint_id || config.configurable?.thread_ts || \"\";\n}\n\n//#endregion\nexport { BaseCheckpointSaver, WRITES_IDX_MAP, compareChannelVersions, copyCheckpoint, deepCopy, emptyCheckpoint, getCheckpointId, maxChannelVersion };\n//# sourceMappingURL=base.js.map","import { TASKS } from \"./serde/types.js\";\nimport { BaseCheckpointSaver, WRITES_IDX_MAP, copyCheckpoint, getCheckpointId, maxChannelVersion } from \"./base.js\";\n\n//#region src/memory.ts\nfunction _generateKey(threadId, checkpointNamespace, checkpointId) {\n\treturn JSON.stringify([\n\t\tthreadId,\n\t\tcheckpointNamespace,\n\t\tcheckpointId\n\t]);\n}\nfunction _parseKey(key) {\n\tconst [threadId, checkpointNamespace, checkpointId] = JSON.parse(key);\n\treturn {\n\t\tthreadId,\n\t\tcheckpointNamespace,\n\t\tcheckpointId\n\t};\n}\nvar MemorySaver = class extends BaseCheckpointSaver {\n\tstorage = {};\n\twrites = {};\n\tconstructor(serde) {\n\t\tsuper(serde);\n\t}\n\t/** @internal */\n\tasync _migratePendingSends(mutableCheckpoint, threadId, checkpointNs, parentCheckpointId) {\n\t\tconst deseriablizableCheckpoint = mutableCheckpoint;\n\t\tconst parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId);\n\t\tconst pendingSends = await Promise.all(Object.values(this.writes[parentKey] ?? {}).filter(([_taskId, channel]) => channel === TASKS).map(async ([_taskId, _channel, writes]) => await this.serde.loadsTyped(\"json\", writes)));\n\t\tdeseriablizableCheckpoint.channel_values ??= {};\n\t\tdeseriablizableCheckpoint.channel_values[TASKS] = pendingSends;\n\t\tdeseriablizableCheckpoint.channel_versions ??= {};\n\t\tdeseriablizableCheckpoint.channel_versions[TASKS] = Object.keys(deseriablizableCheckpoint.channel_versions).length > 0 ? maxChannelVersion(...Object.values(deseriablizableCheckpoint.channel_versions)) : this.getNextVersion(void 0);\n\t}\n\tasync getTuple(config) {\n\t\tconst thread_id = config.configurable?.thread_id;\n\t\tconst checkpoint_ns = config.configurable?.checkpoint_ns ?? \"\";\n\t\tlet checkpoint_id = getCheckpointId(config);\n\t\tif (checkpoint_id) {\n\t\t\tconst saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id];\n\t\t\tif (saved !== void 0) {\n\t\t\t\tconst [checkpoint, metadata, parentCheckpointId] = saved;\n\t\t\t\tconst key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n\t\t\t\tconst deserializedCheckpoint = await this.serde.loadsTyped(\"json\", checkpoint);\n\t\t\t\tif (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId);\n\t\t\t\tconst pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => {\n\t\t\t\t\treturn [\n\t\t\t\t\t\ttaskId,\n\t\t\t\t\t\tchannel,\n\t\t\t\t\t\tawait this.serde.loadsTyped(\"json\", value)\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tconst checkpointTuple = {\n\t\t\t\t\tconfig,\n\t\t\t\t\tcheckpoint: deserializedCheckpoint,\n\t\t\t\t\tmetadata: await this.serde.loadsTyped(\"json\", metadata),\n\t\t\t\t\tpendingWrites\n\t\t\t\t};\n\t\t\t\tif (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: {\n\t\t\t\t\tthread_id,\n\t\t\t\t\tcheckpoint_ns,\n\t\t\t\t\tcheckpoint_id: parentCheckpointId\n\t\t\t\t} };\n\t\t\t\treturn checkpointTuple;\n\t\t\t}\n\t\t} else {\n\t\t\tconst checkpoints = this.storage[thread_id]?.[checkpoint_ns];\n\t\t\tif (checkpoints !== void 0) {\n\t\t\t\tcheckpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0];\n\t\t\t\tconst saved = checkpoints[checkpoint_id];\n\t\t\t\tconst [checkpoint, metadata, parentCheckpointId] = saved;\n\t\t\t\tconst key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n\t\t\t\tconst deserializedCheckpoint = await this.serde.loadsTyped(\"json\", checkpoint);\n\t\t\t\tif (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId);\n\t\t\t\tconst pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => {\n\t\t\t\t\treturn [\n\t\t\t\t\t\ttaskId,\n\t\t\t\t\t\tchannel,\n\t\t\t\t\t\tawait this.serde.loadsTyped(\"json\", value)\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tconst checkpointTuple = {\n\t\t\t\t\tconfig: { configurable: {\n\t\t\t\t\t\tthread_id,\n\t\t\t\t\t\tcheckpoint_id,\n\t\t\t\t\t\tcheckpoint_ns\n\t\t\t\t\t} },\n\t\t\t\t\tcheckpoint: deserializedCheckpoint,\n\t\t\t\t\tmetadata: await this.serde.loadsTyped(\"json\", metadata),\n\t\t\t\t\tpendingWrites\n\t\t\t\t};\n\t\t\t\tif (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: {\n\t\t\t\t\tthread_id,\n\t\t\t\t\tcheckpoint_ns,\n\t\t\t\t\tcheckpoint_id: parentCheckpointId\n\t\t\t\t} };\n\t\t\t\treturn checkpointTuple;\n\t\t\t}\n\t\t}\n\t\treturn void 0;\n\t}\n\tasync *list(config, options) {\n\t\tlet { before, limit, filter } = options ?? {};\n\t\tconst threadIds = config.configurable?.thread_id ? [config.configurable?.thread_id] : Object.keys(this.storage);\n\t\tconst configCheckpointNamespace = config.configurable?.checkpoint_ns;\n\t\tconst configCheckpointId = config.configurable?.checkpoint_id;\n\t\tfor (const threadId of threadIds) for (const checkpointNamespace of Object.keys(this.storage[threadId] ?? {})) {\n\t\t\tif (configCheckpointNamespace !== void 0 && checkpointNamespace !== configCheckpointNamespace) continue;\n\t\t\tconst checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {};\n\t\t\tconst sortedCheckpoints = Object.entries(checkpoints).sort((a, b) => b[0].localeCompare(a[0]));\n\t\t\tfor (const [checkpointId, [checkpoint, metadataStr, parentCheckpointId]] of sortedCheckpoints) {\n\t\t\t\tif (configCheckpointId && checkpointId !== configCheckpointId) continue;\n\t\t\t\tif (before && before.configurable?.checkpoint_id && checkpointId >= before.configurable.checkpoint_id) continue;\n\t\t\t\tconst metadata = await this.serde.loadsTyped(\"json\", metadataStr);\n\t\t\t\tif (filter && !Object.entries(filter).every(([key$1, value]) => metadata[key$1] === value)) continue;\n\t\t\t\tif (limit !== void 0) {\n\t\t\t\t\tif (limit <= 0) break;\n\t\t\t\t\tlimit -= 1;\n\t\t\t\t}\n\t\t\t\tconst key = _generateKey(threadId, checkpointNamespace, checkpointId);\n\t\t\t\tconst writes = Object.values(this.writes[key] || {});\n\t\t\t\tconst pendingWrites = await Promise.all(writes.map(async ([taskId, channel, value]) => {\n\t\t\t\t\treturn [\n\t\t\t\t\t\ttaskId,\n\t\t\t\t\t\tchannel,\n\t\t\t\t\t\tawait this.serde.loadsTyped(\"json\", value)\n\t\t\t\t\t];\n\t\t\t\t}));\n\t\t\t\tconst deserializedCheckpoint = await this.serde.loadsTyped(\"json\", checkpoint);\n\t\t\t\tif (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, threadId, checkpointNamespace, parentCheckpointId);\n\t\t\t\tconst checkpointTuple = {\n\t\t\t\t\tconfig: { configurable: {\n\t\t\t\t\t\tthread_id: threadId,\n\t\t\t\t\t\tcheckpoint_ns: checkpointNamespace,\n\t\t\t\t\t\tcheckpoint_id: checkpointId\n\t\t\t\t\t} },\n\t\t\t\t\tcheckpoint: deserializedCheckpoint,\n\t\t\t\t\tmetadata,\n\t\t\t\t\tpendingWrites\n\t\t\t\t};\n\t\t\t\tif (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: {\n\t\t\t\t\tthread_id: threadId,\n\t\t\t\t\tcheckpoint_ns: checkpointNamespace,\n\t\t\t\t\tcheckpoint_id: parentCheckpointId\n\t\t\t\t} };\n\t\t\t\tyield checkpointTuple;\n\t\t\t}\n\t\t}\n\t}\n\tasync put(config, checkpoint, metadata) {\n\t\tconst preparedCheckpoint = copyCheckpoint(checkpoint);\n\t\tconst threadId = config.configurable?.thread_id;\n\t\tconst checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n\t\tif (threadId === void 0) throw new Error(`Failed to put checkpoint. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property.`);\n\t\tif (!this.storage[threadId]) this.storage[threadId] = {};\n\t\tif (!this.storage[threadId][checkpointNamespace]) this.storage[threadId][checkpointNamespace] = {};\n\t\tconst [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([this.serde.dumpsTyped(preparedCheckpoint), this.serde.dumpsTyped(metadata)]);\n\t\tthis.storage[threadId][checkpointNamespace][checkpoint.id] = [\n\t\t\tserializedCheckpoint,\n\t\t\tserializedMetadata,\n\t\t\tconfig.configurable?.checkpoint_id\n\t\t];\n\t\treturn { configurable: {\n\t\t\tthread_id: threadId,\n\t\t\tcheckpoint_ns: checkpointNamespace,\n\t\t\tcheckpoint_id: checkpoint.id\n\t\t} };\n\t}\n\tasync putWrites(config, writes, taskId) {\n\t\tconst threadId = config.configurable?.thread_id;\n\t\tconst checkpointNamespace = config.configurable?.checkpoint_ns;\n\t\tconst checkpointId = config.configurable?.checkpoint_id;\n\t\tif (threadId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property`);\n\t\tif (checkpointId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required \"checkpoint_id\" field in its \"configurable\" property.`);\n\t\tconst outerKey = _generateKey(threadId, checkpointNamespace, checkpointId);\n\t\tconst outerWrites_ = this.writes[outerKey];\n\t\tif (this.writes[outerKey] === void 0) this.writes[outerKey] = {};\n\t\tawait Promise.all(writes.map(async ([channel, value], idx) => {\n\t\t\tconst [, serializedValue] = await this.serde.dumpsTyped(value);\n\t\t\tconst innerKey = [taskId, WRITES_IDX_MAP[channel] || idx];\n\t\t\tconst innerKeyStr = `${innerKey[0]},${innerKey[1]}`;\n\t\t\tif (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) return;\n\t\t\tthis.writes[outerKey][innerKeyStr] = [\n\t\t\t\ttaskId,\n\t\t\t\tchannel,\n\t\t\t\tserializedValue\n\t\t\t];\n\t\t}));\n\t}\n\tasync deleteThread(threadId) {\n\t\tdelete this.storage[threadId];\n\t\tfor (const key of Object.keys(this.writes)) if (_parseKey(key).threadId === threadId) delete this.writes[key];\n\t}\n};\n\n//#endregion\nexport { MemorySaver };\n//# sourceMappingURL=memory.js.map","//#region src/store/base.ts\n/**\n* Error thrown when an invalid namespace is provided.\n*/\nvar InvalidNamespaceError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"InvalidNamespaceError\";\n\t}\n};\n/**\n* Validates the provided namespace.\n* @param namespace The namespace to validate.\n* @throws {InvalidNamespaceError} If the namespace is invalid.\n*/\nfunction validateNamespace(namespace) {\n\tif (namespace.length === 0) throw new InvalidNamespaceError(\"Namespace cannot be empty.\");\n\tfor (const label of namespace) {\n\t\tif (typeof label !== \"string\") throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`);\n\t\tif (label.includes(\".\")) throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`);\n\t\tif (label === \"\") throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`);\n\t}\n\tif (namespace[0] === \"langgraph\") throw new InvalidNamespaceError(`Root label for namespace cannot be \"langgraph\". Got: ${namespace}`);\n}\n/**\n* Utility function to get text at a specific JSON path\n*/\nfunction getTextAtPath(obj, path) {\n\tconst parts = path.split(\".\");\n\tlet current = obj;\n\tfor (const part of parts) {\n\t\tif (part.includes(\"[\")) {\n\t\t\tconst [arrayName, indexStr] = part.split(\"[\");\n\t\t\tconst index = indexStr.replace(\"]\", \"\");\n\t\t\tif (!current[arrayName]) return [];\n\t\t\tif (index === \"*\") {\n\t\t\t\tconst results = [];\n\t\t\t\tfor (const item of current[arrayName]) if (typeof item === \"string\") results.push(item);\n\t\t\t\treturn results;\n\t\t\t}\n\t\t\tconst idx = parseInt(index, 10);\n\t\t\tif (Number.isNaN(idx)) return [];\n\t\t\tcurrent = current[arrayName][idx];\n\t\t} else current = current[part];\n\t\tif (current === void 0) return [];\n\t}\n\treturn typeof current === \"string\" ? [current] : [];\n}\n/**\n* Tokenizes a JSON path into parts\n*/\nfunction tokenizePath(path) {\n\treturn path.split(\".\");\n}\n/**\n* Abstract base class for persistent key-value stores.\n*\n* Stores enable persistence and memory that can be shared across threads,\n* scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n*\n* Features:\n* - Hierarchical namespaces for organization\n* - Key-value storage with metadata\n* - Vector similarity search (if configured)\n* - Filtering and pagination\n*/\nvar BaseStore = class {\n\t/**\n\t* Retrieve a single item by its namespace and key.\n\t*\n\t* @param namespace Hierarchical path for the item\n\t* @param key Unique identifier within the namespace\n\t* @returns Promise resolving to the item or null if not found\n\t*/\n\tasync get(namespace, key) {\n\t\treturn (await this.batch([{\n\t\t\tnamespace,\n\t\t\tkey\n\t\t}]))[0];\n\t}\n\t/**\n\t* Search for items within a namespace prefix.\n\t* Supports both metadata filtering and vector similarity search.\n\t*\n\t* @param namespacePrefix Hierarchical path prefix to search within\n\t* @param options Search options for filtering and pagination\n\t* @returns Promise resolving to list of matching items with relevance scores\n\t*\n\t* @example\n\t* // Search with filters\n\t* await store.search([\"documents\"], {\n\t* filter: { type: \"report\", status: \"active\" },\n\t* limit: 5,\n\t* offset: 10\n\t* });\n\t*\n\t* // Vector similarity search\n\t* await store.search([\"users\", \"content\"], {\n\t* query: \"technical documentation about APIs\",\n\t* limit: 20\n\t* });\n\t*/\n\tasync search(namespacePrefix, options = {}) {\n\t\tconst { filter, limit = 10, offset = 0, query } = options;\n\t\treturn (await this.batch([{\n\t\t\tnamespacePrefix,\n\t\t\tfilter,\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tquery\n\t\t}]))[0];\n\t}\n\t/**\n\t* Store or update an item.\n\t*\n\t* @param namespace Hierarchical path for the item\n\t* @param key Unique identifier within the namespace\n\t* @param value Object containing the item's data\n\t* @param index Optional indexing configuration\n\t*\n\t* @example\n\t* // Simple storage\n\t* await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n\t*\n\t* // With specific field indexing\n\t* await store.put(\n\t* [\"docs\"],\n\t* \"report\",\n\t* {\n\t* title: \"Q4 Report\",\n\t* chapters: [{ content: \"...\" }, { content: \"...\" }]\n\t* },\n\t* [\"title\", \"chapters[*].content\"]\n\t* );\n\t*/\n\tasync put(namespace, key, value, index) {\n\t\tvalidateNamespace(namespace);\n\t\tawait this.batch([{\n\t\t\tnamespace,\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tindex\n\t\t}]);\n\t}\n\t/**\n\t* Delete an item from the store.\n\t*\n\t* @param namespace Hierarchical path for the item\n\t* @param key Unique identifier within the namespace\n\t*/\n\tasync delete(namespace, key) {\n\t\tawait this.batch([{\n\t\t\tnamespace,\n\t\t\tkey,\n\t\t\tvalue: null\n\t\t}]);\n\t}\n\t/**\n\t* List and filter namespaces in the store.\n\t* Used to explore data organization and navigate the namespace hierarchy.\n\t*\n\t* @param options Options for listing namespaces\n\t* @returns Promise resolving to list of namespace paths\n\t*\n\t* @example\n\t* // List all namespaces under \"documents\"\n\t* await store.listNamespaces({\n\t* prefix: [\"documents\"],\n\t* maxDepth: 2\n\t* });\n\t*\n\t* // List namespaces ending with \"v1\"\n\t* await store.listNamespaces({\n\t* suffix: [\"v1\"],\n\t* limit: 50\n\t* });\n\t*/\n\tasync listNamespaces(options = {}) {\n\t\tconst { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options;\n\t\tconst matchConditions = [];\n\t\tif (prefix) matchConditions.push({\n\t\t\tmatchType: \"prefix\",\n\t\t\tpath: prefix\n\t\t});\n\t\tif (suffix) matchConditions.push({\n\t\t\tmatchType: \"suffix\",\n\t\t\tpath: suffix\n\t\t});\n\t\treturn (await this.batch([{\n\t\t\tmatchConditions: matchConditions.length ? matchConditions : void 0,\n\t\t\tmaxDepth,\n\t\t\tlimit,\n\t\t\toffset\n\t\t}]))[0];\n\t}\n\t/**\n\t* Start the store. Override if initialization is needed.\n\t*/\n\tstart() {}\n\t/**\n\t* Stop the store. Override if cleanup is needed.\n\t*/\n\tstop() {}\n};\n\n//#endregion\nexport { BaseStore, InvalidNamespaceError, getTextAtPath, tokenizePath };\n//# sourceMappingURL=base.js.map","import { BaseStore } from \"./base.js\";\n\n//#region src/store/batch.ts\n/**\n* Extracts and returns the underlying store from an `AsyncBatchedStore`,\n* or returns the input if it is not an `AsyncBatchedStore`.\n*/\nconst extractStore = (input) => {\n\tif (\"lg_name\" in input && input.lg_name === \"AsyncBatchedStore\") return input.store;\n\treturn input;\n};\nvar AsyncBatchedStore = class extends BaseStore {\n\tlg_name = \"AsyncBatchedStore\";\n\tstore;\n\tqueue = /* @__PURE__ */ new Map();\n\tnextKey = 0;\n\trunning = false;\n\tprocessingTask = null;\n\tconstructor(store) {\n\t\tsuper();\n\t\tthis.store = extractStore(store);\n\t}\n\tget isRunning() {\n\t\treturn this.running;\n\t}\n\t/**\n\t* @ignore\n\t* Batch is not implemented here as we're only extending `BaseStore`\n\t* to allow it to be passed where `BaseStore` is expected, and implement\n\t* the convenience methods (get, search, put, delete).\n\t*/\n\tasync batch(_operations) {\n\t\tthrow new Error(\"The `batch` method is not implemented on `AsyncBatchedStore`.\\n Instead, it calls the `batch` method on the wrapped store.\\n If you are seeing this error, something is wrong.\");\n\t}\n\tasync get(namespace, key) {\n\t\treturn this.enqueueOperation({\n\t\t\tnamespace,\n\t\t\tkey\n\t\t});\n\t}\n\tasync search(namespacePrefix, options) {\n\t\tconst { filter, limit = 10, offset = 0, query } = options || {};\n\t\treturn this.enqueueOperation({\n\t\t\tnamespacePrefix,\n\t\t\tfilter,\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tquery\n\t\t});\n\t}\n\tasync put(namespace, key, value) {\n\t\treturn this.enqueueOperation({\n\t\t\tnamespace,\n\t\t\tkey,\n\t\t\tvalue\n\t\t});\n\t}\n\tasync delete(namespace, key) {\n\t\treturn this.enqueueOperation({\n\t\t\tnamespace,\n\t\t\tkey,\n\t\t\tvalue: null\n\t\t});\n\t}\n\tstart() {\n\t\tif (!this.running) {\n\t\t\tthis.running = true;\n\t\t\tthis.processingTask = this.processBatchQueue();\n\t\t}\n\t}\n\tasync stop() {\n\t\tthis.running = false;\n\t\tif (this.processingTask) await this.processingTask;\n\t}\n\tenqueueOperation(operation) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst key = this.nextKey;\n\t\t\tthis.nextKey += 1;\n\t\t\tthis.queue.set(key, {\n\t\t\t\toperation,\n\t\t\t\tresolve,\n\t\t\t\treject\n\t\t\t});\n\t\t});\n\t}\n\tasync processBatchQueue() {\n\t\twhile (this.running) {\n\t\t\tawait new Promise((resolve) => {\n\t\t\t\tsetTimeout(resolve, 0);\n\t\t\t});\n\t\t\tif (this.queue.size === 0) continue;\n\t\t\tconst batch = new Map(this.queue);\n\t\t\tthis.queue.clear();\n\t\t\ttry {\n\t\t\t\tconst operations = Array.from(batch.values()).map(({ operation }) => operation);\n\t\t\t\tconst results = await this.store.batch(operations);\n\t\t\t\tbatch.forEach(({ resolve }, key) => {\n\t\t\t\t\tconst index = Array.from(batch.keys()).indexOf(key);\n\t\t\t\t\tresolve(results[index]);\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tbatch.forEach(({ reject }) => {\n\t\t\t\t\treject(e);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\ttoJSON() {\n\t\treturn {\n\t\t\tqueue: this.queue,\n\t\t\tnextKey: this.nextKey,\n\t\t\trunning: this.running,\n\t\t\tstore: \"[LangGraphStore]\"\n\t\t};\n\t}\n};\n\n//#endregion\nexport { AsyncBatchedStore };\n//# sourceMappingURL=batch.js.map","//#region src/store/utils.ts\n/**\n* Tokenize a JSON path into parts.\n* @example\n* tokenizePath(\"metadata.title\") // -> [\"metadata\", \"title\"]\n* tokenizePath(\"chapters[*].content\") // -> [\"chapters[*]\", \"content\"]\n*/\nfunction tokenizePath(path) {\n\tif (!path) return [];\n\tconst tokens = [];\n\tlet current = [];\n\tlet i = 0;\n\twhile (i < path.length) {\n\t\tconst char = path[i];\n\t\tif (char === \"[\") {\n\t\t\tif (current.length) {\n\t\t\t\ttokens.push(current.join(\"\"));\n\t\t\t\tcurrent = [];\n\t\t\t}\n\t\t\tlet bracketCount = 1;\n\t\t\tconst indexChars = [\"[\"];\n\t\t\ti += 1;\n\t\t\twhile (i < path.length && bracketCount > 0) {\n\t\t\t\tif (path[i] === \"[\") bracketCount += 1;\n\t\t\t\telse if (path[i] === \"]\") bracketCount -= 1;\n\t\t\t\tindexChars.push(path[i]);\n\t\t\t\ti += 1;\n\t\t\t}\n\t\t\ttokens.push(indexChars.join(\"\"));\n\t\t\tcontinue;\n\t\t} else if (char === \"{\") {\n\t\t\tif (current.length) {\n\t\t\t\ttokens.push(current.join(\"\"));\n\t\t\t\tcurrent = [];\n\t\t\t}\n\t\t\tlet braceCount = 1;\n\t\t\tconst fieldChars = [\"{\"];\n\t\t\ti += 1;\n\t\t\twhile (i < path.length && braceCount > 0) {\n\t\t\t\tif (path[i] === \"{\") braceCount += 1;\n\t\t\t\telse if (path[i] === \"}\") braceCount -= 1;\n\t\t\t\tfieldChars.push(path[i]);\n\t\t\t\ti += 1;\n\t\t\t}\n\t\t\ttokens.push(fieldChars.join(\"\"));\n\t\t\tcontinue;\n\t\t} else if (char === \".\") {\n\t\t\tif (current.length) {\n\t\t\t\ttokens.push(current.join(\"\"));\n\t\t\t\tcurrent = [];\n\t\t\t}\n\t\t} else current.push(char);\n\t\ti += 1;\n\t}\n\tif (current.length) tokens.push(current.join(\"\"));\n\treturn tokens;\n}\n/**\n* Type guard to check if an object is a FilterOperators\n*/\nfunction isFilterOperators(obj) {\n\treturn typeof obj === \"object\" && obj !== null && Object.keys(obj).every((key) => key === \"$eq\" || key === \"$ne\" || key === \"$gt\" || key === \"$gte\" || key === \"$lt\" || key === \"$lte\" || key === \"$in\" || key === \"$nin\");\n}\n/**\n* Compare values for filtering, supporting operator-based comparisons.\n*/\nfunction compareValues(itemValue, filterValue) {\n\tif (isFilterOperators(filterValue)) {\n\t\tconst operators = Object.keys(filterValue).filter((k) => k.startsWith(\"$\"));\n\t\treturn operators.every((op) => {\n\t\t\tconst value = filterValue[op];\n\t\t\tswitch (op) {\n\t\t\t\tcase \"$eq\": return itemValue === value;\n\t\t\t\tcase \"$ne\": return itemValue !== value;\n\t\t\t\tcase \"$gt\": return Number(itemValue) > Number(value);\n\t\t\t\tcase \"$gte\": return Number(itemValue) >= Number(value);\n\t\t\t\tcase \"$lt\": return Number(itemValue) < Number(value);\n\t\t\t\tcase \"$lte\": return Number(itemValue) <= Number(value);\n\t\t\t\tcase \"$in\": return Array.isArray(value) ? value.includes(itemValue) : false;\n\t\t\t\tcase \"$nin\": return Array.isArray(value) ? !value.includes(itemValue) : true;\n\t\t\t\tdefault: return false;\n\t\t\t}\n\t\t});\n\t}\n\treturn itemValue === filterValue;\n}\n/**\n* Extract text from a value at a specific JSON path.\n*\n* Supports:\n* - Simple paths: \"field1.field2\"\n* - Array indexing: \"[0]\", \"[*]\", \"[-1]\"\n* - Wildcards: \"*\"\n* - Multi-field selection: \"{field1,field2}\"\n* - Nested paths in multi-field: \"{field1,nested.field2}\"\n*/\nfunction getTextAtPath(obj, path) {\n\tif (!path || path === \"$\") return [JSON.stringify(obj, null, 2)];\n\tconst tokens = Array.isArray(path) ? path : tokenizePath(path);\n\tfunction extractFromObj(obj$1, tokens$1, pos) {\n\t\tif (pos >= tokens$1.length) {\n\t\t\tif (typeof obj$1 === \"string\" || typeof obj$1 === \"number\" || typeof obj$1 === \"boolean\") return [String(obj$1)];\n\t\t\tif (obj$1 === null || obj$1 === void 0) return [];\n\t\t\tif (Array.isArray(obj$1) || typeof obj$1 === \"object\") return [JSON.stringify(obj$1, null, 2)];\n\t\t\treturn [];\n\t\t}\n\t\tconst token = tokens$1[pos];\n\t\tconst results = [];\n\t\tif (pos === 0 && token === \"$\") results.push(JSON.stringify(obj$1, null, 2));\n\t\tif (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n\t\t\tif (!Array.isArray(obj$1)) return [];\n\t\t\tconst index = token.slice(1, -1);\n\t\t\tif (index === \"*\") for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1));\n\t\t\telse try {\n\t\t\t\tlet idx = parseInt(index, 10);\n\t\t\t\tif (idx < 0) idx = obj$1.length + idx;\n\t\t\t\tif (idx >= 0 && idx < obj$1.length) results.push(...extractFromObj(obj$1[idx], tokens$1, pos + 1));\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t} else if (token.startsWith(\"{\") && token.endsWith(\"}\")) {\n\t\t\tif (typeof obj$1 !== \"object\" || obj$1 === null) return [];\n\t\t\tconst fields = token.slice(1, -1).split(\",\").map((f) => f.trim());\n\t\t\tfor (const field of fields) {\n\t\t\t\tconst nestedTokens = tokenizePath(field);\n\t\t\t\tif (nestedTokens.length) {\n\t\t\t\t\tlet currentObj = obj$1;\n\t\t\t\t\tfor (const nestedToken of nestedTokens) if (currentObj && typeof currentObj === \"object\" && nestedToken in currentObj) currentObj = currentObj[nestedToken];\n\t\t\t\t\telse {\n\t\t\t\t\t\tcurrentObj = void 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (currentObj !== void 0) {\n\t\t\t\t\t\tif (typeof currentObj === \"string\" || typeof currentObj === \"number\" || typeof currentObj === \"boolean\") results.push(String(currentObj));\n\t\t\t\t\t\telse if (Array.isArray(currentObj) || typeof currentObj === \"object\") results.push(JSON.stringify(currentObj, null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (token === \"*\") {\n\t\t\tif (Array.isArray(obj$1)) for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1));\n\t\t\telse if (typeof obj$1 === \"object\" && obj$1 !== null) for (const value of Object.values(obj$1)) results.push(...extractFromObj(value, tokens$1, pos + 1));\n\t\t} else if (typeof obj$1 === \"object\" && obj$1 !== null && token in obj$1) results.push(...extractFromObj(obj$1[token], tokens$1, pos + 1));\n\t\treturn results;\n\t}\n\treturn extractFromObj(obj, tokens, 0);\n}\n\n//#endregion\nexport { compareValues, getTextAtPath, tokenizePath };\n//# sourceMappingURL=utils.js.map","import { BaseStore } from \"./base.js\";\nimport { compareValues, getTextAtPath, tokenizePath } from \"./utils.js\";\n\n//#region src/store/memory.ts\n/**\n* In-memory key-value store with optional vector search.\n*\n* A lightweight store implementation using JavaScript Maps. Supports basic\n* key-value operations and vector search when configured with embeddings.\n*\n* @example\n* ```typescript\n* // Basic key-value storage\n* const store = new InMemoryStore();\n* await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n* const item = await store.get([\"users\", \"123\"], \"prefs\");\n*\n* // Vector search with embeddings\n* import { OpenAIEmbeddings } from \"@langchain/openai\";\n* const store = new InMemoryStore({\n* index: {\n* dims: 1536,\n* embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n* }\n* });\n*\n* // Store documents\n* await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n* await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n*\n* // Search by similarity\n* const results = await store.search([\"docs\"], { query: \"python programming\" });\n* ```\n*\n* **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n* For persistence, use a database-backed store.\n*/\nvar InMemoryStore = class extends BaseStore {\n\tdata = /* @__PURE__ */ new Map();\n\tvectors = /* @__PURE__ */ new Map();\n\t_indexConfig;\n\tconstructor(options) {\n\t\tsuper();\n\t\tif (options?.index) this._indexConfig = {\n\t\t\t...options.index,\n\t\t\t__tokenizedFields: (options.index.fields ?? [\"$\"]).map((p) => [p, p === \"$\" ? [p] : tokenizePath(p)])\n\t\t};\n\t}\n\tasync batch(operations) {\n\t\tconst results = [];\n\t\tconst putOps = /* @__PURE__ */ new Map();\n\t\tconst searchOps = /* @__PURE__ */ new Map();\n\t\tfor (let i = 0; i < operations.length; i += 1) {\n\t\t\tconst op = operations[i];\n\t\t\tif (\"key\" in op && \"namespace\" in op && !(\"value\" in op)) results.push(this.getOperation(op));\n\t\t\telse if (\"namespacePrefix\" in op) {\n\t\t\t\tconst candidates = this.filterItems(op);\n\t\t\t\tsearchOps.set(i, [op, candidates]);\n\t\t\t\tresults.push(null);\n\t\t\t} else if (\"value\" in op) {\n\t\t\t\tconst key = `${op.namespace.join(\":\")}:${op.key}`;\n\t\t\t\tputOps.set(key, op);\n\t\t\t\tresults.push(null);\n\t\t\t} else if (\"matchConditions\" in op) results.push(this.listNamespacesOperation(op));\n\t\t}\n\t\tif (searchOps.size > 0) if (this._indexConfig?.embeddings) {\n\t\t\tconst queries = /* @__PURE__ */ new Set();\n\t\t\tfor (const [op] of searchOps.values()) if (op.query) queries.add(op.query);\n\t\t\tconst queryEmbeddings = queries.size > 0 ? await Promise.all(Array.from(queries).map((q) => this._indexConfig.embeddings.embedQuery(q))) : [];\n\t\t\tconst queryVectors = Object.fromEntries(Array.from(queries).map((q, i) => [q, queryEmbeddings[i]]));\n\t\t\tfor (const [i, [op, candidates]] of searchOps.entries()) if (op.query && queryVectors[op.query]) {\n\t\t\t\tconst queryVector = queryVectors[op.query];\n\t\t\t\tconst scoredResults = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10);\n\t\t\t\tresults[i] = scoredResults;\n\t\t\t} else results[i] = this.paginateResults(candidates.map((item) => ({\n\t\t\t\t...item,\n\t\t\t\tscore: void 0\n\t\t\t})), op.offset ?? 0, op.limit ?? 10);\n\t\t} else for (const [i, [op, candidates]] of searchOps.entries()) results[i] = this.paginateResults(candidates.map((item) => ({\n\t\t\t...item,\n\t\t\tscore: void 0\n\t\t})), op.offset ?? 0, op.limit ?? 10);\n\t\tif (putOps.size > 0 && this._indexConfig?.embeddings) {\n\t\t\tconst toEmbed = this.extractTexts(Array.from(putOps.values()));\n\t\t\tif (Object.keys(toEmbed).length > 0) {\n\t\t\t\tconst embeddings = await this._indexConfig.embeddings.embedDocuments(Object.keys(toEmbed));\n\t\t\t\tthis.insertVectors(toEmbed, embeddings);\n\t\t\t}\n\t\t}\n\t\tfor (const op of putOps.values()) this.putOperation(op);\n\t\treturn results;\n\t}\n\tgetOperation(op) {\n\t\tconst namespaceKey = op.namespace.join(\":\");\n\t\tconst item = this.data.get(namespaceKey)?.get(op.key);\n\t\treturn item ?? null;\n\t}\n\tputOperation(op) {\n\t\tconst namespaceKey = op.namespace.join(\":\");\n\t\tif (!this.data.has(namespaceKey)) this.data.set(namespaceKey, /* @__PURE__ */ new Map());\n\t\tconst namespaceMap = this.data.get(namespaceKey);\n\t\tif (op.value === null) namespaceMap.delete(op.key);\n\t\telse {\n\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\tif (namespaceMap.has(op.key)) {\n\t\t\t\tconst item = namespaceMap.get(op.key);\n\t\t\t\titem.value = op.value;\n\t\t\t\titem.updatedAt = now;\n\t\t\t} else namespaceMap.set(op.key, {\n\t\t\t\tvalue: op.value,\n\t\t\t\tkey: op.key,\n\t\t\t\tnamespace: op.namespace,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t}\n\t}\n\tlistNamespacesOperation(op) {\n\t\tconst allNamespaces = Array.from(this.data.keys()).map((ns) => ns.split(\":\"));\n\t\tlet namespaces = allNamespaces;\n\t\tif (op.matchConditions && op.matchConditions.length > 0) namespaces = namespaces.filter((ns) => op.matchConditions.every((condition) => this.doesMatch(condition, ns)));\n\t\tif (op.maxDepth !== void 0) namespaces = Array.from(new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(\":\")))).map((ns) => ns.split(\":\"));\n\t\tnamespaces.sort((a, b) => a.join(\":\").localeCompare(b.join(\":\")));\n\t\treturn namespaces.slice(op.offset ?? 0, (op.offset ?? 0) + (op.limit ?? namespaces.length));\n\t}\n\tdoesMatch(matchCondition, key) {\n\t\tconst { matchType, path } = matchCondition;\n\t\tif (matchType === \"prefix\") {\n\t\t\tif (path.length > key.length) return false;\n\t\t\treturn path.every((pElem, index) => {\n\t\t\t\tconst kElem = key[index];\n\t\t\t\treturn pElem === \"*\" || kElem === pElem;\n\t\t\t});\n\t\t} else if (matchType === \"suffix\") {\n\t\t\tif (path.length > key.length) return false;\n\t\t\treturn path.every((pElem, index) => {\n\t\t\t\tconst kElem = key[key.length - path.length + index];\n\t\t\t\treturn pElem === \"*\" || kElem === pElem;\n\t\t\t});\n\t\t}\n\t\tthrow new Error(`Unsupported match type: ${matchType}`);\n\t}\n\tfilterItems(op) {\n\t\tconst candidates = [];\n\t\tfor (const [namespace, items] of this.data.entries()) if (namespace.startsWith(op.namespacePrefix.join(\":\"))) candidates.push(...items.values());\n\t\tlet filteredCandidates = candidates;\n\t\tif (op.filter) filteredCandidates = candidates.filter((item) => Object.entries(op.filter).every(([key, value]) => compareValues(item.value[key], value)));\n\t\treturn filteredCandidates;\n\t}\n\tscoreResults(candidates, queryVector, offset = 0, limit = 10) {\n\t\tconst flatItems = [];\n\t\tconst flatVectors = [];\n\t\tconst scoreless = [];\n\t\tfor (const item of candidates) {\n\t\t\tconst vectors = this.getVectors(item);\n\t\t\tif (vectors.length) for (const vector of vectors) {\n\t\t\t\tflatItems.push(item);\n\t\t\t\tflatVectors.push(vector);\n\t\t\t}\n\t\t\telse scoreless.push(item);\n\t\t}\n\t\tconst scores = this.cosineSimilarity(queryVector, flatVectors);\n\t\tconst sortedResults = scores.map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tconst kept = [];\n\t\tfor (const [score, item] of sortedResults) {\n\t\t\tconst key = `${item.namespace.join(\":\")}:${item.key}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tconst ix = seen.size;\n\t\t\tif (ix >= offset + limit) break;\n\t\t\tif (ix < offset) {\n\t\t\t\tseen.add(key);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseen.add(key);\n\t\t\tkept.push([score, item]);\n\t\t}\n\t\tif (scoreless.length && kept.length < limit) for (const item of scoreless.slice(0, limit - kept.length)) {\n\t\t\tconst key = `${item.namespace.join(\":\")}:${item.key}`;\n\t\t\tif (!seen.has(key)) {\n\t\t\t\tseen.add(key);\n\t\t\t\tkept.push([void 0, item]);\n\t\t\t}\n\t\t}\n\t\treturn kept.map(([score, item]) => ({\n\t\t\t...item,\n\t\t\tscore\n\t\t}));\n\t}\n\tpaginateResults(results, offset, limit) {\n\t\treturn results.slice(offset, offset + limit);\n\t}\n\textractTexts(ops) {\n\t\tif (!ops.length || !this._indexConfig) return {};\n\t\tconst toEmbed = {};\n\t\tfor (const op of ops) if (op.value !== null && op.index !== false) {\n\t\t\tconst paths = op.index === null || op.index === void 0 ? this._indexConfig.__tokenizedFields ?? [] : op.index.map((ix) => [ix, tokenizePath(ix)]);\n\t\t\tfor (const [path, field] of paths) {\n\t\t\t\tconst texts = getTextAtPath(op.value, field);\n\t\t\t\tif (texts.length) if (texts.length > 1) texts.forEach((text, i) => {\n\t\t\t\t\tif (!toEmbed[text]) toEmbed[text] = [];\n\t\t\t\t\ttoEmbed[text].push([\n\t\t\t\t\t\top.namespace,\n\t\t\t\t\t\top.key,\n\t\t\t\t\t\t`${path}.${i}`\n\t\t\t\t\t]);\n\t\t\t\t});\n\t\t\t\telse {\n\t\t\t\t\tif (!toEmbed[texts[0]]) toEmbed[texts[0]] = [];\n\t\t\t\t\ttoEmbed[texts[0]].push([\n\t\t\t\t\t\top.namespace,\n\t\t\t\t\t\top.key,\n\t\t\t\t\t\tpath\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn toEmbed;\n\t}\n\tinsertVectors(texts, embeddings) {\n\t\tfor (const [text, metadata] of Object.entries(texts)) {\n\t\t\tconst embedding = embeddings.shift();\n\t\t\tif (!embedding) throw new Error(`No embedding found for text: ${text}`);\n\t\t\tfor (const [namespace, key, field] of metadata) {\n\t\t\t\tconst namespaceKey = namespace.join(\":\");\n\t\t\t\tif (!this.vectors.has(namespaceKey)) this.vectors.set(namespaceKey, /* @__PURE__ */ new Map());\n\t\t\t\tconst namespaceMap = this.vectors.get(namespaceKey);\n\t\t\t\tif (!namespaceMap.has(key)) namespaceMap.set(key, /* @__PURE__ */ new Map());\n\t\t\t\tconst itemMap = namespaceMap.get(key);\n\t\t\t\titemMap.set(field, embedding);\n\t\t\t}\n\t\t}\n\t}\n\tgetVectors(item) {\n\t\tconst namespaceKey = item.namespace.join(\":\");\n\t\tconst itemKey = item.key;\n\t\tif (!this.vectors.has(namespaceKey)) return [];\n\t\tconst namespaceMap = this.vectors.get(namespaceKey);\n\t\tif (!namespaceMap.has(itemKey)) return [];\n\t\tconst itemMap = namespaceMap.get(itemKey);\n\t\tconst vectors = Array.from(itemMap.values());\n\t\tif (!vectors.length) return [];\n\t\treturn vectors;\n\t}\n\tcosineSimilarity(X, Y) {\n\t\tif (!Y.length) return [];\n\t\tconst dotProducts = Y.map((vector) => vector.reduce((acc, val, i) => acc + val * X[i], 0));\n\t\tconst magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0));\n\t\tconst magnitudes2 = Y.map((vector) => Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0)));\n\t\treturn dotProducts.map((dot, i) => {\n\t\t\tconst magnitude2 = magnitudes2[i];\n\t\t\treturn magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0;\n\t\t});\n\t}\n\tget indexConfig() {\n\t\treturn this._indexConfig;\n\t}\n};\n/** @deprecated Alias for InMemoryStore */\nvar MemoryStore = class extends InMemoryStore {};\n\n//#endregion\nexport { InMemoryStore, MemoryStore };\n//# sourceMappingURL=memory.js.map","import { JsonPlusSerializer } from \"../serde/jsonplus.js\";\n\n//#region src/cache/base.ts\nvar BaseCache = class {\n\tserde = new JsonPlusSerializer();\n\t/**\n\t* Initialize the cache with a serializer.\n\t*\n\t* @param serde - The serializer to use.\n\t*/\n\tconstructor(serde) {\n\t\tthis.serde = serde || this.serde;\n\t}\n};\n\n//#endregion\nexport { BaseCache };\n//# sourceMappingURL=base.js.map","import { BaseCache } from \"./base.js\";\n\n//#region src/cache/memory.ts\nvar InMemoryCache = class extends BaseCache {\n\tcache = {};\n\tasync get(keys) {\n\t\tif (!keys.length) return [];\n\t\tconst now = Date.now();\n\t\treturn (await Promise.all(keys.map(async (fullKey) => {\n\t\t\tconst [namespace, key] = fullKey;\n\t\t\tconst strNamespace = namespace.join(\",\");\n\t\t\tif (strNamespace in this.cache && key in this.cache[strNamespace]) {\n\t\t\t\tconst cached = this.cache[strNamespace][key];\n\t\t\t\tif (cached.exp == null || now < cached.exp) {\n\t\t\t\t\tconst value = await this.serde.loadsTyped(cached.enc, cached.val);\n\t\t\t\t\treturn [{\n\t\t\t\t\t\tkey: fullKey,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}];\n\t\t\t\t} else delete this.cache[strNamespace][key];\n\t\t\t}\n\t\t\treturn [];\n\t\t}))).flat();\n\t}\n\tasync set(pairs) {\n\t\tconst now = Date.now();\n\t\tfor (const { key: fullKey, value, ttl } of pairs) {\n\t\t\tconst [namespace, key] = fullKey;\n\t\t\tconst strNamespace = namespace.join(\",\");\n\t\t\tconst [enc, val] = await this.serde.dumpsTyped(value);\n\t\t\tconst exp = ttl != null ? ttl * 1e3 + now : null;\n\t\t\tthis.cache[strNamespace] ??= {};\n\t\t\tthis.cache[strNamespace][key] = {\n\t\t\t\tenc,\n\t\t\t\tval,\n\t\t\t\texp\n\t\t\t};\n\t\t}\n\t}\n\tasync clear(namespaces) {\n\t\tif (!namespaces.length) {\n\t\t\tthis.cache = {};\n\t\t\treturn;\n\t\t}\n\t\tfor (const namespace of namespaces) {\n\t\t\tconst strNamespace = namespace.join(\",\");\n\t\t\tif (strNamespace in this.cache) delete this.cache[strNamespace];\n\t\t}\n\t}\n};\n\n//#endregion\nexport { InMemoryCache };\n//# sourceMappingURL=memory.js.map","import { BaseCache } from \"./base.js\";\nimport { InMemoryCache } from \"./memory.js\";\n\nexport { };","import { uuid5, uuid6 } from \"./id.js\";\nimport { ERROR, INTERRUPT, RESUME, SCHEDULED, TASKS } from \"./serde/types.js\";\nimport { BaseCheckpointSaver, WRITES_IDX_MAP, compareChannelVersions, copyCheckpoint, deepCopy, emptyCheckpoint, getCheckpointId, maxChannelVersion } from \"./base.js\";\nimport { MemorySaver } from \"./memory.js\";\nimport { BaseStore, InvalidNamespaceError, getTextAtPath, tokenizePath } from \"./store/base.js\";\nimport { AsyncBatchedStore } from \"./store/batch.js\";\nimport { InMemoryStore, MemoryStore } from \"./store/memory.js\";\nimport { BaseCache } from \"./cache/base.js\";\nimport { InMemoryCache } from \"./cache/memory.js\";\nimport \"./cache/index.js\";\n\nexport { AsyncBatchedStore, BaseCache, BaseCheckpointSaver, BaseStore, ERROR, INTERRUPT, InMemoryCache, InMemoryStore, InvalidNamespaceError, MemorySaver, MemoryStore, RESUME, SCHEDULED, TASKS, WRITES_IDX_MAP, compareChannelVersions, copyCheckpoint, deepCopy, emptyCheckpoint, getCheckpointId, getTextAtPath, maxChannelVersion, tokenizePath, uuid5, uuid6 };","import { EmptyChannelError } from \"../errors.js\";\nimport { uuid6 } from \"@langchain/langgraph-checkpoint\";\n\n//#region src/channels/base.ts\nfunction isBaseChannel(obj) {\n\treturn obj != null && obj.lg_is_channel === true;\n}\n/** @internal */\nvar BaseChannel = class {\n\tValueType;\n\tUpdateType;\n\t/** @ignore */\n\tlg_is_channel = true;\n\t/**\n\t* Mark the current value of the channel as consumed. By default, no-op.\n\t* A channel can use this method to modify its state, preventing the value\n\t* from being consumed again.\n\t*\n\t* Returns True if the channel was updated, False otherwise.\n\t*/\n\tconsume() {\n\t\treturn false;\n\t}\n\t/**\n\t* Notify the channel that the Pregel run is finishing. By default, no-op.\n\t* A channel can use this method to modify its state, preventing finish.\n\t*\n\t* Returns True if the channel was updated, False otherwise.\n\t*/\n\tfinish() {\n\t\treturn false;\n\t}\n\t/**\n\t* Return True if the channel is available (not empty), False otherwise.\n\t* Subclasses should override this method to provide a more efficient\n\t* implementation than calling get() and catching EmptyChannelError.\n\t*/\n\tisAvailable() {\n\t\ttry {\n\t\t\tthis.get();\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error.name === EmptyChannelError.unminifiable_name) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n};\nconst IS_ONLY_BASE_CHANNEL = Symbol.for(\"LG_IS_ONLY_BASE_CHANNEL\");\nfunction getOnlyChannels(channels) {\n\tif (channels[IS_ONLY_BASE_CHANNEL] === true) return channels;\n\tconst newChannels = {};\n\tfor (const k in channels) {\n\t\tif (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n\t\tconst value = channels[k];\n\t\tif (isBaseChannel(value)) newChannels[k] = value;\n\t}\n\tObject.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n\treturn newChannels;\n}\nfunction emptyChannels(channels, checkpoint) {\n\tconst filteredChannels = getOnlyChannels(channels);\n\tconst newChannels = {};\n\tfor (const k in filteredChannels) {\n\t\tif (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue;\n\t\tconst channelValue = checkpoint.channel_values[k];\n\t\tnewChannels[k] = filteredChannels[k].fromCheckpoint(channelValue);\n\t}\n\tObject.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n\treturn newChannels;\n}\nfunction createCheckpoint(checkpoint, channels, step, options) {\n\tlet values;\n\tif (channels === void 0) values = checkpoint.channel_values;\n\telse {\n\t\tvalues = {};\n\t\tfor (const k in channels) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n\t\t\ttry {\n\t\t\t\tvalues[k] = channels[k].checkpoint();\n\t\t\t} catch (error) {\n\t\t\t\tif (error.name === EmptyChannelError.unminifiable_name) {} else throw error;\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tv: 4,\n\t\tid: options?.id ?? uuid6(step),\n\t\tts: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tchannel_values: values,\n\t\tchannel_versions: checkpoint.channel_versions,\n\t\tversions_seen: checkpoint.versions_seen\n\t};\n}\n\n//#endregion\nexport { BaseChannel, createCheckpoint, emptyChannels, getOnlyChannels, isBaseChannel };\n//# sourceMappingURL=base.js.map","import { EmptyChannelError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\n\n//#region src/channels/binop.ts\n/**\n* Stores the result of applying a binary operator to the current value and each new value.\n*/\nvar BinaryOperatorAggregate = class BinaryOperatorAggregate extends BaseChannel {\n\tlc_graph_name = \"BinaryOperatorAggregate\";\n\tvalue;\n\toperator;\n\tinitialValueFactory;\n\tconstructor(operator, initialValueFactory) {\n\t\tsuper();\n\t\tthis.operator = operator;\n\t\tthis.initialValueFactory = initialValueFactory;\n\t\tthis.value = initialValueFactory?.();\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new BinaryOperatorAggregate(this.operator, this.initialValueFactory);\n\t\tif (typeof checkpoint !== \"undefined\") empty.value = checkpoint;\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tlet newValues = values;\n\t\tif (!newValues.length) return false;\n\t\tif (this.value === void 0) {\n\t\t\t[this.value] = newValues;\n\t\t\tnewValues = newValues.slice(1);\n\t\t}\n\t\tfor (const value of newValues) if (this.value !== void 0) this.value = this.operator(this.value, value);\n\t\treturn true;\n\t}\n\tget() {\n\t\tif (this.value === void 0) throw new EmptyChannelError();\n\t\treturn this.value;\n\t}\n\tcheckpoint() {\n\t\tif (this.value === void 0) throw new EmptyChannelError();\n\t\treturn this.value;\n\t}\n\tisAvailable() {\n\t\treturn this.value !== void 0;\n\t}\n};\n\n//#endregion\nexport { BinaryOperatorAggregate };\n//# sourceMappingURL=binop.js.map","import { EmptyChannelError, InvalidUpdateError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\n\n//#region src/channels/last_value.ts\n/**\n* Stores the last value received, can receive at most one value per step.\n*\n* Since `update` is only called once per step and value can only be of length 1,\n* LastValue always stores the last value of a single node. If multiple nodes attempt to\n* write to this channel in a single step, an error will be thrown.\n* @internal\n*/\nvar LastValue = class LastValue extends BaseChannel {\n\tlc_graph_name = \"LastValue\";\n\tvalue = [];\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new LastValue();\n\t\tif (typeof checkpoint !== \"undefined\") empty.value = [checkpoint];\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tif (values.length === 0) return false;\n\t\tif (values.length !== 1) throw new InvalidUpdateError(\"LastValue can only receive one value per step.\", { lc_error_code: \"INVALID_CONCURRENT_GRAPH_UPDATE\" });\n\t\tthis.value = [values[values.length - 1]];\n\t\treturn true;\n\t}\n\tget() {\n\t\tif (this.value.length === 0) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tcheckpoint() {\n\t\tif (this.value.length === 0) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tisAvailable() {\n\t\treturn this.value.length !== 0;\n\t}\n};\n/**\n* Stores the last value received, but only made available after finish().\n* Once made available, clears the value.\n*/\nvar LastValueAfterFinish = class LastValueAfterFinish extends BaseChannel {\n\tlc_graph_name = \"LastValueAfterFinish\";\n\tvalue = [];\n\tfinished = false;\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new LastValueAfterFinish();\n\t\tif (typeof checkpoint !== \"undefined\") {\n\t\t\tconst [value, finished] = checkpoint;\n\t\t\tempty.value = [value];\n\t\t\tempty.finished = finished;\n\t\t}\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tif (values.length === 0) return false;\n\t\tthis.finished = false;\n\t\tthis.value = [values[values.length - 1]];\n\t\treturn true;\n\t}\n\tget() {\n\t\tif (this.value.length === 0 || !this.finished) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tcheckpoint() {\n\t\tif (this.value.length === 0) return void 0;\n\t\treturn [this.value[0], this.finished];\n\t}\n\tconsume() {\n\t\tif (this.finished) {\n\t\t\tthis.finished = false;\n\t\t\tthis.value = [];\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tfinish() {\n\t\tif (!this.finished && this.value.length > 0) {\n\t\t\tthis.finished = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tisAvailable() {\n\t\treturn this.value.length !== 0 && this.finished;\n\t}\n};\n\n//#endregion\nexport { LastValue, LastValueAfterFinish };\n//# sourceMappingURL=last_value.js.map","import { BinaryOperatorAggregate } from \"../channels/binop.js\";\nimport { LastValue } from \"../channels/last_value.js\";\n\n//#region src/graph/annotation.ts\n/**\n* Should not be instantiated directly. See {@link Annotation}.\n*/\nvar AnnotationRoot = class {\n\tlc_graph_name = \"AnnotationRoot\";\n\tspec;\n\tconstructor(s) {\n\t\tthis.spec = s;\n\t}\n};\n/**\n* Helper that instantiates channels within a StateGraph state.\n*\n* Can be used as a field in an {@link Annotation.Root} wrapper in one of two ways:\n* 1. **Directly**: Creates a channel that stores the most recent value returned from a node.\n* 2. **With a reducer**: Creates a channel that applies the reducer on a node's return value.\n*\n* @example\n* ```ts\n* import { StateGraph, Annotation } from \"@langchain/langgraph\";\n*\n* // Define a state with a single string key named \"currentOutput\"\n* const SimpleAnnotation = Annotation.Root({\n* currentOutput: Annotation,\n* });\n*\n* const graphBuilder = new StateGraph(SimpleAnnotation);\n*\n* // A node in the graph that returns an object with a \"currentOutput\" key\n* // replaces the value in the state. You can get the state type as shown below:\n* const myNode = (state: typeof SimpleAnnotation.State) => {\n* return {\n* currentOutput: \"some_new_value\",\n* };\n* }\n*\n* const graph = graphBuilder\n* .addNode(\"myNode\", myNode)\n* ...\n* .compile();\n* ```\n*\n* @example\n* ```ts\n* import { type BaseMessage, AIMessage } from \"@langchain/core/messages\";\n* import { StateGraph, Annotation } from \"@langchain/langgraph\";\n*\n* // Define a state with a single key named \"messages\" that will\n* // combine a returned BaseMessage or arrays of BaseMessages\n* const AnnotationWithReducer = Annotation.Root({\n* messages: Annotation({\n* // Different types are allowed for updates\n* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => {\n* if (Array.isArray(right)) {\n* return left.concat(right);\n* }\n* return left.concat([right]);\n* },\n* default: () => [],\n* }),\n* });\n*\n* const graphBuilder = new StateGraph(AnnotationWithReducer);\n*\n* // A node in the graph that returns an object with a \"messages\" key\n* // will update the state by combining the existing value with the returned one.\n* const myNode = (state: typeof AnnotationWithReducer.State) => {\n* return {\n* messages: [new AIMessage(\"Some new response\")],\n* };\n* };\n*\n* const graph = graphBuilder\n* .addNode(\"myNode\", myNode)\n* ...\n* .compile();\n* ```\n* @namespace\n* @property Root\n* Helper function that instantiates a StateGraph state. See {@link Annotation} for usage.\n*/\nconst Annotation = function(annotation) {\n\tif (annotation) return getChannel(annotation);\n\telse return new LastValue();\n};\nAnnotation.Root = (sd) => new AnnotationRoot(sd);\nfunction getChannel(reducer) {\n\tif (typeof reducer === \"object\" && reducer && \"reducer\" in reducer && reducer.reducer) return new BinaryOperatorAggregate(reducer.reducer, reducer.default);\n\tif (typeof reducer === \"object\" && reducer && \"value\" in reducer && reducer.value) return new BinaryOperatorAggregate(reducer.value, reducer.default);\n\treturn new LastValue();\n}\n\n//#endregion\nexport { Annotation, AnnotationRoot, getChannel };\n//# sourceMappingURL=annotation.js.map","//#region src/constants.ts\n/** Special reserved node name denoting the start of a graph. */\nconst START = \"__start__\";\n/** Special reserved node name denoting the end of a graph. */\nconst END = \"__end__\";\nconst INPUT = \"__input__\";\nconst COPY = \"__copy__\";\nconst ERROR = \"__error__\";\n/** Special reserved cache namespaces */\nconst CACHE_NS_WRITES = \"__pregel_ns_writes\";\nconst CONFIG_KEY_SEND = \"__pregel_send\";\n/** config key containing function used to call a node (push task) */\nconst CONFIG_KEY_CALL = \"__pregel_call\";\nconst CONFIG_KEY_READ = \"__pregel_read\";\nconst CONFIG_KEY_CHECKPOINTER = \"__pregel_checkpointer\";\nconst CONFIG_KEY_RESUMING = \"__pregel_resuming\";\nconst CONFIG_KEY_TASK_ID = \"__pregel_task_id\";\nconst CONFIG_KEY_STREAM = \"__pregel_stream\";\nconst CONFIG_KEY_RESUME_VALUE = \"__pregel_resume_value\";\nconst CONFIG_KEY_RESUME_MAP = \"__pregel_resume_map\";\nconst CONFIG_KEY_SCRATCHPAD = \"__pregel_scratchpad\";\n/** config key containing state from previous invocation of graph for the given thread */\nconst CONFIG_KEY_PREVIOUS_STATE = \"__pregel_previous\";\nconst CONFIG_KEY_DURABILITY = \"__pregel_durability\";\nconst CONFIG_KEY_CHECKPOINT_ID = \"checkpoint_id\";\nconst CONFIG_KEY_CHECKPOINT_NS = \"checkpoint_ns\";\nconst CONFIG_KEY_NODE_FINISHED = \"__pregel_node_finished\";\nconst CONFIG_KEY_CHECKPOINT_MAP = \"checkpoint_map\";\nconst CONFIG_KEY_ABORT_SIGNALS = \"__pregel_abort_signals\";\n/** Special channel reserved for graph interrupts */\nconst INTERRUPT = \"__interrupt__\";\n/** Special channel reserved for graph resume */\nconst RESUME = \"__resume__\";\n/** Special channel reserved for cases when a task exits without any writes */\nconst NO_WRITES = \"__no_writes__\";\n/** Special channel reserved for graph return */\nconst RETURN = \"__return__\";\n/** Special channel reserved for graph previous state */\nconst PREVIOUS = \"__previous__\";\nconst TAG_HIDDEN = \"langsmith:hidden\";\nconst TAG_NOSTREAM = \"langsmith:nostream\";\nconst SELF = \"__self__\";\nconst TASKS = \"__pregel_tasks\";\nconst PUSH = \"__pregel_push\";\nconst PULL = \"__pregel_pull\";\nconst NULL_TASK_ID = \"00000000-0000-0000-0000-000000000000\";\nconst RESERVED = [\n\tTAG_HIDDEN,\n\tINPUT,\n\tINTERRUPT,\n\tRESUME,\n\tERROR,\n\tNO_WRITES,\n\tCONFIG_KEY_SEND,\n\tCONFIG_KEY_READ,\n\tCONFIG_KEY_CHECKPOINTER,\n\tCONFIG_KEY_DURABILITY,\n\tCONFIG_KEY_STREAM,\n\tCONFIG_KEY_RESUMING,\n\tCONFIG_KEY_TASK_ID,\n\tCONFIG_KEY_CALL,\n\tCONFIG_KEY_RESUME_VALUE,\n\tCONFIG_KEY_SCRATCHPAD,\n\tCONFIG_KEY_PREVIOUS_STATE,\n\tCONFIG_KEY_CHECKPOINT_MAP,\n\tCONFIG_KEY_CHECKPOINT_NS,\n\tCONFIG_KEY_CHECKPOINT_ID\n];\nconst CHECKPOINT_NAMESPACE_SEPARATOR = \"|\";\nconst CHECKPOINT_NAMESPACE_END = \":\";\n/** @internal */\nconst COMMAND_SYMBOL = Symbol.for(\"langgraph.command\");\n/**\n* Instance of a {@link Command} class.\n*\n* This is used to avoid IntelliSense suggesting public fields\n* of {@link Command} class when a plain object is expected.\n*\n* @see {@link Command}\n* @internal\n*/\nvar CommandInstance = class {\n\t[COMMAND_SYMBOL];\n\tconstructor(args) {\n\t\tthis[COMMAND_SYMBOL] = args;\n\t}\n};\nfunction _isSendInterface(x) {\n\tconst operation = x;\n\treturn operation !== null && operation !== void 0 && typeof operation.node === \"string\" && operation.args !== void 0;\n}\n/**\n*\n* A message or packet to send to a specific node in the graph.\n*\n* The `Send` class is used within a `StateGraph`'s conditional edges to\n* dynamically invoke a node with a custom state at the next step.\n*\n* Importantly, the sent state can differ from the core graph's state,\n* allowing for flexible and dynamic workflow management.\n*\n* One such example is a \"map-reduce\" workflow where your graph invokes\n* the same node multiple times in parallel with different states,\n* before aggregating the results back into the main graph's state.\n*\n* @example\n* ```typescript\n* import { Annotation, Send, StateGraph } from \"@langchain/langgraph\";\n*\n* const ChainState = Annotation.Root({\n* subjects: Annotation,\n* jokes: Annotation({\n* reducer: (a, b) => a.concat(b),\n* }),\n* });\n*\n* const continueToJokes = async (state: typeof ChainState.State) => {\n* return state.subjects.map((subject) => {\n* return new Send(\"generate_joke\", { subjects: [subject] });\n* });\n* };\n*\n* const graph = new StateGraph(ChainState)\n* .addNode(\"generate_joke\", (state) => ({\n* jokes: [`Joke about ${state.subjects}`],\n* }))\n* .addConditionalEdges(\"__start__\", continueToJokes)\n* .addEdge(\"generate_joke\", \"__end__\")\n* .compile();\n*\n* const res = await graph.invoke({ subjects: [\"cats\", \"dogs\"] });\n* console.log(res);\n*\n* // Invoking with two subjects results in a generated joke for each\n* // { subjects: [\"cats\", \"dogs\"], jokes: [`Joke about cats`, `Joke about dogs`] }\n* ```\n*/\nvar Send = class {\n\tlg_name = \"Send\";\n\tnode;\n\targs;\n\tconstructor(node, args) {\n\t\tthis.node = node;\n\t\tthis.args = _deserializeCommandSendObjectGraph(args);\n\t}\n\ttoJSON() {\n\t\treturn {\n\t\t\tlg_name: this.lg_name,\n\t\t\tnode: this.node,\n\t\t\targs: this.args\n\t\t};\n\t}\n};\nfunction _isSend(x) {\n\treturn x instanceof Send;\n}\n/**\n* Checks if the given graph invoke / stream chunk contains interrupt.\n*\n* @example\n* ```ts\n* import { INTERRUPT, isInterrupted } from \"@langchain/langgraph\";\n*\n* const values = await graph.invoke({ foo: \"bar\" });\n* if (isInterrupted(values)) {\n* const interrupt = values[INTERRUPT][0].value;\n* }\n* ```\n*\n* @param values - The values to check.\n* @returns `true` if the values contain an interrupt, `false` otherwise.\n*/\nfunction isInterrupted(values) {\n\tif (!values || typeof values !== \"object\") return false;\n\tif (!(INTERRUPT in values)) return false;\n\treturn Array.isArray(values[INTERRUPT]);\n}\n/**\n* One or more commands to update the graph's state and send messages to nodes.\n* Can be used to combine routing logic with state updates in lieu of conditional edges\n*\n* @example\n* ```ts\n* import { Annotation, Command } from \"@langchain/langgraph\";\n*\n* // Define graph state\n* const StateAnnotation = Annotation.Root({\n* foo: Annotation,\n* });\n*\n* // Define the nodes\n* const nodeA = async (_state: typeof StateAnnotation.State) => {\n* console.log(\"Called A\");\n* // this is a replacement for a real conditional edge function\n* const goto = Math.random() > .5 ? \"nodeB\" : \"nodeC\";\n* // note how Command allows you to BOTH update the graph state AND route to the next node\n* return new Command({\n* // this is the state update\n* update: {\n* foo: \"a\",\n* },\n* // this is a replacement for an edge\n* goto,\n* });\n* };\n*\n* // Nodes B and C are unchanged\n* const nodeB = async (state: typeof StateAnnotation.State) => {\n* console.log(\"Called B\");\n* return {\n* foo: state.foo + \"|b\",\n* };\n* }\n*\n* const nodeC = async (state: typeof StateAnnotation.State) => {\n* console.log(\"Called C\");\n* return {\n* foo: state.foo + \"|c\",\n* };\n* }\n* \n* import { StateGraph } from \"@langchain/langgraph\";\n\n* // NOTE: there are no edges between nodes A, B and C!\n* const graph = new StateGraph(StateAnnotation)\n* .addNode(\"nodeA\", nodeA, {\n* ends: [\"nodeB\", \"nodeC\"],\n* })\n* .addNode(\"nodeB\", nodeB)\n* .addNode(\"nodeC\", nodeC)\n* .addEdge(\"__start__\", \"nodeA\")\n* .compile();\n* \n* await graph.invoke({ foo: \"\" });\n*\n* // Randomly oscillates between\n* // { foo: 'a|c' } and { foo: 'a|b' }\n* ```\n*/\nvar Command = class extends CommandInstance {\n\tlg_name = \"Command\";\n\tlc_direct_tool_output = true;\n\t/**\n\t* Graph to send the command to. Supported values are:\n\t* - None: the current graph (default)\n\t* - The specific name of the graph to send the command to\n\t* - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph)\n\t*/\n\tgraph;\n\t/**\n\t* Update to apply to the graph's state as a result of executing the node that is returning the command.\n\t* Written to the state as if the node had simply returned this value instead of the Command object.\n\t*/\n\tupdate;\n\t/**\n\t* Value to resume execution with. To be used together with {@link interrupt}.\n\t*/\n\tresume;\n\t/**\n\t* Can be one of the following:\n\t* - name of the node to navigate to next (any node that belongs to the specified `graph`)\n\t* - sequence of node names to navigate to next\n\t* - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object)\n\t* - sequence of {@link Send} objects\n\t*/\n\tgoto = [];\n\tstatic PARENT = \"__parent__\";\n\tconstructor(args) {\n\t\tsuper(args);\n\t\tthis.resume = args.resume;\n\t\tthis.graph = args.graph;\n\t\tthis.update = args.update;\n\t\tif (args.goto) this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)];\n\t}\n\t/**\n\t* Convert the update field to a list of {@link PendingWrite} tuples\n\t* @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`.\n\t* @internal\n\t*/\n\t_updateAsTuples() {\n\t\tif (this.update && typeof this.update === \"object\" && !Array.isArray(this.update)) return Object.entries(this.update);\n\t\telse if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === \"string\")) return this.update;\n\t\telse return [[\"__root__\", this.update]];\n\t}\n\ttoJSON() {\n\t\tlet serializedGoto;\n\t\tif (typeof this.goto === \"string\") serializedGoto = this.goto;\n\t\telse if (_isSend(this.goto)) serializedGoto = this.goto.toJSON();\n\t\telse serializedGoto = this.goto?.map((innerGoto) => {\n\t\t\tif (typeof innerGoto === \"string\") return innerGoto;\n\t\t\telse return innerGoto.toJSON();\n\t\t});\n\t\treturn {\n\t\t\tlg_name: this.lg_name,\n\t\t\tupdate: this.update,\n\t\t\tresume: this.resume,\n\t\t\tgoto: serializedGoto\n\t\t};\n\t}\n};\n/**\n* A type guard to check if the given value is a {@link Command}.\n*\n* Useful for type narrowing when working with the {@link Command} object.\n*\n* @param x - The value to check.\n* @returns `true` if the value is a {@link Command}, `false` otherwise.\n*/\nfunction isCommand(x) {\n\tif (typeof x !== \"object\") return false;\n\tif (x === null || x === void 0) return false;\n\tif (\"lg_name\" in x && x.lg_name === \"Command\") return true;\n\treturn false;\n}\n/**\n* Reconstructs Command and Send objects from a deeply nested tree of anonymous objects\n* matching their interfaces.\n*\n* This is only exported for testing purposes. It is NOT intended to be used outside of\n* the Command and Send classes.\n*\n* @internal\n*\n* @param x - The command send tree to convert.\n* @param seen - A map of seen objects to avoid infinite loops.\n* @returns The converted command send tree.\n*/\nfunction _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map()) {\n\tif (x !== void 0 && x !== null && typeof x === \"object\") {\n\t\tif (seen.has(x)) return seen.get(x);\n\t\tlet result;\n\t\tif (Array.isArray(x)) {\n\t\t\tresult = [];\n\t\t\tseen.set(x, result);\n\t\t\tx.forEach((item, index) => {\n\t\t\t\tresult[index] = _deserializeCommandSendObjectGraph(item, seen);\n\t\t\t});\n\t\t} else if (isCommand(x) && !(x instanceof Command)) {\n\t\t\tresult = new Command(x);\n\t\t\tseen.set(x, result);\n\t\t} else if (_isSendInterface(x) && !(x instanceof Send)) {\n\t\t\tresult = new Send(x.node, x.args);\n\t\t\tseen.set(x, result);\n\t\t} else if (isCommand(x) || _isSend(x)) {\n\t\t\tresult = x;\n\t\t\tseen.set(x, result);\n\t\t} else if (\"lc_serializable\" in x && x.lc_serializable) {\n\t\t\tresult = x;\n\t\t\tseen.set(x, result);\n\t\t} else {\n\t\t\tresult = {};\n\t\t\tseen.set(x, result);\n\t\t\tfor (const [key, value] of Object.entries(x)) result[key] = _deserializeCommandSendObjectGraph(value, seen);\n\t\t}\n\t\treturn result;\n\t}\n\treturn x;\n}\n\n//#endregion\nexport { CACHE_NS_WRITES, CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_ABORT_SIGNALS, CONFIG_KEY_CALL, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_CHECKPOINT_ID, CONFIG_KEY_CHECKPOINT_MAP, CONFIG_KEY_CHECKPOINT_NS, CONFIG_KEY_DURABILITY, CONFIG_KEY_NODE_FINISHED, CONFIG_KEY_PREVIOUS_STATE, CONFIG_KEY_READ, CONFIG_KEY_RESUME_MAP, CONFIG_KEY_RESUMING, CONFIG_KEY_SCRATCHPAD, CONFIG_KEY_SEND, CONFIG_KEY_STREAM, CONFIG_KEY_TASK_ID, COPY, Command, CommandInstance, END, ERROR, INPUT, INTERRUPT, NO_WRITES, NULL_TASK_ID, PREVIOUS, PULL, PUSH, RESERVED, RESUME, RETURN, SELF, START, Send, TAG_HIDDEN, TAG_NOSTREAM, TASKS, _isSend, _isSendInterface, isCommand, isInterrupted };\n//# sourceMappingURL=constants.js.map","import { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_SCRATCHPAD } from \"../../constants.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\n\n//#region src/pregel/utils/config.ts\nconst COPIABLE_KEYS = [\n\t\"tags\",\n\t\"metadata\",\n\t\"callbacks\",\n\t\"configurable\"\n];\nconst CONFIG_KEYS = [\n\t\"tags\",\n\t\"metadata\",\n\t\"callbacks\",\n\t\"runName\",\n\t\"maxConcurrency\",\n\t\"recursionLimit\",\n\t\"configurable\",\n\t\"runId\",\n\t\"outputKeys\",\n\t\"streamMode\",\n\t\"store\",\n\t\"writer\",\n\t\"interrupt\",\n\t\"context\",\n\t\"interruptBefore\",\n\t\"interruptAfter\",\n\t\"checkpointDuring\",\n\t\"durability\",\n\t\"signal\"\n];\nconst DEFAULT_RECURSION_LIMIT = 25;\nfunction ensureLangGraphConfig(...configs) {\n\tconst empty = {\n\t\ttags: [],\n\t\tmetadata: {},\n\t\tcallbacks: void 0,\n\t\trecursionLimit: DEFAULT_RECURSION_LIMIT,\n\t\tconfigurable: {}\n\t};\n\tconst implicitConfig = AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (implicitConfig !== void 0) {\n\t\tfor (const [k, v] of Object.entries(implicitConfig)) if (v !== void 0) if (COPIABLE_KEYS.includes(k)) {\n\t\t\tlet copiedValue;\n\t\t\tif (Array.isArray(v)) copiedValue = [...v];\n\t\t\telse if (typeof v === \"object\") if (k === \"callbacks\" && \"copy\" in v && typeof v.copy === \"function\") copiedValue = v.copy();\n\t\t\telse copiedValue = { ...v };\n\t\t\telse copiedValue = v;\n\t\t\tempty[k] = copiedValue;\n\t\t} else empty[k] = v;\n\t}\n\tfor (const config of configs) {\n\t\tif (config === void 0) continue;\n\t\tfor (const [k, v] of Object.entries(config)) if (v !== void 0 && CONFIG_KEYS.includes(k)) empty[k] = v;\n\t}\n\tfor (const [key, value] of Object.entries(empty.configurable)) {\n\t\tempty.metadata = empty.metadata ?? {};\n\t\tif (!key.startsWith(\"__\") && (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") && !(key in empty.metadata)) empty.metadata[key] = value;\n\t}\n\treturn empty;\n}\n/**\n* A helper utility function that returns the {@link BaseStore} that was set when the graph was initialized\n*\n* @returns a reference to the {@link BaseStore} that was set when the graph was initialized\n*/\nfunction getStore(config) {\n\tconst runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (runConfig === void 0) throw new Error([\"Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.\", \"If you're running `getStore` in such environment, pass the `config` from the node function directly.\"].join(\"\\n\"));\n\treturn runConfig?.store;\n}\n/**\n* A helper utility function that returns the {@link LangGraphRunnableConfig#writer} if \"custom\" stream mode is enabled, otherwise undefined.\n*\n* @returns a reference to the {@link LangGraphRunnableConfig#writer} if \"custom\" stream mode is enabled, otherwise undefined\n*/\nfunction getWriter(config) {\n\tconst runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (runConfig === void 0) throw new Error([\"Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.\", \"If you're running `getWriter` in such environment, pass the `config` from the node function directly.\"].join(\"\\n\"));\n\treturn runConfig?.writer || runConfig?.configurable?.writer;\n}\n/**\n* A helper utility function that returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized.\n*\n* Note: This only works when running in an environment that supports node:async_hooks and AsyncLocalStorage. If you're running this in a\n* web environment, access the LangGraphRunnableConfig from the node function directly.\n*\n* @returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized\n*/\nfunction getConfig() {\n\treturn AsyncLocalStorageProviderSingleton.getRunnableConfig();\n}\n/**\n* A helper utility function that returns the input for the currently executing task\n*\n* @returns the input for the currently executing task\n*/\nfunction getCurrentTaskInput(config) {\n\tconst runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (runConfig === void 0) throw new Error([\"Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.\", \"If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly.\"].join(\"\\n\"));\n\tif (runConfig.configurable?.[CONFIG_KEY_SCRATCHPAD]?.currentTaskInput === void 0) throw new Error(\"BUG: internal scratchpad not initialized.\");\n\treturn runConfig.configurable[CONFIG_KEY_SCRATCHPAD].currentTaskInput;\n}\nfunction recastCheckpointNamespace(namespace) {\n\treturn namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR).filter((part) => !part.match(/^\\d+$/)).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR);\n}\nfunction getParentCheckpointNamespace(namespace) {\n\tconst parts = namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR);\n\twhile (parts.length > 1 && parts[parts.length - 1].match(/^\\d+$/)) parts.pop();\n\treturn parts.slice(0, -1).join(CHECKPOINT_NAMESPACE_SEPARATOR);\n}\n\n//#endregion\nexport { ensureLangGraphConfig, getConfig, getCurrentTaskInput, getParentCheckpointNamespace, getStore, getWriter, recastCheckpointNamespace };\n//# sourceMappingURL=config.js.map","//#region src/hash.ts\nconst n = (n$1) => BigInt(n$1);\nconst view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset);\nconst PRIME32_1 = n(\"0x9E3779B1\");\nconst PRIME32_2 = n(\"0x85EBCA77\");\nconst PRIME32_3 = n(\"0xC2B2AE3D\");\nconst PRIME64_1 = n(\"0x9E3779B185EBCA87\");\nconst PRIME64_2 = n(\"0xC2B2AE3D27D4EB4F\");\nconst PRIME64_3 = n(\"0x165667B19E3779F9\");\nconst PRIME64_4 = n(\"0x85EBCA77C2B2AE63\");\nconst PRIME64_5 = n(\"0x27D4EB2F165667C5\");\nconst PRIME_MX1 = n(\"0x165667919E3779F9\");\nconst PRIME_MX2 = n(\"0x9FB21C651E98DF25\");\nconst hexToUint8Array = (hex) => {\n\tconst strLen = hex.length;\n\tif (strLen % 2 !== 0) throw new Error(\"String should have an even number of characters\");\n\tconst maxLength = strLen / 2;\n\tconst bytes = new Uint8Array(maxLength);\n\tlet read = 0;\n\tlet write = 0;\n\twhile (write < maxLength) {\n\t\tconst slice = hex.slice(read, read += 2);\n\t\tbytes[write] = Number.parseInt(slice, 16);\n\t\twrite += 1;\n\t}\n\treturn view(bytes);\n};\nconst kkey = hexToUint8Array(\"b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e\");\nconst mask128 = (n(1) << n(128)) - n(1);\nconst mask64 = (n(1) << n(64)) - n(1);\nconst mask32 = (n(1) << n(32)) - n(1);\nconst STRIPE_LEN = 64;\nconst ACC_NB = STRIPE_LEN / 8;\nconst _U64 = 8;\nconst _U32 = 4;\nfunction assert(a) {\n\tif (!a) throw new Error(\"Assert failed\");\n}\nfunction bswap64(a) {\n\tconst scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));\n\tscratchbuf.setBigUint64(0, a, true);\n\treturn scratchbuf.getBigUint64(0, false);\n}\nfunction bswap32(input) {\n\tlet a = input;\n\ta = (a & n(65535)) << n(16) | (a & n(4294901760)) >> n(16);\n\ta = (a & n(16711935)) << n(8) | (a & n(4278255360)) >> n(8);\n\treturn a;\n}\nfunction XXH_mult32to64(a, b) {\n\treturn (a & mask32) * (b & mask32) & mask64;\n}\nfunction rotl32(a, b) {\n\treturn (a << b | a >> n(32) - b) & mask32;\n}\nfunction XXH3_accumulate_512(acc, dataView, keyView) {\n\tfor (let i = 0; i < ACC_NB; i += 1) {\n\t\tconst data_val = dataView.getBigUint64(i * 8, true);\n\t\tconst data_key = data_val ^ keyView.getBigUint64(i * 8, true);\n\t\tacc[i ^ 1] += data_val;\n\t\tacc[i] += XXH_mult32to64(data_key, data_key >> n(32));\n\t}\n\treturn acc;\n}\nfunction XXH3_accumulate(acc, dataView, keyView, nbStripes) {\n\tfor (let n$1 = 0; n$1 < nbStripes; n$1 += 1) XXH3_accumulate_512(acc, view(dataView, n$1 * STRIPE_LEN), view(keyView, n$1 * 8));\n\treturn acc;\n}\nfunction XXH3_scrambleAcc(acc, key) {\n\tfor (let i = 0; i < ACC_NB; i += 1) {\n\t\tconst key64 = key.getBigUint64(i * 8, true);\n\t\tlet acc64 = acc[i];\n\t\tacc64 = xorshift64(acc64, n(47));\n\t\tacc64 ^= key64;\n\t\tacc64 *= PRIME32_1;\n\t\tacc[i] = acc64 & mask64;\n\t}\n\treturn acc;\n}\nfunction XXH3_mix2Accs(acc, key) {\n\treturn XXH3_mul128_fold64(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U64, true));\n}\nfunction XXH3_mergeAccs(acc, key, start) {\n\tlet result64 = start;\n\tresult64 += XXH3_mix2Accs(acc.slice(0), view(key, 0 * _U32));\n\tresult64 += XXH3_mix2Accs(acc.slice(2), view(key, 4 * _U32));\n\tresult64 += XXH3_mix2Accs(acc.slice(4), view(key, 8 * _U32));\n\tresult64 += XXH3_mix2Accs(acc.slice(6), view(key, 12 * _U32));\n\treturn XXH3_avalanche(result64 & mask64);\n}\nfunction XXH3_hashLong(input, data, secret, f_acc, f_scramble) {\n\tlet acc = input;\n\tconst nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN) / 8);\n\tconst block_len = STRIPE_LEN * nbStripesPerBlock;\n\tconst nb_blocks = Math.floor((data.byteLength - 1) / block_len);\n\tfor (let n$1 = 0; n$1 < nb_blocks; n$1 += 1) {\n\t\tacc = XXH3_accumulate(acc, view(data, n$1 * block_len), secret, nbStripesPerBlock);\n\t\tacc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN));\n\t}\n\t{\n\t\tconst nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN);\n\t\tacc = XXH3_accumulate(acc, view(data, nb_blocks * block_len), secret, nbStripes);\n\t\tacc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN), view(secret, secret.byteLength - STRIPE_LEN - 7));\n\t}\n\treturn acc;\n}\nfunction XXH3_hashLong_128b(data, secret) {\n\tlet acc = new BigUint64Array([\n\t\tPRIME32_3,\n\t\tPRIME64_1,\n\t\tPRIME64_2,\n\t\tPRIME64_3,\n\t\tPRIME64_4,\n\t\tPRIME32_2,\n\t\tPRIME64_5,\n\t\tPRIME32_1\n\t]);\n\tassert(data.byteLength > 128);\n\tacc = XXH3_hashLong(acc, data, secret, XXH3_accumulate_512, XXH3_scrambleAcc);\n\tassert(acc.length * 8 === 64);\n\t{\n\t\tconst low64 = XXH3_mergeAccs(acc, view(secret, 11), n(data.byteLength) * PRIME64_1 & mask64);\n\t\tconst high64 = XXH3_mergeAccs(acc, view(secret, secret.byteLength - STRIPE_LEN - 11), ~(n(data.byteLength) * PRIME64_2) & mask64);\n\t\treturn high64 << n(64) | low64;\n\t}\n}\nfunction XXH3_mul128_fold64(a, b) {\n\tconst lll = a * b & mask128;\n\treturn lll & mask64 ^ lll >> n(64);\n}\nfunction XXH3_mix16B(dataView, keyView, seed) {\n\treturn XXH3_mul128_fold64((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask64, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask64);\n}\nfunction XXH3_mix32B(acc, data1, data2, key, seed) {\n\tlet accl = acc & mask64;\n\tlet acch = acc >> n(64) & mask64;\n\taccl += XXH3_mix16B(data1, key, seed);\n\taccl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true);\n\taccl &= mask64;\n\tacch += XXH3_mix16B(data2, view(key, 16), seed);\n\tacch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true);\n\tacch &= mask64;\n\treturn acch << n(64) | accl;\n}\nfunction XXH3_avalanche(input) {\n\tlet h64 = input;\n\th64 ^= h64 >> n(37);\n\th64 *= PRIME_MX1;\n\th64 &= mask64;\n\th64 ^= h64 >> n(32);\n\treturn h64;\n}\nfunction XXH3_avalanche64(input) {\n\tlet h64 = input;\n\th64 ^= h64 >> n(33);\n\th64 *= PRIME64_2;\n\th64 &= mask64;\n\th64 ^= h64 >> n(29);\n\th64 *= PRIME64_3;\n\th64 &= mask64;\n\th64 ^= h64 >> n(32);\n\treturn h64;\n}\nfunction XXH3_len_1to3_128b(data, key32, seed) {\n\tconst len = data.byteLength;\n\tassert(len > 0 && len <= 3);\n\tconst combined = n(data.getUint8(len - 1)) | n(len << 8) | n(data.getUint8(0) << 16) | n(data.getUint8(len >> 1) << 24);\n\tconst blow = (n(key32.getUint32(0, true)) ^ n(key32.getUint32(4, true))) + seed;\n\tconst low = (combined ^ blow) & mask64;\n\tconst bhigh = (n(key32.getUint32(8, true)) ^ n(key32.getUint32(12, true))) - seed;\n\tconst high = (rotl32(bswap32(combined), n(13)) ^ bhigh) & mask64;\n\treturn (XXH3_avalanche64(high) & mask64) << n(64) | XXH3_avalanche64(low);\n}\nfunction xorshift64(b, shift) {\n\treturn b ^ b >> shift;\n}\nfunction XXH3_len_4to8_128b(data, key32, seed) {\n\tconst len = data.byteLength;\n\tassert(len >= 4 && len <= 8);\n\t{\n\t\tconst l1 = data.getUint32(0, true);\n\t\tconst l2 = data.getUint32(len - 4, true);\n\t\tconst l64 = n(l1) | n(l2) << n(32);\n\t\tconst bitflip = (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask64;\n\t\tconst keyed = l64 ^ bitflip;\n\t\tlet m128 = keyed * (PRIME64_1 + (n(len) << n(2))) & mask128;\n\t\tm128 += (m128 & mask64) << n(65);\n\t\tm128 &= mask128;\n\t\tm128 ^= m128 >> n(67);\n\t\treturn xorshift64(xorshift64(m128 & mask64, n(35)) * PRIME_MX2 & mask64, n(28)) | XXH3_avalanche(m128 >> n(64)) << n(64);\n\t}\n}\nfunction XXH3_len_9to16_128b(data, key64, seed) {\n\tconst len = data.byteLength;\n\tassert(len >= 9 && len <= 16);\n\t{\n\t\tconst bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask64;\n\t\tconst bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask64;\n\t\tconst ll1 = data.getBigUint64(0, true);\n\t\tlet ll2 = data.getBigUint64(len - 8, true);\n\t\tlet m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_1;\n\t\tconst m128_l = (m128 & mask64) + (n(len - 1) << n(54));\n\t\tm128 = m128 & (mask128 ^ mask64) | m128_l;\n\t\tll2 ^= bitfliph;\n\t\tm128 += ll2 + (ll2 & mask32) * (PRIME32_2 - n(1)) << n(64);\n\t\tm128 &= mask128;\n\t\tm128 ^= bswap64(m128 >> n(64));\n\t\tlet h128 = (m128 & mask64) * PRIME64_2;\n\t\th128 += (m128 >> n(64)) * PRIME64_2 << n(64);\n\t\th128 &= mask128;\n\t\treturn XXH3_avalanche(h128 & mask64) | XXH3_avalanche(h128 >> n(64)) << n(64);\n\t}\n}\nfunction XXH3_len_0to16_128b(data, seed) {\n\tconst len = data.byteLength;\n\tassert(len <= 16);\n\tif (len > 8) return XXH3_len_9to16_128b(data, kkey, seed);\n\tif (len >= 4) return XXH3_len_4to8_128b(data, kkey, seed);\n\tif (len > 0) return XXH3_len_1to3_128b(data, kkey, seed);\n\treturn XXH3_avalanche64(seed ^ kkey.getBigUint64(64, true) ^ kkey.getBigUint64(72, true)) | XXH3_avalanche64(seed ^ kkey.getBigUint64(80, true) ^ kkey.getBigUint64(88, true)) << n(64);\n}\nfunction inv64(x) {\n\treturn ~x + n(1) & mask64;\n}\nfunction XXH3_len_17to128_128b(data, secret, seed) {\n\tlet acc = n(data.byteLength) * PRIME64_1 & mask64;\n\tlet i = n(data.byteLength - 1) / n(32);\n\twhile (i >= 0) {\n\t\tconst ni = Number(i);\n\t\tacc = XXH3_mix32B(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed);\n\t\ti -= n(1);\n\t}\n\tlet h128l = acc + (acc >> n(64)) & mask64;\n\th128l = XXH3_avalanche(h128l);\n\tlet h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2;\n\th128h &= mask64;\n\th128h = inv64(XXH3_avalanche(h128h));\n\treturn h128l | h128h << n(64);\n}\nfunction XXH3_len_129to240_128b(data, secret, seed) {\n\tlet acc = n(data.byteLength) * PRIME64_1 & mask64;\n\tfor (let i = 32; i < 160; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed);\n\tacc = XXH3_avalanche(acc & mask64) | XXH3_avalanche(acc >> n(64)) << n(64);\n\tfor (let i = 160; i <= data.byteLength; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed);\n\tacc = XXH3_mix32B(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv64(seed));\n\tlet h128l = acc + (acc >> n(64)) & mask64;\n\th128l = XXH3_avalanche(h128l);\n\tlet h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2;\n\th128h &= mask64;\n\th128h = inv64(XXH3_avalanche(h128h));\n\treturn h128l | h128h << n(64);\n}\nfunction XXH3(input, seed = n(0)) {\n\tconst encoder = new TextEncoder();\n\tconst data = view(typeof input === \"string\" ? encoder.encode(input) : input);\n\tconst len = data.byteLength;\n\tconst hexDigest = (data$1) => data$1.toString(16).padStart(32, \"0\");\n\tif (len <= 16) return hexDigest(XXH3_len_0to16_128b(data, seed));\n\tif (len <= 128) return hexDigest(XXH3_len_17to128_128b(data, kkey, seed));\n\tif (len <= 240) return hexDigest(XXH3_len_129to240_128b(data, kkey, seed));\n\treturn hexDigest(XXH3_hashLong_128b(data, kkey));\n}\nfunction isXXH3(value) {\n\treturn /^[0-9a-f]{32}$/.test(value);\n}\n\n//#endregion\nexport { XXH3, isXXH3 };\n//# sourceMappingURL=hash.js.map","import { GraphInterrupt, GraphValueError } from \"./errors.js\";\nimport { CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_CHECKPOINT_NS, CONFIG_KEY_SCRATCHPAD, CONFIG_KEY_SEND, RESUME } from \"./constants.js\";\nimport { XXH3 } from \"./hash.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\n\n//#region src/interrupt.ts\n/**\n* Interrupts the execution of a graph node.\n* This function can be used to pause execution of a node, and return the value of the `resume`\n* input when the graph is re-invoked using `Command`.\n* Multiple interrupts can be called within a single node, and each will be handled sequentially.\n*\n* When an interrupt is called:\n* 1. If there's a `resume` value available (from a previous `Command`), it returns that value.\n* 2. Otherwise, it throws a `GraphInterrupt` with the provided value\n* 3. The graph can be resumed by passing a `Command` with a `resume` value\n*\n* Because the `interrupt` function propagates by throwing a special `GraphInterrupt` error,\n* you should avoid using `try/catch` blocks around the `interrupt` function,\n* or if you do, ensure that the `GraphInterrupt` error is thrown again within your `catch` block.\n*\n* @param value - The value to include in the interrupt. This will be available in task.interrupts[].value\n* @returns The `resume` value provided when the graph is re-invoked with a Command\n*\n* @example\n* ```typescript\n* // Define a node that uses multiple interrupts\n* const nodeWithInterrupts = () => {\n* // First interrupt - will pause execution and include {value: 1} in task values\n* const answer1 = interrupt({ value: 1 });\n*\n* // Second interrupt - only called after first interrupt is resumed\n* const answer2 = interrupt({ value: 2 });\n*\n* // Use the resume values\n* return { myKey: answer1 + \" \" + answer2 };\n* };\n*\n* // Resume the graph after first interrupt\n* await graph.stream(new Command({ resume: \"answer 1\" }));\n*\n* // Resume the graph after second interrupt\n* await graph.stream(new Command({ resume: \"answer 2\" }));\n* // Final result: { myKey: \"answer 1 answer 2\" }\n* ```\n*\n* @throws {Error} If called outside the context of a graph\n* @throws {GraphInterrupt} When no resume value is available\n*/\nfunction interrupt(value) {\n\tconst config = AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (!config) throw new Error(\"Called interrupt() outside the context of a graph.\");\n\tconst conf = config.configurable;\n\tif (!conf) throw new Error(\"No configurable found in config\");\n\tconst checkpointer = conf[CONFIG_KEY_CHECKPOINTER];\n\tif (!checkpointer) throw new GraphValueError(\"No checkpointer set\", { lc_error_code: \"MISSING_CHECKPOINTER\" });\n\tconst scratchpad = conf[CONFIG_KEY_SCRATCHPAD];\n\tscratchpad.interruptCounter += 1;\n\tconst idx = scratchpad.interruptCounter;\n\tif (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) {\n\t\tconf[CONFIG_KEY_SEND]?.([[RESUME, scratchpad.resume]]);\n\t\treturn scratchpad.resume[idx];\n\t}\n\tif (scratchpad.nullResume !== void 0) {\n\t\tif (scratchpad.resume.length !== idx) throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`);\n\t\tconst v = scratchpad.consumeNullResume();\n\t\tscratchpad.resume.push(v);\n\t\tconf[CONFIG_KEY_SEND]?.([[RESUME, scratchpad.resume]]);\n\t\treturn v;\n\t}\n\tconst ns = conf[CONFIG_KEY_CHECKPOINT_NS]?.split(CHECKPOINT_NAMESPACE_SEPARATOR);\n\tconst id = ns ? XXH3(ns.join(CHECKPOINT_NAMESPACE_SEPARATOR)) : void 0;\n\tthrow new GraphInterrupt([{\n\t\tid,\n\t\tvalue\n\t}]);\n}\n\n//#endregion\nexport { interrupt };\n//# sourceMappingURL=interrupt.js.map","import { ensureLangGraphConfig } from \"./pregel/utils/config.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { Runnable, mergeConfigs, patchConfig } from \"@langchain/core/runnables\";\n\n//#region src/utils.ts\nvar RunnableCallable = class extends Runnable {\n\tlc_namespace = [\"langgraph\"];\n\tfunc;\n\ttags;\n\tconfig;\n\ttrace = true;\n\trecurse = true;\n\tconstructor(fields) {\n\t\tsuper();\n\t\tthis.name = fields.name ?? fields.func.name;\n\t\tthis.func = fields.func;\n\t\tthis.config = fields.tags ? { tags: fields.tags } : void 0;\n\t\tthis.trace = fields.trace ?? this.trace;\n\t\tthis.recurse = fields.recurse ?? this.recurse;\n\t}\n\tasync _tracedInvoke(input, config, runManager) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst childConfig = patchConfig(config, { callbacks: runManager?.getChild() });\n\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst output = await this.func(input, childConfig);\n\t\t\t\t\tresolve(output);\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\tasync invoke(input, options) {\n\t\tlet returnValue;\n\t\tconst config = ensureLangGraphConfig(options);\n\t\tconst mergedConfig = mergeConfigs(this.config, config);\n\t\tif (this.trace) returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig);\n\t\telse returnValue = await AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig));\n\t\tif (Runnable.isRunnable(returnValue) && this.recurse) return await AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig));\n\t\treturn returnValue;\n\t}\n};\nfunction* prefixGenerator(generator, prefix) {\n\tif (prefix === void 0) yield* generator;\n\telse for (const value of generator) yield [prefix, value];\n}\nasync function gatherIterator(i) {\n\tconst out = [];\n\tfor await (const item of await i) out.push(item);\n\treturn out;\n}\nfunction gatherIteratorSync(i) {\n\tconst out = [];\n\tfor (const item of i) out.push(item);\n\treturn out;\n}\nfunction patchConfigurable(config, patch) {\n\tif (!config) return { configurable: patch };\n\telse if (!(\"configurable\" in config)) return {\n\t\t...config,\n\t\tconfigurable: patch\n\t};\n\telse return {\n\t\t...config,\n\t\tconfigurable: {\n\t\t\t...config.configurable,\n\t\t\t...patch\n\t\t}\n\t};\n}\nfunction isAsyncGeneratorFunction(val) {\n\treturn val != null && typeof val === \"function\" && val instanceof Object.getPrototypeOf(async function* () {}).constructor;\n}\nfunction isGeneratorFunction(val) {\n\treturn val != null && typeof val === \"function\" && val instanceof Object.getPrototypeOf(function* () {}).constructor;\n}\n\n//#endregion\nexport { RunnableCallable, gatherIterator, gatherIteratorSync, isAsyncGeneratorFunction, isGeneratorFunction, patchConfigurable, prefixGenerator };\n//# sourceMappingURL=utils.js.map","import { InvalidUpdateError } from \"../errors.js\";\nimport { CONFIG_KEY_SEND, TASKS, _isSend } from \"../constants.js\";\nimport { RunnableCallable } from \"../utils.js\";\nimport { Runnable } from \"@langchain/core/runnables\";\n\n//#region src/pregel/write.ts\nconst SKIP_WRITE = { [Symbol.for(\"LG_SKIP_WRITE\")]: true };\nfunction _isSkipWrite(x) {\n\treturn typeof x === \"object\" && x?.[Symbol.for(\"LG_SKIP_WRITE\")] !== void 0;\n}\nconst PASSTHROUGH = { [Symbol.for(\"LG_PASSTHROUGH\")]: true };\nfunction _isPassthrough(x) {\n\treturn typeof x === \"object\" && x?.[Symbol.for(\"LG_PASSTHROUGH\")] !== void 0;\n}\nconst IS_WRITER = Symbol(\"IS_WRITER\");\n/**\n* Mapping of write channels to Runnables that return the value to be written,\n* or None to skip writing.\n*/\nvar ChannelWrite = class ChannelWrite extends RunnableCallable {\n\twrites;\n\tconstructor(writes, tags) {\n\t\tconst name = `ChannelWrite<${writes.map((packet) => {\n\t\t\tif (_isSend(packet)) return packet.node;\n\t\t\telse if (\"channel\" in packet) return packet.channel;\n\t\t\treturn \"...\";\n\t\t}).join(\",\")}>`;\n\t\tsuper({\n\t\t\twrites,\n\t\t\tname,\n\t\t\ttags,\n\t\t\tfunc: async (input, config) => {\n\t\t\t\treturn this._write(input, config ?? {});\n\t\t\t}\n\t\t});\n\t\tthis.writes = writes;\n\t}\n\tasync _write(input, config) {\n\t\tconst writes = this.writes.map((write) => {\n\t\t\tif (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) return {\n\t\t\t\tmapper: write.mapper,\n\t\t\t\tvalue: input\n\t\t\t};\n\t\t\telse if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) return {\n\t\t\t\tchannel: write.channel,\n\t\t\t\tvalue: input,\n\t\t\t\tskipNone: write.skipNone,\n\t\t\t\tmapper: write.mapper\n\t\t\t};\n\t\t\telse return write;\n\t\t});\n\t\tawait ChannelWrite.doWrite(config, writes);\n\t\treturn input;\n\t}\n\tstatic async doWrite(config, writes) {\n\t\tfor (const w of writes) {\n\t\t\tif (_isChannelWriteEntry(w)) {\n\t\t\t\tif (w.channel === TASKS) throw new InvalidUpdateError(\"Cannot write to the reserved channel TASKS\");\n\t\t\t\tif (_isPassthrough(w.value)) throw new InvalidUpdateError(\"PASSTHROUGH value must be replaced\");\n\t\t\t}\n\t\t\tif (_isChannelWriteTupleEntry(w)) {\n\t\t\t\tif (_isPassthrough(w.value)) throw new InvalidUpdateError(\"PASSTHROUGH value must be replaced\");\n\t\t\t}\n\t\t}\n\t\tconst writeEntries = [];\n\t\tfor (const w of writes) if (_isSend(w)) writeEntries.push([TASKS, w]);\n\t\telse if (_isChannelWriteTupleEntry(w)) {\n\t\t\tconst mappedResult = await w.mapper.invoke(w.value, config);\n\t\t\tif (mappedResult != null && mappedResult.length > 0) writeEntries.push(...mappedResult);\n\t\t} else if (_isChannelWriteEntry(w)) {\n\t\t\tconst mappedValue = w.mapper !== void 0 ? await w.mapper.invoke(w.value, config) : w.value;\n\t\t\tif (_isSkipWrite(mappedValue)) continue;\n\t\t\tif (w.skipNone && mappedValue === void 0) continue;\n\t\t\twriteEntries.push([w.channel, mappedValue]);\n\t\t} else throw new Error(`Invalid write entry: ${JSON.stringify(w)}`);\n\t\tconst write = config.configurable?.[CONFIG_KEY_SEND];\n\t\twrite(writeEntries);\n\t}\n\tstatic isWriter(runnable) {\n\t\treturn runnable instanceof ChannelWrite || IS_WRITER in runnable && !!runnable[IS_WRITER];\n\t}\n\tstatic registerWriter(runnable) {\n\t\treturn Object.defineProperty(runnable, IS_WRITER, { value: true });\n\t}\n};\nfunction _isChannelWriteEntry(x) {\n\treturn x !== void 0 && typeof x.channel === \"string\";\n}\nfunction _isChannelWriteTupleEntry(x) {\n\treturn x !== void 0 && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper);\n}\n\n//#endregion\nexport { ChannelWrite, PASSTHROUGH };\n//# sourceMappingURL=write.js.map","import { CONFIG_KEY_READ } from \"../constants.js\";\nimport { RunnableCallable } from \"../utils.js\";\nimport { ChannelWrite } from \"./write.js\";\nimport { RunnableBinding, RunnablePassthrough, RunnableSequence, _coerceToRunnable } from \"@langchain/core/runnables\";\n\n//#region src/pregel/read.ts\nvar ChannelRead = class ChannelRead extends RunnableCallable {\n\tlc_graph_name = \"ChannelRead\";\n\tchannel;\n\tfresh = false;\n\tmapper;\n\tconstructor(channel, mapper, fresh = false) {\n\t\tsuper({ func: (_, config) => ChannelRead.doRead(config, this.channel, this.fresh, this.mapper) });\n\t\tthis.fresh = fresh;\n\t\tthis.mapper = mapper;\n\t\tthis.channel = channel;\n\t\tthis.name = Array.isArray(channel) ? `ChannelRead<${channel.join(\",\")}>` : `ChannelRead<${channel}>`;\n\t}\n\tstatic doRead(config, channel, fresh, mapper) {\n\t\tconst read = config.configurable?.[CONFIG_KEY_READ];\n\t\tif (!read) throw new Error(\"Runnable is not configured with a read function. Make sure to call in the context of a Pregel process\");\n\t\tif (mapper) return mapper(read(channel, fresh));\n\t\telse return read(channel, fresh);\n\t}\n};\nconst defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough();\nvar PregelNode = class PregelNode extends RunnableBinding {\n\tlc_graph_name = \"PregelNode\";\n\tchannels;\n\ttriggers = [];\n\tmapper;\n\twriters = [];\n\tbound = defaultRunnableBound;\n\tkwargs = {};\n\tmetadata = {};\n\ttags = [];\n\tretryPolicy;\n\tcachePolicy;\n\tsubgraphs;\n\tends;\n\tconstructor(fields) {\n\t\tconst { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields;\n\t\tconst mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []];\n\t\tsuper({\n\t\t\t...fields,\n\t\t\tbound: fields.bound ?? defaultRunnableBound,\n\t\t\tconfig: {\n\t\t\t\t...fields.config ? fields.config : {},\n\t\t\t\ttags: mergedTags\n\t\t\t}\n\t\t});\n\t\tthis.channels = channels;\n\t\tthis.triggers = triggers;\n\t\tthis.mapper = mapper;\n\t\tthis.writers = writers ?? this.writers;\n\t\tthis.bound = bound ?? this.bound;\n\t\tthis.kwargs = kwargs ?? this.kwargs;\n\t\tthis.metadata = metadata ?? this.metadata;\n\t\tthis.tags = mergedTags;\n\t\tthis.retryPolicy = retryPolicy;\n\t\tthis.cachePolicy = cachePolicy;\n\t\tthis.subgraphs = subgraphs;\n\t\tthis.ends = ends;\n\t}\n\tgetWriters() {\n\t\tconst newWriters = [...this.writers];\n\t\twhile (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) {\n\t\t\tconst endWriters = newWriters.slice(-2);\n\t\t\tconst combinedWrites = endWriters[0].writes.concat(endWriters[1].writes);\n\t\t\tnewWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags);\n\t\t\tnewWriters.pop();\n\t\t}\n\t\treturn newWriters;\n\t}\n\tgetNode() {\n\t\tconst writers = this.getWriters();\n\t\tif (this.bound === defaultRunnableBound && writers.length === 0) return void 0;\n\t\telse if (this.bound === defaultRunnableBound && writers.length === 1) return writers[0];\n\t\telse if (this.bound === defaultRunnableBound) return new RunnableSequence({\n\t\t\tfirst: writers[0],\n\t\t\tmiddle: writers.slice(1, writers.length - 1),\n\t\t\tlast: writers[writers.length - 1],\n\t\t\tomitSequenceTags: true\n\t\t});\n\t\telse if (writers.length > 0) return new RunnableSequence({\n\t\t\tfirst: this.bound,\n\t\t\tmiddle: writers.slice(0, writers.length - 1),\n\t\t\tlast: writers[writers.length - 1],\n\t\t\tomitSequenceTags: true\n\t\t});\n\t\telse return this.bound;\n\t}\n\tjoin(channels) {\n\t\tif (!Array.isArray(channels)) throw new Error(\"channels must be a list\");\n\t\tif (typeof this.channels !== \"object\") throw new Error(\"all channels must be named when using .join()\");\n\t\treturn new PregelNode({\n\t\t\tchannels: {\n\t\t\t\t...this.channels,\n\t\t\t\t...Object.fromEntries(channels.map((chan) => [chan, chan]))\n\t\t\t},\n\t\t\ttriggers: this.triggers,\n\t\t\tmapper: this.mapper,\n\t\t\twriters: this.writers,\n\t\t\tbound: this.bound,\n\t\t\tkwargs: this.kwargs,\n\t\t\tconfig: this.config,\n\t\t\tretryPolicy: this.retryPolicy,\n\t\t\tcachePolicy: this.cachePolicy\n\t\t});\n\t}\n\tpipe(coerceable) {\n\t\tif (ChannelWrite.isWriter(coerceable)) return new PregelNode({\n\t\t\tchannels: this.channels,\n\t\t\ttriggers: this.triggers,\n\t\t\tmapper: this.mapper,\n\t\t\twriters: [...this.writers, coerceable],\n\t\t\tbound: this.bound,\n\t\t\tconfig: this.config,\n\t\t\tkwargs: this.kwargs,\n\t\t\tretryPolicy: this.retryPolicy,\n\t\t\tcachePolicy: this.cachePolicy\n\t\t});\n\t\telse if (this.bound === defaultRunnableBound) return new PregelNode({\n\t\t\tchannels: this.channels,\n\t\t\ttriggers: this.triggers,\n\t\t\tmapper: this.mapper,\n\t\t\twriters: this.writers,\n\t\t\tbound: _coerceToRunnable(coerceable),\n\t\t\tconfig: this.config,\n\t\t\tkwargs: this.kwargs,\n\t\t\tretryPolicy: this.retryPolicy,\n\t\t\tcachePolicy: this.cachePolicy\n\t\t});\n\t\telse return new PregelNode({\n\t\t\tchannels: this.channels,\n\t\t\ttriggers: this.triggers,\n\t\t\tmapper: this.mapper,\n\t\t\twriters: this.writers,\n\t\t\tbound: this.bound.pipe(coerceable),\n\t\t\tconfig: this.config,\n\t\t\tkwargs: this.kwargs,\n\t\t\tretryPolicy: this.retryPolicy,\n\t\t\tcachePolicy: this.cachePolicy\n\t\t});\n\t}\n};\n\n//#endregion\nexport { ChannelRead, PregelNode };\n//# sourceMappingURL=read.js.map","//#region src/pregel/utils/subgraph.ts\nfunction isRunnableSequence(x) {\n\treturn \"steps\" in x && Array.isArray(x.steps);\n}\nfunction isPregelLike(x) {\n\treturn \"lg_is_pregel\" in x && x.lg_is_pregel === true;\n}\nfunction findSubgraphPregel(candidate) {\n\tconst candidates = [candidate];\n\tfor (const candidate$1 of candidates) if (isPregelLike(candidate$1)) return candidate$1;\n\telse if (isRunnableSequence(candidate$1)) candidates.push(...candidate$1.steps);\n\treturn void 0;\n}\n\n//#endregion\nexport { findSubgraphPregel, isPregelLike };\n//# sourceMappingURL=subgraph.js.map","import { EmptyChannelError, InvalidUpdateError } from \"../errors.js\";\nimport { Command, ERROR, INTERRUPT, NULL_TASK_ID, RESUME, RETURN, TAG_HIDDEN, TASKS, _isSend } from \"../constants.js\";\nimport { isXXH3 } from \"../hash.js\";\n\n//#region src/pregel/io.ts\nfunction readChannel(channels, chan, catchErrors = true, returnException = false) {\n\ttry {\n\t\treturn channels[chan].get();\n\t} catch (e) {\n\t\tif (e.name === EmptyChannelError.unminifiable_name) {\n\t\t\tif (returnException) return e;\n\t\t\telse if (catchErrors) return null;\n\t\t}\n\t\tthrow e;\n\t}\n}\nfunction readChannels(channels, select, skipEmpty = true) {\n\tif (Array.isArray(select)) {\n\t\tconst values = {};\n\t\tfor (const k of select) try {\n\t\t\tvalues[k] = readChannel(channels, k, !skipEmpty);\n\t\t} catch (e) {\n\t\t\tif (e.name === EmptyChannelError.unminifiable_name) continue;\n\t\t}\n\t\treturn values;\n\t} else return readChannel(channels, select);\n}\n/**\n* Map input chunk to a sequence of pending writes in the form (channel, value).\n*/\nfunction* mapCommand(cmd, pendingWrites) {\n\tif (cmd.graph === Command.PARENT) throw new InvalidUpdateError(\"There is no parent graph.\");\n\tif (cmd.goto) {\n\t\tlet sends;\n\t\tif (Array.isArray(cmd.goto)) sends = cmd.goto;\n\t\telse sends = [cmd.goto];\n\t\tfor (const send of sends) if (_isSend(send)) yield [\n\t\t\tNULL_TASK_ID,\n\t\t\tTASKS,\n\t\t\tsend\n\t\t];\n\t\telse if (typeof send === \"string\") yield [\n\t\t\tNULL_TASK_ID,\n\t\t\t`branch:to:${send}`,\n\t\t\t\"__start__\"\n\t\t];\n\t\telse throw new Error(`In Command.send, expected Send or string, got ${typeof send}`);\n\t}\n\tif (cmd.resume) if (typeof cmd.resume === \"object\" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) for (const [tid, resume] of Object.entries(cmd.resume)) {\n\t\tconst existing = pendingWrites.filter((w) => w[0] === tid && w[1] === RESUME).map((w) => w[2]).slice(0, 1) ?? [];\n\t\texisting.push(resume);\n\t\tyield [\n\t\t\ttid,\n\t\t\tRESUME,\n\t\t\texisting\n\t\t];\n\t}\n\telse yield [\n\t\tNULL_TASK_ID,\n\t\tRESUME,\n\t\tcmd.resume\n\t];\n\tif (cmd.update) {\n\t\tif (typeof cmd.update !== \"object\" || !cmd.update) throw new Error(\"Expected cmd.update to be a dict mapping channel names to update values\");\n\t\tif (Array.isArray(cmd.update)) for (const [k, v] of cmd.update) yield [\n\t\t\tNULL_TASK_ID,\n\t\t\tk,\n\t\t\tv\n\t\t];\n\t\telse for (const [k, v] of Object.entries(cmd.update)) yield [\n\t\t\tNULL_TASK_ID,\n\t\t\tk,\n\t\t\tv\n\t\t];\n\t}\n}\n/**\n* Map input chunk to a sequence of pending writes in the form [channel, value].\n*/\nfunction* mapInput(inputChannels, chunk) {\n\tif (chunk !== void 0 && chunk !== null) if (Array.isArray(inputChannels) && typeof chunk === \"object\" && !Array.isArray(chunk)) {\n\t\tfor (const k in chunk) if (inputChannels.includes(k)) yield [k, chunk[k]];\n\t} else if (Array.isArray(inputChannels)) throw new Error(`Input chunk must be an object when \"inputChannels\" is an array`);\n\telse yield [inputChannels, chunk];\n}\n/**\n* Map pending writes (a sequence of tuples (channel, value)) to output chunk.\n*/\nfunction* mapOutputValues(outputChannels, pendingWrites, channels) {\n\tif (Array.isArray(outputChannels)) {\n\t\tif (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) yield readChannels(channels, outputChannels);\n\t} else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) yield readChannel(channels, outputChannels);\n}\n/**\n* Map pending writes (a sequence of tuples (channel, value)) to output chunk.\n* @internal\n*\n* @param outputChannels - The channels to output.\n* @param tasks - The tasks to output.\n* @param cached - Whether the output is cached.\n*\n* @returns A generator that yields the output chunk (if any).\n*/\nfunction* mapOutputUpdates(outputChannels, tasks, cached) {\n\tconst outputTasks = tasks.filter(([task, ww]) => {\n\t\treturn (task.config === void 0 || !task.config.tags?.includes(TAG_HIDDEN)) && ww[0][0] !== ERROR && ww[0][0] !== INTERRUPT;\n\t});\n\tif (!outputTasks.length) return;\n\tlet updated;\n\tif (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === RETURN))) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value]));\n\telse if (!Array.isArray(outputChannels)) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value]));\n\telse updated = outputTasks.flatMap(([task]) => {\n\t\tconst { writes } = task;\n\t\tconst counts = {};\n\t\tfor (const [chan] of writes) if (outputChannels.includes(chan)) counts[chan] = (counts[chan] || 0) + 1;\n\t\tif (Object.values(counts).some((count) => count > 1)) return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]);\n\t\telse return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]];\n\t});\n\tconst grouped = {};\n\tfor (const [node, value] of updated) {\n\t\tif (!(node in grouped)) grouped[node] = [];\n\t\tgrouped[node].push(value);\n\t}\n\tconst flattened = {};\n\tfor (const node in grouped) if (grouped[node].length === 1) {\n\t\tconst [write] = grouped[node];\n\t\tflattened[node] = write;\n\t} else flattened[node] = grouped[node];\n\tif (cached) flattened[\"__metadata__\"] = { cached };\n\tyield flattened;\n}\n\n//#endregion\nexport { mapCommand, mapInput, mapOutputUpdates, mapOutputValues, readChannel, readChannels };\n//# sourceMappingURL=io.js.map","import { CONFIG_KEY_CHECKPOINT_MAP, START } from \"../../constants.js\";\n\n//#region src/pregel/utils/index.ts\nfunction getNullChannelVersion(currentVersions) {\n\tconst startVersion = typeof currentVersions[START];\n\tif (startVersion === \"number\") return 0;\n\tif (startVersion === \"string\") return \"\";\n\tfor (const key in currentVersions) {\n\t\tif (!Object.prototype.hasOwnProperty.call(currentVersions, key)) continue;\n\t\tconst versionType = typeof currentVersions[key];\n\t\tif (versionType === \"number\") return 0;\n\t\tif (versionType === \"string\") return \"\";\n\t\tbreak;\n\t}\n\treturn void 0;\n}\nfunction getNewChannelVersions(previousVersions, currentVersions) {\n\tif (Object.keys(previousVersions).length > 0) {\n\t\tconst nullVersion = getNullChannelVersion(currentVersions);\n\t\treturn Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion)));\n\t} else return currentVersions;\n}\nfunction _coerceToDict(value, defaultKey) {\n\treturn value && !Array.isArray(value) && !(value instanceof Date) && typeof value === \"object\" ? value : { [defaultKey]: value };\n}\nfunction patchConfigurable(config, patch) {\n\tif (config === null) return { configurable: patch };\n\telse if (config?.configurable === void 0) return {\n\t\t...config,\n\t\tconfigurable: patch\n\t};\n\telse return {\n\t\t...config,\n\t\tconfigurable: {\n\t\t\t...config.configurable,\n\t\t\t...patch\n\t\t}\n\t};\n}\nfunction patchCheckpointMap(config, metadata) {\n\tconst parents = metadata?.parents ?? {};\n\tif (Object.keys(parents).length > 0) return patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_MAP]: {\n\t\t...parents,\n\t\t[config.configurable?.checkpoint_ns ?? \"\"]: config.configurable?.checkpoint_id\n\t} });\n\telse return config;\n}\n/**\n* Combine multiple abort signals into a single abort signal.\n* @param signals - The abort signals to combine.\n* @returns A combined abort signal and a dispose function to remove the abort listener if unused.\n*/\nfunction combineAbortSignals(...x) {\n\tconst signals = [...new Set(x.filter(Boolean))];\n\tif (signals.length === 0) return {\n\t\tsignal: void 0,\n\t\tdispose: void 0\n\t};\n\tif (signals.length === 1) return {\n\t\tsignal: signals[0],\n\t\tdispose: void 0\n\t};\n\tconst combinedController = new AbortController();\n\tconst listener = () => {\n\t\tconst reason = signals.find((s) => s.aborted)?.reason;\n\t\tcombinedController.abort(reason);\n\t\tsignals.forEach((s) => s.removeEventListener(\"abort\", listener));\n\t};\n\tsignals.forEach((s) => s.addEventListener(\"abort\", listener, { once: true }));\n\tconst hasAlreadyAbortedSignal = signals.find((s) => s.aborted);\n\tif (hasAlreadyAbortedSignal) combinedController.abort(hasAlreadyAbortedSignal.reason);\n\treturn {\n\t\tsignal: combinedController.signal,\n\t\tdispose: () => {\n\t\t\tsignals.forEach((s) => s.removeEventListener(\"abort\", listener));\n\t\t}\n\t};\n}\n/**\n* Combine multiple callbacks into a single callback.\n* @param callback1 - The first callback to combine.\n* @param callback2 - The second callback to combine.\n* @returns A single callback that is a combination of the input callbacks.\n*/\nconst combineCallbacks = (callback1, callback2) => {\n\tif (!callback1 && !callback2) return void 0;\n\tif (!callback1) return callback2;\n\tif (!callback2) return callback1;\n\tif (Array.isArray(callback1) && Array.isArray(callback2)) return [...callback1, ...callback2];\n\tif (Array.isArray(callback1)) return [...callback1, callback2];\n\tif (Array.isArray(callback2)) return [callback1, ...callback2];\n\treturn [callback1, callback2];\n};\n\n//#endregion\nexport { _coerceToDict, combineAbortSignals, combineCallbacks, getNewChannelVersions, getNullChannelVersion, patchCheckpointMap, patchConfigurable };\n//# sourceMappingURL=index.js.map","//#region src/pregel/types.ts\nvar Call = class {\n\tfunc;\n\tname;\n\tinput;\n\tretry;\n\tcache;\n\tcallbacks;\n\t__lg_type = \"call\";\n\tconstructor({ func, name, input, retry, cache, callbacks }) {\n\t\tthis.func = func;\n\t\tthis.name = name;\n\t\tthis.input = input;\n\t\tthis.retry = retry;\n\t\tthis.cache = cache;\n\t\tthis.callbacks = callbacks;\n\t}\n};\nfunction isCall(value) {\n\treturn typeof value === \"object\" && value !== null && \"__lg_type\" in value && value.__lg_type === \"call\";\n}\n\n//#endregion\nexport { Call, isCall };\n//# sourceMappingURL=types.js.map","import { CONFIG_KEY_CALL, RETURN, TAG_HIDDEN } from \"../constants.js\";\nimport { RunnableCallable } from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"./write.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { RunnableSequence } from \"@langchain/core/runnables\";\n\n//#region src/pregel/call.ts\n/**\n* Wraps a user function in a Runnable that writes the returned value to the RETURN channel.\n*/\nfunction getRunnableForFunc(name, func) {\n\tconst run = new RunnableCallable({\n\t\tfunc: (input) => func(...input),\n\t\tname,\n\t\ttrace: false,\n\t\trecurse: false\n\t});\n\treturn new RunnableSequence({\n\t\tname,\n\t\tfirst: run,\n\t\tlast: new ChannelWrite([{\n\t\t\tchannel: RETURN,\n\t\t\tvalue: PASSTHROUGH\n\t\t}], [TAG_HIDDEN])\n\t});\n}\nfunction getRunnableForEntrypoint(name, func) {\n\tconst run = new RunnableCallable({\n\t\tfunc: (input, config) => {\n\t\t\treturn func(input, config);\n\t\t},\n\t\tname,\n\t\ttrace: false,\n\t\trecurse: false\n\t});\n\treturn run;\n}\nfunction call({ func, name, cache, retry }, ...args) {\n\tconst config = AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (typeof config.configurable?.[CONFIG_KEY_CALL] === \"function\") return config.configurable[CONFIG_KEY_CALL](func, name, args, {\n\t\tretry,\n\t\tcache,\n\t\tcallbacks: config.callbacks\n\t});\n\tthrow new Error(\"Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function.\");\n}\n\n//#endregion\nexport { call, getRunnableForEntrypoint, getRunnableForFunc };\n//# sourceMappingURL=call.js.map","import { EmptyChannelError, InvalidUpdateError } from \"../errors.js\";\nimport { createCheckpoint, emptyChannels, getOnlyChannels } from \"../channels/base.js\";\nimport { CACHE_NS_WRITES, CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_CHECKPOINT_MAP, CONFIG_KEY_PREVIOUS_STATE, CONFIG_KEY_READ, CONFIG_KEY_RESUME_MAP, CONFIG_KEY_SCRATCHPAD, CONFIG_KEY_SEND, CONFIG_KEY_TASK_ID, ERROR, INTERRUPT, NO_WRITES, NULL_TASK_ID, PREVIOUS, PULL, PUSH, RESERVED, RESUME, RETURN, START, Send, TAG_HIDDEN, TASKS, _isSend, _isSendInterface } from \"../constants.js\";\nimport { XXH3 } from \"../hash.js\";\nimport { readChannel, readChannels } from \"./io.js\";\nimport { isCall } from \"./types.js\";\nimport { getNullChannelVersion } from \"./utils/index.js\";\nimport { getRunnableForFunc } from \"./call.js\";\nimport { copyCheckpoint, maxChannelVersion, uuid5 } from \"@langchain/langgraph-checkpoint\";\nimport { mergeConfigs, patchConfig } from \"@langchain/core/runnables\";\n\n//#region src/pregel/algo.ts\nconst increment = (current) => {\n\treturn current !== void 0 ? current + 1 : 1;\n};\nfunction triggersNextStep(updatedChannels, triggerToNodes) {\n\tif (triggerToNodes == null) return false;\n\tfor (const chan of updatedChannels) if (triggerToNodes[chan]) return true;\n\treturn false;\n}\nfunction maxChannelMapVersion(channelVersions) {\n\tlet maxVersion;\n\tfor (const chan in channelVersions) {\n\t\tif (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) continue;\n\t\tif (maxVersion == null) maxVersion = channelVersions[chan];\n\t\telse maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]);\n\t}\n\treturn maxVersion;\n}\nfunction shouldInterrupt(checkpoint, interruptNodes, tasks) {\n\tconst nullVersion = getNullChannelVersion(checkpoint.channel_versions);\n\tconst seen = checkpoint.versions_seen[INTERRUPT] ?? {};\n\tlet anyChannelUpdated = false;\n\tif ((checkpoint.channel_versions[START] ?? nullVersion) > (seen[START] ?? nullVersion)) anyChannelUpdated = true;\n\telse for (const chan in checkpoint.channel_versions) {\n\t\tif (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) continue;\n\t\tif (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) {\n\t\t\tanyChannelUpdated = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === \"*\" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name));\n\treturn anyChannelUpdated && anyTriggeredNodeInInterruptNodes;\n}\nfunction _localRead(checkpoint, channels, task, select, fresh = false) {\n\tlet updated = /* @__PURE__ */ new Set();\n\tif (!Array.isArray(select)) {\n\t\tfor (const [c] of task.writes) if (c === select) {\n\t\t\tupdated = new Set([c]);\n\t\t\tbreak;\n\t\t}\n\t\tupdated = updated || /* @__PURE__ */ new Set();\n\t} else updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c)));\n\tlet values;\n\tif (fresh && updated.size > 0) {\n\t\tconst localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k)));\n\t\tconst newCheckpoint = createCheckpoint(checkpoint, localChannels, -1);\n\t\tconst newChannels = emptyChannels(localChannels, newCheckpoint);\n\t\t_applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], void 0, void 0);\n\t\tvalues = readChannels({\n\t\t\t...channels,\n\t\t\t...newChannels\n\t\t}, select);\n\t} else values = readChannels(channels, select);\n\treturn values;\n}\nfunction _localWrite(commit, processes, writes) {\n\tfor (const [chan, value] of writes) if ([PUSH, TASKS].includes(chan) && value != null) {\n\t\tif (!_isSend(value)) throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`);\n\t\tif (!(value.node in processes)) throw new InvalidUpdateError(`Invalid node name \"${value.node}\" in Send packet`);\n\t}\n\tcommit(writes);\n}\nconst IGNORE = new Set([\n\tNO_WRITES,\n\tPUSH,\n\tRESUME,\n\tINTERRUPT,\n\tRETURN,\n\tERROR\n]);\nfunction _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) {\n\ttasks.sort((a, b) => {\n\t\tconst aPath = a.path?.slice(0, 3) || [];\n\t\tconst bPath = b.path?.slice(0, 3) || [];\n\t\tfor (let i = 0; i < Math.min(aPath.length, bPath.length); i += 1) {\n\t\t\tif (aPath[i] < bPath[i]) return -1;\n\t\t\tif (aPath[i] > bPath[i]) return 1;\n\t\t}\n\t\treturn aPath.length - bPath.length;\n\t});\n\tconst bumpStep = tasks.some((task) => task.triggers.length > 0);\n\tconst onlyChannels = getOnlyChannels(channels);\n\tfor (const task of tasks) {\n\t\tcheckpoint.versions_seen[task.name] ??= {};\n\t\tfor (const chan of task.triggers) if (chan in checkpoint.channel_versions) checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan];\n\t}\n\tlet maxVersion = maxChannelMapVersion(checkpoint.channel_versions);\n\tconst channelsToConsume = new Set(tasks.flatMap((task) => task.triggers).filter((chan) => !RESERVED.includes(chan)));\n\tlet usedNewVersion = false;\n\tfor (const chan of channelsToConsume) if (chan in onlyChannels && onlyChannels[chan].consume()) {\n\t\tif (getNextVersion !== void 0) {\n\t\t\tcheckpoint.channel_versions[chan] = getNextVersion(maxVersion);\n\t\t\tusedNewVersion = true;\n\t\t}\n\t}\n\tconst pendingWritesByChannel = {};\n\tfor (const task of tasks) for (const [chan, val] of task.writes) if (IGNORE.has(chan)) {} else if (chan in onlyChannels) {\n\t\tpendingWritesByChannel[chan] ??= [];\n\t\tpendingWritesByChannel[chan].push(val);\n\t}\n\tif (maxVersion != null && getNextVersion != null) maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion;\n\tconst updatedChannels = /* @__PURE__ */ new Set();\n\tfor (const [chan, vals] of Object.entries(pendingWritesByChannel)) if (chan in onlyChannels) {\n\t\tconst channel = onlyChannels[chan];\n\t\tlet updated;\n\t\ttry {\n\t\t\tupdated = channel.update(vals);\n\t\t} catch (e) {\n\t\t\tif (e.name === InvalidUpdateError.unminifiable_name) {\n\t\t\t\tconst wrappedError = new InvalidUpdateError(`Invalid update for channel \"${chan}\" with values ${JSON.stringify(vals)}: ${e.message}`);\n\t\t\t\twrappedError.lc_error_code = e.lc_error_code;\n\t\t\t\tthrow wrappedError;\n\t\t\t} else throw e;\n\t\t}\n\t\tif (updated && getNextVersion !== void 0) {\n\t\t\tcheckpoint.channel_versions[chan] = getNextVersion(maxVersion);\n\t\t\tif (channel.isAvailable()) updatedChannels.add(chan);\n\t\t}\n\t}\n\tif (bumpStep) for (const chan in onlyChannels) {\n\t\tif (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue;\n\t\tconst channel = onlyChannels[chan];\n\t\tif (channel.isAvailable() && !updatedChannels.has(chan)) {\n\t\t\tconst updated = channel.update([]);\n\t\t\tif (updated && getNextVersion !== void 0) {\n\t\t\t\tcheckpoint.channel_versions[chan] = getNextVersion(maxVersion);\n\t\t\t\tif (channel.isAvailable()) updatedChannels.add(chan);\n\t\t\t}\n\t\t}\n\t}\n\tif (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) for (const chan in onlyChannels) {\n\t\tif (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue;\n\t\tconst channel = onlyChannels[chan];\n\t\tif (channel.finish() && getNextVersion !== void 0) {\n\t\t\tcheckpoint.channel_versions[chan] = getNextVersion(maxVersion);\n\t\t\tif (channel.isAvailable()) updatedChannels.add(chan);\n\t\t}\n\t}\n\treturn updatedChannels;\n}\nfunction* candidateNodes(checkpoint, processes, extra) {\n\tif (extra.updatedChannels != null && extra.triggerToNodes != null) {\n\t\tconst triggeredNodes = /* @__PURE__ */ new Set();\n\t\tfor (const channel of extra.updatedChannels) {\n\t\t\tconst nodeIds = extra.triggerToNodes[channel];\n\t\t\tfor (const id of nodeIds ?? []) triggeredNodes.add(id);\n\t\t}\n\t\tyield* [...triggeredNodes].sort();\n\t\treturn;\n\t}\n\tconst isEmptyChannelVersions = (() => {\n\t\tfor (const chan in checkpoint.channel_versions) if (checkpoint.channel_versions[chan] !== null) return false;\n\t\treturn true;\n\t})();\n\tif (isEmptyChannelVersions) return;\n\tfor (const name in processes) {\n\t\tif (!Object.prototype.hasOwnProperty.call(processes, name)) continue;\n\t\tyield name;\n\t}\n}\n/**\n* Prepare the set of tasks that will make up the next Pregel step.\n* This is the union of all PUSH tasks (Sends) and PULL tasks (nodes triggered\n* by edges).\n*/\nfunction _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config, forExecution, extra) {\n\tconst tasks = {};\n\tconst tasksChannel = channels[TASKS];\n\tif (tasksChannel?.isAvailable()) {\n\t\tconst len = tasksChannel.get().length;\n\t\tfor (let i = 0; i < len; i += 1) {\n\t\t\tconst task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config, forExecution, extra);\n\t\t\tif (task !== void 0) tasks[task.id] = task;\n\t\t}\n\t}\n\tfor (const name of candidateNodes(checkpoint, processes, extra)) {\n\t\tconst task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config, forExecution, extra);\n\t\tif (task !== void 0) tasks[task.id] = task;\n\t}\n\treturn tasks;\n}\n/**\n* Prepares a single task for the next Pregel step, given a task path, which\n* uniquely identifies a PUSH or PULL task within the graph.\n*/\nfunction _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config, forExecution, extra) {\n\tconst { step, checkpointer, manager } = extra;\n\tconst configurable = config.configurable ?? {};\n\tconst parentNamespace = configurable.checkpoint_ns ?? \"\";\n\tif (taskPath[0] === PUSH && isCall(taskPath[taskPath.length - 1])) {\n\t\tconst call = taskPath[taskPath.length - 1];\n\t\tconst proc = getRunnableForFunc(call.name, call.func);\n\t\tconst triggers = [PUSH];\n\t\tconst checkpointNamespace = parentNamespace === \"\" ? call.name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${call.name}`;\n\t\tconst id = uuid5(JSON.stringify([\n\t\t\tcheckpointNamespace,\n\t\t\tstep.toString(),\n\t\t\tcall.name,\n\t\t\tPUSH,\n\t\t\ttaskPath[1],\n\t\t\ttaskPath[2]\n\t\t]), checkpoint.id);\n\t\tconst taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${id}`;\n\t\tconst outputTaskPath = [...taskPath.slice(0, 3), true];\n\t\tconst metadata = {\n\t\t\tlanggraph_step: step,\n\t\t\tlanggraph_node: call.name,\n\t\t\tlanggraph_triggers: triggers,\n\t\t\tlanggraph_path: outputTaskPath,\n\t\t\tlanggraph_checkpoint_ns: taskCheckpointNamespace\n\t\t};\n\t\tif (forExecution) {\n\t\t\tconst writes = [];\n\t\t\tconst task = {\n\t\t\t\tname: call.name,\n\t\t\t\tinput: call.input,\n\t\t\t\tproc,\n\t\t\t\twrites,\n\t\t\t\tconfig: patchConfig(mergeConfigs(config, {\n\t\t\t\t\tmetadata,\n\t\t\t\t\tstore: extra.store ?? config.store\n\t\t\t\t}), {\n\t\t\t\t\trunName: call.name,\n\t\t\t\t\tcallbacks: manager?.getChild(`graph:step:${step}`),\n\t\t\t\t\tconfigurable: {\n\t\t\t\t\t\t[CONFIG_KEY_TASK_ID]: id,\n\t\t\t\t\t\t[CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_),\n\t\t\t\t\t\t[CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, {\n\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\twrites,\n\t\t\t\t\t\t\ttriggers,\n\t\t\t\t\t\t\tpath: outputTaskPath\n\t\t\t\t\t\t}, select_, fresh_),\n\t\t\t\t\t\t[CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER],\n\t\t\t\t\t\t[CONFIG_KEY_CHECKPOINT_MAP]: {\n\t\t\t\t\t\t\t...configurable[CONFIG_KEY_CHECKPOINT_MAP],\n\t\t\t\t\t\t\t[parentNamespace]: checkpoint.id\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[CONFIG_KEY_SCRATCHPAD]: _scratchpad({\n\t\t\t\t\t\t\tpendingWrites: pendingWrites ?? [],\n\t\t\t\t\t\t\ttaskId: id,\n\t\t\t\t\t\t\tcurrentTaskInput: call.input,\n\t\t\t\t\t\t\tresumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP],\n\t\t\t\t\t\t\tnamespaceHash: XXH3(taskCheckpointNamespace)\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t[CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS],\n\t\t\t\t\t\tcheckpoint_id: void 0,\n\t\t\t\t\t\tcheckpoint_ns: taskCheckpointNamespace\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\ttriggers,\n\t\t\t\tretry_policy: call.retry,\n\t\t\t\tcache_key: call.cache ? {\n\t\t\t\t\tkey: XXH3((call.cache.keyFunc ?? JSON.stringify)([call.input])),\n\t\t\t\t\tns: [CACHE_NS_WRITES, call.name ?? \"__dynamic__\"],\n\t\t\t\t\tttl: call.cache.ttl\n\t\t\t\t} : void 0,\n\t\t\t\tid,\n\t\t\t\tpath: outputTaskPath,\n\t\t\t\twriters: []\n\t\t\t};\n\t\t\treturn task;\n\t\t} else return {\n\t\t\tid,\n\t\t\tname: call.name,\n\t\t\tinterrupts: [],\n\t\t\tpath: outputTaskPath\n\t\t};\n\t} else if (taskPath[0] === PUSH) {\n\t\tconst index = typeof taskPath[1] === \"number\" ? taskPath[1] : parseInt(taskPath[1], 10);\n\t\tif (!channels[TASKS]?.isAvailable()) return void 0;\n\t\tconst sends = channels[TASKS].get();\n\t\tif (index < 0 || index >= sends.length) return void 0;\n\t\tconst packet = _isSendInterface(sends[index]) && !_isSend(sends[index]) ? new Send(sends[index].node, sends[index].args) : sends[index];\n\t\tif (!_isSendInterface(packet)) {\n\t\t\tconsole.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`);\n\t\t\treturn void 0;\n\t\t}\n\t\tif (!(packet.node in processes)) {\n\t\t\tconsole.warn(`Ignoring unknown node name ${packet.node} in pending sends.`);\n\t\t\treturn void 0;\n\t\t}\n\t\tconst triggers = [PUSH];\n\t\tconst checkpointNamespace = parentNamespace === \"\" ? packet.node : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${packet.node}`;\n\t\tconst taskId = uuid5(JSON.stringify([\n\t\t\tcheckpointNamespace,\n\t\t\tstep.toString(),\n\t\t\tpacket.node,\n\t\t\tPUSH,\n\t\t\tindex.toString()\n\t\t]), checkpoint.id);\n\t\tconst taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`;\n\t\tlet metadata = {\n\t\t\tlanggraph_step: step,\n\t\t\tlanggraph_node: packet.node,\n\t\t\tlanggraph_triggers: triggers,\n\t\t\tlanggraph_path: taskPath.slice(0, 3),\n\t\t\tlanggraph_checkpoint_ns: taskCheckpointNamespace\n\t\t};\n\t\tif (forExecution) {\n\t\t\tconst proc = processes[packet.node];\n\t\t\tconst node = proc.getNode();\n\t\t\tif (node !== void 0) {\n\t\t\t\tif (proc.metadata !== void 0) metadata = {\n\t\t\t\t\t...metadata,\n\t\t\t\t\t...proc.metadata\n\t\t\t\t};\n\t\t\t\tconst writes = [];\n\t\t\t\treturn {\n\t\t\t\t\tname: packet.node,\n\t\t\t\t\tinput: packet.args,\n\t\t\t\t\tproc: node,\n\t\t\t\t\tsubgraphs: proc.subgraphs,\n\t\t\t\t\twrites,\n\t\t\t\t\tconfig: patchConfig(mergeConfigs(config, {\n\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\ttags: proc.tags,\n\t\t\t\t\t\tstore: extra.store ?? config.store\n\t\t\t\t\t}), {\n\t\t\t\t\t\trunName: packet.node,\n\t\t\t\t\t\tcallbacks: manager?.getChild(`graph:step:${step}`),\n\t\t\t\t\t\tconfigurable: {\n\t\t\t\t\t\t\t[CONFIG_KEY_TASK_ID]: taskId,\n\t\t\t\t\t\t\t[CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_),\n\t\t\t\t\t\t\t[CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, {\n\t\t\t\t\t\t\t\tname: packet.node,\n\t\t\t\t\t\t\t\twrites,\n\t\t\t\t\t\t\t\ttriggers,\n\t\t\t\t\t\t\t\tpath: taskPath\n\t\t\t\t\t\t\t}, select_, fresh_),\n\t\t\t\t\t\t\t[CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER],\n\t\t\t\t\t\t\t[CONFIG_KEY_CHECKPOINT_MAP]: {\n\t\t\t\t\t\t\t\t...configurable[CONFIG_KEY_CHECKPOINT_MAP],\n\t\t\t\t\t\t\t\t[parentNamespace]: checkpoint.id\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t[CONFIG_KEY_SCRATCHPAD]: _scratchpad({\n\t\t\t\t\t\t\t\tpendingWrites: pendingWrites ?? [],\n\t\t\t\t\t\t\t\ttaskId,\n\t\t\t\t\t\t\t\tcurrentTaskInput: packet.args,\n\t\t\t\t\t\t\t\tresumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP],\n\t\t\t\t\t\t\t\tnamespaceHash: XXH3(taskCheckpointNamespace)\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t[CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS],\n\t\t\t\t\t\t\tcheckpoint_id: void 0,\n\t\t\t\t\t\t\tcheckpoint_ns: taskCheckpointNamespace\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttriggers,\n\t\t\t\t\tretry_policy: proc.retryPolicy,\n\t\t\t\t\tcache_key: proc.cachePolicy ? {\n\t\t\t\t\t\tkey: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])),\n\t\t\t\t\t\tns: [\n\t\t\t\t\t\t\tCACHE_NS_WRITES,\n\t\t\t\t\t\t\tproc.name ?? \"__dynamic__\",\n\t\t\t\t\t\t\tpacket.node\n\t\t\t\t\t\t],\n\t\t\t\t\t\tttl: proc.cachePolicy.ttl\n\t\t\t\t\t} : void 0,\n\t\t\t\t\tid: taskId,\n\t\t\t\t\tpath: taskPath,\n\t\t\t\t\twriters: proc.getWriters()\n\t\t\t\t};\n\t\t\t}\n\t\t} else return {\n\t\t\tid: taskId,\n\t\t\tname: packet.node,\n\t\t\tinterrupts: [],\n\t\t\tpath: taskPath\n\t\t};\n\t} else if (taskPath[0] === PULL) {\n\t\tconst name = taskPath[1].toString();\n\t\tconst proc = processes[name];\n\t\tif (proc === void 0) return void 0;\n\t\tif (pendingWrites?.length) {\n\t\t\tconst checkpointNamespace = parentNamespace === \"\" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`;\n\t\t\tconst taskId = uuid5(JSON.stringify([\n\t\t\t\tcheckpointNamespace,\n\t\t\t\tstep.toString(),\n\t\t\t\tname,\n\t\t\t\tPULL,\n\t\t\t\tname\n\t\t\t]), checkpoint.id);\n\t\t\tconst hasSuccessfulWrites = pendingWrites.some((w) => w[0] === taskId && w[1] !== ERROR);\n\t\t\tif (hasSuccessfulWrites) return void 0;\n\t\t}\n\t\tconst nullVersion = getNullChannelVersion(checkpoint.channel_versions);\n\t\tif (nullVersion === void 0) return void 0;\n\t\tconst seen = checkpoint.versions_seen[name] ?? {};\n\t\tconst trigger = proc.triggers.find((chan) => {\n\t\t\tif (!channels[chan].isAvailable()) return false;\n\t\t\treturn (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion);\n\t\t});\n\t\tif (trigger !== void 0) {\n\t\t\tconst val = _procInput(proc, channels, forExecution);\n\t\t\tif (val === void 0) return void 0;\n\t\t\tconst checkpointNamespace = parentNamespace === \"\" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`;\n\t\t\tconst taskId = uuid5(JSON.stringify([\n\t\t\t\tcheckpointNamespace,\n\t\t\t\tstep.toString(),\n\t\t\t\tname,\n\t\t\t\tPULL,\n\t\t\t\t[trigger]\n\t\t\t]), checkpoint.id);\n\t\t\tconst taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`;\n\t\t\tlet metadata = {\n\t\t\t\tlanggraph_step: step,\n\t\t\t\tlanggraph_node: name,\n\t\t\t\tlanggraph_triggers: [trigger],\n\t\t\t\tlanggraph_path: taskPath,\n\t\t\t\tlanggraph_checkpoint_ns: taskCheckpointNamespace\n\t\t\t};\n\t\t\tif (forExecution) {\n\t\t\t\tconst node = proc.getNode();\n\t\t\t\tif (node !== void 0) {\n\t\t\t\t\tif (proc.metadata !== void 0) metadata = {\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...proc.metadata\n\t\t\t\t\t};\n\t\t\t\t\tconst writes = [];\n\t\t\t\t\treturn {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tinput: val,\n\t\t\t\t\t\tproc: node,\n\t\t\t\t\t\tsubgraphs: proc.subgraphs,\n\t\t\t\t\t\twrites,\n\t\t\t\t\t\tconfig: patchConfig(mergeConfigs(config, {\n\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t\ttags: proc.tags,\n\t\t\t\t\t\t\tstore: extra.store ?? config.store\n\t\t\t\t\t\t}), {\n\t\t\t\t\t\t\trunName: name,\n\t\t\t\t\t\t\tcallbacks: manager?.getChild(`graph:step:${step}`),\n\t\t\t\t\t\t\tconfigurable: {\n\t\t\t\t\t\t\t\t[CONFIG_KEY_TASK_ID]: taskId,\n\t\t\t\t\t\t\t\t[CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => {\n\t\t\t\t\t\t\t\t\twrites.push(...items);\n\t\t\t\t\t\t\t\t}, processes, writes_),\n\t\t\t\t\t\t\t\t[CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, {\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\twrites,\n\t\t\t\t\t\t\t\t\ttriggers: [trigger],\n\t\t\t\t\t\t\t\t\tpath: taskPath\n\t\t\t\t\t\t\t\t}, select_, fresh_),\n\t\t\t\t\t\t\t\t[CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER],\n\t\t\t\t\t\t\t\t[CONFIG_KEY_CHECKPOINT_MAP]: {\n\t\t\t\t\t\t\t\t\t...configurable[CONFIG_KEY_CHECKPOINT_MAP],\n\t\t\t\t\t\t\t\t\t[parentNamespace]: checkpoint.id\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t[CONFIG_KEY_SCRATCHPAD]: _scratchpad({\n\t\t\t\t\t\t\t\t\tpendingWrites: pendingWrites ?? [],\n\t\t\t\t\t\t\t\t\ttaskId,\n\t\t\t\t\t\t\t\t\tcurrentTaskInput: val,\n\t\t\t\t\t\t\t\t\tresumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP],\n\t\t\t\t\t\t\t\t\tnamespaceHash: XXH3(taskCheckpointNamespace)\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t[CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS],\n\t\t\t\t\t\t\t\tcheckpoint_id: void 0,\n\t\t\t\t\t\t\t\tcheckpoint_ns: taskCheckpointNamespace\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttriggers: [trigger],\n\t\t\t\t\t\tretry_policy: proc.retryPolicy,\n\t\t\t\t\t\tcache_key: proc.cachePolicy ? {\n\t\t\t\t\t\t\tkey: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])),\n\t\t\t\t\t\t\tns: [\n\t\t\t\t\t\t\t\tCACHE_NS_WRITES,\n\t\t\t\t\t\t\t\tproc.name ?? \"__dynamic__\",\n\t\t\t\t\t\t\t\tname\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tttl: proc.cachePolicy.ttl\n\t\t\t\t\t\t} : void 0,\n\t\t\t\t\t\tid: taskId,\n\t\t\t\t\t\tpath: taskPath,\n\t\t\t\t\t\twriters: proc.getWriters()\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else return {\n\t\t\t\tid: taskId,\n\t\t\t\tname,\n\t\t\t\tinterrupts: [],\n\t\t\t\tpath: taskPath\n\t\t\t};\n\t\t}\n\t}\n\treturn void 0;\n}\n/**\n* Function injected under CONFIG_KEY_READ in task config, to read current state.\n* Used by conditional edges to read a copy of the state with reflecting the writes\n* from that node only.\n*\n* @internal\n*/\nfunction _procInput(proc, channels, forExecution) {\n\tlet val;\n\tif (typeof proc.channels === \"object\" && !Array.isArray(proc.channels)) {\n\t\tval = {};\n\t\tfor (const [k, chan] of Object.entries(proc.channels)) if (proc.triggers.includes(chan)) try {\n\t\t\tval[k] = readChannel(channels, chan, false);\n\t\t} catch (e) {\n\t\t\tif (e.name === EmptyChannelError.unminifiable_name) return void 0;\n\t\t\telse throw e;\n\t\t}\n\t\telse if (chan in channels) try {\n\t\t\tval[k] = readChannel(channels, chan, false);\n\t\t} catch (e) {\n\t\t\tif (e.name === EmptyChannelError.unminifiable_name) continue;\n\t\t\telse throw e;\n\t\t}\n\t} else if (Array.isArray(proc.channels)) {\n\t\tlet successfulRead = false;\n\t\tfor (const chan of proc.channels) try {\n\t\t\tval = readChannel(channels, chan, false);\n\t\t\tsuccessfulRead = true;\n\t\t\tbreak;\n\t\t} catch (e) {\n\t\t\tif (e.name === EmptyChannelError.unminifiable_name) continue;\n\t\t\telse throw e;\n\t\t}\n\t\tif (!successfulRead) return void 0;\n\t} else throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`);\n\tif (forExecution && proc.mapper !== void 0) val = proc.mapper(val);\n\treturn val;\n}\nfunction _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) {\n\tconst nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === RESUME)?.[2];\n\tconst resume = (() => {\n\t\tconst result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === RESUME).flatMap(([_writeTaskId, _chan, resume$1]) => resume$1);\n\t\tif (resumeMap != null && namespaceHash in resumeMap) {\n\t\t\tconst mappedResume = resumeMap[namespaceHash];\n\t\t\tresult.push(mappedResume);\n\t\t}\n\t\treturn result;\n\t})();\n\tconst scratchpad = {\n\t\tcallCounter: 0,\n\t\tinterruptCounter: -1,\n\t\tresume,\n\t\tnullResume,\n\t\tsubgraphCounter: 0,\n\t\tcurrentTaskInput,\n\t\tconsumeNullResume: () => {\n\t\t\tif (scratchpad.nullResume) {\n\t\t\t\tdelete scratchpad.nullResume;\n\t\t\t\tpendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === RESUME), 1);\n\t\t\t\treturn nullResume;\n\t\t\t}\n\t\t\treturn void 0;\n\t\t}\n\t};\n\treturn scratchpad;\n}\n\n//#endregion\nexport { _applyWrites, _localRead, _prepareNextTasks, _prepareSingleTask, increment, shouldInterrupt };\n//# sourceMappingURL=algo.js.map","import { ERROR, INTERRUPT, RETURN, TAG_HIDDEN } from \"../constants.js\";\nimport { readChannels } from \"./io.js\";\nimport { findSubgraphPregel } from \"./utils/subgraph.js\";\n\n//#region src/pregel/debug.ts\nconst COLORS_MAP = {\n\tblue: {\n\t\tstart: \"\\x1B[34m\",\n\t\tend: \"\\x1B[0m\"\n\t},\n\tgreen: {\n\t\tstart: \"\\x1B[32m\",\n\t\tend: \"\\x1B[0m\"\n\t},\n\tyellow: {\n\t\tstart: \"\\x1B[33;1m\",\n\t\tend: \"\\x1B[0m\"\n\t}\n};\n/**\n* Wrap some text in a color for printing to the console.\n*/\nconst wrap = (color, text) => `${color.start}${text}${color.end}`;\nfunction* mapDebugTasks(tasks) {\n\tfor (const { id, name, input, config, triggers, writes } of tasks) {\n\t\tif (config?.tags?.includes(TAG_HIDDEN)) continue;\n\t\tconst interrupts = writes.filter(([writeId, n]) => {\n\t\t\treturn writeId === id && n === INTERRUPT;\n\t\t}).map(([, v]) => {\n\t\t\treturn v;\n\t\t});\n\t\tyield {\n\t\t\tid,\n\t\t\tname,\n\t\t\tinput,\n\t\t\ttriggers,\n\t\t\tinterrupts\n\t\t};\n\t}\n}\nfunction isMultipleChannelWrite(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"$writes\" in value && Array.isArray(value.$writes);\n}\nfunction mapTaskResultWrites(writes) {\n\tconst result = {};\n\tfor (const [channel, value] of writes) {\n\t\tconst strChannel = String(channel);\n\t\tif (strChannel in result) {\n\t\t\tconst channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]];\n\t\t\tchannelWrites.push(value);\n\t\t\tresult[strChannel] = { $writes: channelWrites };\n\t\t} else result[strChannel] = value;\n\t}\n\treturn result;\n}\nfunction* mapDebugTaskResults(tasks, streamChannels) {\n\tfor (const [{ id, name, config }, writes] of tasks) {\n\t\tif (config?.tags?.includes(TAG_HIDDEN)) continue;\n\t\tyield {\n\t\t\tid,\n\t\t\tname,\n\t\t\tresult: mapTaskResultWrites(writes.filter(([channel]) => {\n\t\t\t\treturn Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels;\n\t\t\t})),\n\t\t\tinterrupts: writes.filter((w) => w[0] === INTERRUPT).map((w) => w[1])\n\t\t};\n\t}\n}\nfunction* mapDebugCheckpoint(config, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) {\n\tfunction formatConfig(config$1) {\n\t\tconst pyConfig = {};\n\t\tif (config$1.callbacks != null) pyConfig.callbacks = config$1.callbacks;\n\t\tif (config$1.configurable != null) pyConfig.configurable = config$1.configurable;\n\t\tif (config$1.maxConcurrency != null) pyConfig.max_concurrency = config$1.maxConcurrency;\n\t\tif (config$1.metadata != null) pyConfig.metadata = config$1.metadata;\n\t\tif (config$1.recursionLimit != null) pyConfig.recursion_limit = config$1.recursionLimit;\n\t\tif (config$1.runId != null) pyConfig.run_id = config$1.runId;\n\t\tif (config$1.runName != null) pyConfig.run_name = config$1.runName;\n\t\tif (config$1.tags != null) pyConfig.tags = config$1.tags;\n\t\treturn pyConfig;\n\t}\n\tconst parentNs = config.configurable?.checkpoint_ns;\n\tconst taskStates = {};\n\tfor (const task of tasks) {\n\t\tconst candidates = task.subgraphs?.length ? task.subgraphs : [task.proc];\n\t\tif (!candidates.find(findSubgraphPregel)) continue;\n\t\tlet taskNs = `${task.name}:${task.id}`;\n\t\tif (parentNs) taskNs = `${parentNs}|${taskNs}`;\n\t\ttaskStates[task.id] = { configurable: {\n\t\t\tthread_id: config.configurable?.thread_id,\n\t\t\tcheckpoint_ns: taskNs\n\t\t} };\n\t}\n\tyield {\n\t\tconfig: formatConfig(config),\n\t\tvalues: readChannels(channels, streamChannels),\n\t\tmetadata,\n\t\tnext: tasks.map((task) => task.name),\n\t\ttasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys),\n\t\tparentConfig: parentConfig ? formatConfig(parentConfig) : void 0\n\t};\n}\nfunction tasksWithWrites(tasks, pendingWrites, states, outputKeys) {\n\treturn tasks.map((task) => {\n\t\tconst error = pendingWrites.find(([id, n]) => id === task.id && n === ERROR)?.[2];\n\t\tconst interrupts = pendingWrites.filter(([id, n]) => id === task.id && n === INTERRUPT).map(([, , v]) => v);\n\t\tconst result = (() => {\n\t\t\tif (error || interrupts.length || !pendingWrites.length) return void 0;\n\t\t\tconst idx = pendingWrites.findIndex(([tid, n]) => tid === task.id && n === RETURN);\n\t\t\tif (idx >= 0) return pendingWrites[idx][2];\n\t\t\tif (typeof outputKeys === \"string\") return pendingWrites.find(([tid, n]) => tid === task.id && n === outputKeys)?.[2];\n\t\t\tif (Array.isArray(outputKeys)) {\n\t\t\t\tconst results = pendingWrites.filter(([tid, n]) => tid === task.id && outputKeys.includes(n)).map(([, n, v]) => [n, v]);\n\t\t\t\tif (!results.length) return void 0;\n\t\t\t\treturn mapTaskResultWrites(results);\n\t\t\t}\n\t\t\treturn void 0;\n\t\t})();\n\t\tif (error) return {\n\t\t\tid: task.id,\n\t\t\tname: task.name,\n\t\t\tpath: task.path,\n\t\t\terror,\n\t\t\tinterrupts,\n\t\t\tresult\n\t\t};\n\t\tconst taskState = states?.[task.id];\n\t\treturn {\n\t\t\tid: task.id,\n\t\t\tname: task.name,\n\t\t\tpath: task.path,\n\t\t\tinterrupts,\n\t\t\t...taskState !== void 0 ? { state: taskState } : {},\n\t\t\tresult\n\t\t};\n\t});\n}\nfunction printStepCheckpoint(step, channels, whitelist) {\n\tconsole.log([\n\t\t`${wrap(COLORS_MAP.blue, `[${step}:checkpoint]`)}`,\n\t\t`\\x1b[1m State at the end of step ${step}:\\x1b[0m\\n`,\n\t\tJSON.stringify(readChannels(channels, whitelist), null, 2)\n\t].join(\"\"));\n}\nfunction printStepTasks(step, nextTasks) {\n\tconst nTasks = nextTasks.length;\n\tconsole.log([\n\t\t`${wrap(COLORS_MAP.blue, `[${step}:tasks]`)}`,\n\t\t`\\x1b[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? \"\" : \"s\"}:\\x1b[0m\\n`,\n\t\tnextTasks.map((task) => `- ${wrap(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join(\"\\n\")\n\t].join(\"\"));\n}\nfunction printStepWrites(step, writes, whitelist) {\n\tconst byChannel = {};\n\tfor (const [channel, value] of writes) if (whitelist.includes(channel)) {\n\t\tif (!byChannel[channel]) byChannel[channel] = [];\n\t\tbyChannel[channel].push(value);\n\t}\n\tconsole.log([\n\t\t`${wrap(COLORS_MAP.blue, `[${step}:writes]`)}`,\n\t\t`\\x1b[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? \"s\" : \"\"}:\\x1b[0m\\n`,\n\t\tObject.entries(byChannel).map(([name, vals]) => `- ${wrap(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(\", \")}`).join(\"\\n\")\n\t].join(\"\"));\n}\n\n//#endregion\nexport { mapDebugCheckpoint, mapDebugTaskResults, mapDebugTasks, printStepCheckpoint, printStepTasks, printStepWrites, tasksWithWrites };\n//# sourceMappingURL=debug.js.map","import { IterableReadableStream } from \"@langchain/core/utils/stream\";\n\n//#region src/pregel/stream.ts\n/**\n* A wrapper around an IterableReadableStream that allows for aborting the stream when\n* {@link cancel} is called.\n*/\nvar IterableReadableStreamWithAbortSignal = class extends IterableReadableStream {\n\t_abortController;\n\t_innerReader;\n\t/**\n\t* @param readableStream - The stream to wrap.\n\t* @param abortController - The abort controller to use. Optional. One will be created if not provided.\n\t*/\n\tconstructor(readableStream, abortController) {\n\t\tconst reader = readableStream.getReader();\n\t\tconst ac = abortController ?? new AbortController();\n\t\tsuper({ start(controller) {\n\t\t\treturn pump();\n\t\t\tfunction pump() {\n\t\t\t\treturn reader.read().then(({ done, value }) => {\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\treturn pump();\n\t\t\t\t});\n\t\t\t}\n\t\t} });\n\t\tthis._abortController = ac;\n\t\tthis._innerReader = reader;\n\t}\n\t/**\n\t* Aborts the stream, abandoning any pending operations in progress. Calling this triggers an\n\t* {@link AbortSignal} that is propagated to the tasks that are producing the data for this stream.\n\t* @param reason - The reason for aborting the stream. Optional.\n\t*/\n\tasync cancel(reason) {\n\t\tthis._abortController.abort(reason);\n\t\tthis._innerReader.releaseLock();\n\t}\n\t/**\n\t* The {@link AbortSignal} for the stream. Aborted when {@link cancel} is called.\n\t*/\n\tget signal() {\n\t\treturn this._abortController.signal;\n\t}\n};\nvar IterableReadableWritableStream = class extends IterableReadableStream {\n\tmodes;\n\tcontroller;\n\tpassthroughFn;\n\t_closed = false;\n\tget closed() {\n\t\treturn this._closed;\n\t}\n\tconstructor(params) {\n\t\tlet streamControllerPromiseResolver;\n\t\tconst streamControllerPromise = new Promise((resolve) => {\n\t\t\tstreamControllerPromiseResolver = resolve;\n\t\t});\n\t\tsuper({ start: (controller) => {\n\t\t\tstreamControllerPromiseResolver(controller);\n\t\t} });\n\t\tstreamControllerPromise.then((controller) => {\n\t\t\tthis.controller = controller;\n\t\t});\n\t\tthis.passthroughFn = params.passthroughFn;\n\t\tthis.modes = params.modes;\n\t}\n\tpush(chunk) {\n\t\tthis.passthroughFn?.(chunk);\n\t\tthis.controller.enqueue(chunk);\n\t}\n\tclose() {\n\t\ttry {\n\t\t\tthis.controller.close();\n\t\t} catch (e) {} finally {\n\t\t\tthis._closed = true;\n\t\t}\n\t}\n\terror(e) {\n\t\tthis.controller.error(e);\n\t}\n};\nfunction _stringifyAsDict(obj) {\n\treturn JSON.stringify(obj, function(key, value) {\n\t\tconst rawValue = this[key];\n\t\tif (rawValue != null && typeof rawValue === \"object\" && \"toDict\" in rawValue && typeof rawValue.toDict === \"function\") {\n\t\t\tconst { type, data } = rawValue.toDict();\n\t\t\treturn {\n\t\t\t\t...data,\n\t\t\t\ttype\n\t\t\t};\n\t\t}\n\t\treturn value;\n\t});\n}\nfunction _serializeError(error) {\n\tif (error instanceof Error) return {\n\t\terror: error.name,\n\t\tmessage: error.message\n\t};\n\treturn {\n\t\terror: \"Error\",\n\t\tmessage: JSON.stringify(error)\n\t};\n}\nfunction _isRunnableConfig(config) {\n\tif (typeof config !== \"object\" || config == null) return false;\n\treturn \"configurable\" in config && typeof config.configurable === \"object\" && config.configurable != null;\n}\nfunction _extractCheckpointFromConfig(config) {\n\tif (!_isRunnableConfig(config) || !config.configurable.thread_id) return null;\n\treturn {\n\t\tthread_id: config.configurable.thread_id,\n\t\tcheckpoint_ns: config.configurable.checkpoint_ns || \"\",\n\t\tcheckpoint_id: config.configurable.checkpoint_id || null,\n\t\tcheckpoint_map: config.configurable.checkpoint_map || null\n\t};\n}\nfunction _serializeConfig(config) {\n\tif (_isRunnableConfig(config)) {\n\t\tconst configurable = Object.fromEntries(Object.entries(config.configurable).filter(([key]) => !key.startsWith(\"__\")));\n\t\tconst newConfig = {\n\t\t\t...config,\n\t\t\tconfigurable\n\t\t};\n\t\tdelete newConfig.callbacks;\n\t\treturn newConfig;\n\t}\n\treturn config;\n}\nfunction _serializeCheckpoint(payload) {\n\tconst result = {\n\t\t...payload,\n\t\tcheckpoint: _extractCheckpointFromConfig(payload.config),\n\t\tparent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig),\n\t\tconfig: _serializeConfig(payload.config),\n\t\tparent_config: _serializeConfig(payload.parentConfig),\n\t\ttasks: payload.tasks.map((task) => {\n\t\t\tif (_isRunnableConfig(task.state)) {\n\t\t\t\tconst checkpoint = _extractCheckpointFromConfig(task.state);\n\t\t\t\tif (checkpoint != null) {\n\t\t\t\t\tconst cloneTask = {\n\t\t\t\t\t\t...task,\n\t\t\t\t\t\tcheckpoint\n\t\t\t\t\t};\n\t\t\t\t\tdelete cloneTask.state;\n\t\t\t\t\treturn cloneTask;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn task;\n\t\t})\n\t};\n\tdelete result.parentConfig;\n\treturn result;\n}\nfunction toEventStream(stream) {\n\tconst encoder = new TextEncoder();\n\treturn new ReadableStream({ async start(controller) {\n\t\tconst enqueueChunk = (sse) => {\n\t\t\tcontroller.enqueue(encoder.encode(`event: ${sse.event}\\ndata: ${_stringifyAsDict(sse.data)}\\n\\n`));\n\t\t};\n\t\ttry {\n\t\t\tfor await (const payload of stream) {\n\t\t\t\tconst [ns, mode, chunk] = payload;\n\t\t\t\tlet data = chunk;\n\t\t\t\tif (mode === \"debug\") {\n\t\t\t\t\tconst debugChunk = chunk;\n\t\t\t\t\tif (debugChunk.type === \"checkpoint\") data = {\n\t\t\t\t\t\t...debugChunk,\n\t\t\t\t\t\tpayload: _serializeCheckpoint(debugChunk.payload)\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (mode === \"checkpoints\") data = _serializeCheckpoint(chunk);\n\t\t\t\tconst event = ns?.length ? `${mode}|${ns.join(\"|\")}` : mode;\n\t\t\t\tenqueueChunk({\n\t\t\t\t\tevent,\n\t\t\t\t\tdata\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tenqueueChunk({\n\t\t\t\tevent: \"error\",\n\t\t\t\tdata: _serializeError(error)\n\t\t\t});\n\t\t}\n\t\tcontroller.close();\n\t} });\n}\n\n//#endregion\nexport { IterableReadableStreamWithAbortSignal, IterableReadableWritableStream, toEventStream };\n//# sourceMappingURL=stream.js.map","import { EmptyInputError, GraphInterrupt, isGraphInterrupt } from \"../errors.js\";\nimport { createCheckpoint, emptyChannels } from \"../channels/base.js\";\nimport { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINT_ID, CONFIG_KEY_CHECKPOINT_MAP, CONFIG_KEY_CHECKPOINT_NS, CONFIG_KEY_READ, CONFIG_KEY_RESUME_MAP, CONFIG_KEY_RESUMING, CONFIG_KEY_SCRATCHPAD, CONFIG_KEY_STREAM, ERROR, INPUT, INTERRUPT, NULL_TASK_ID, PUSH, RESUME, START, TAG_HIDDEN, isCommand } from \"../constants.js\";\nimport { gatherIterator, gatherIteratorSync, prefixGenerator } from \"../utils.js\";\nimport { isXXH3 } from \"../hash.js\";\nimport { mapCommand, mapInput, mapOutputUpdates, mapOutputValues, readChannels } from \"./io.js\";\nimport { getNewChannelVersions, patchConfigurable } from \"./utils/index.js\";\nimport { _applyWrites, _prepareNextTasks, _prepareSingleTask, increment, shouldInterrupt } from \"./algo.js\";\nimport { mapDebugCheckpoint, mapDebugTaskResults, mapDebugTasks, printStepTasks } from \"./debug.js\";\nimport { IterableReadableWritableStream } from \"./stream.js\";\nimport { AsyncBatchedStore, BaseCache, WRITES_IDX_MAP, copyCheckpoint, emptyCheckpoint } from \"@langchain/langgraph-checkpoint\";\n\n//#region src/pregel/loop.ts\nconst INPUT_DONE = Symbol.for(\"INPUT_DONE\");\nconst INPUT_RESUMING = Symbol.for(\"INPUT_RESUMING\");\nconst DEFAULT_LOOP_LIMIT = 25;\nfunction createDuplexStream(...streams) {\n\treturn new IterableReadableWritableStream({\n\t\tpassthroughFn: (value) => {\n\t\t\tfor (const stream of streams) if (stream.modes.has(value[1])) stream.push(value);\n\t\t},\n\t\tmodes: new Set(streams.flatMap((s) => Array.from(s.modes)))\n\t});\n}\nvar AsyncBatchedCache = class extends BaseCache {\n\tcache;\n\tqueue = Promise.resolve();\n\tconstructor(cache) {\n\t\tsuper();\n\t\tthis.cache = cache;\n\t}\n\tasync get(keys) {\n\t\treturn this.enqueueOperation(\"get\", keys);\n\t}\n\tasync set(pairs) {\n\t\treturn this.enqueueOperation(\"set\", pairs);\n\t}\n\tasync clear(namespaces) {\n\t\treturn this.enqueueOperation(\"clear\", namespaces);\n\t}\n\tasync stop() {\n\t\tawait this.queue;\n\t}\n\tenqueueOperation(type, ...args) {\n\t\tconst newPromise = this.queue.then(() => {\n\t\t\treturn this.cache[type](...args);\n\t\t});\n\t\tthis.queue = newPromise.then(() => void 0, () => void 0);\n\t\treturn newPromise;\n\t}\n};\nvar PregelLoop = class PregelLoop {\n\tinput;\n\toutput;\n\tconfig;\n\tcheckpointer;\n\tcheckpointerGetNextVersion;\n\tchannels;\n\tcheckpoint;\n\tcheckpointIdSaved;\n\tcheckpointConfig;\n\tcheckpointMetadata;\n\tcheckpointNamespace;\n\tcheckpointPendingWrites = [];\n\tcheckpointPreviousVersions;\n\tstep;\n\tstop;\n\tdurability;\n\toutputKeys;\n\tstreamKeys;\n\tnodes;\n\tskipDoneTasks;\n\tprevCheckpointConfig;\n\tupdatedChannels;\n\tstatus = \"pending\";\n\ttasks = {};\n\tstream;\n\tcheckpointerPromises = [];\n\tisNested;\n\t_checkpointerChainedPromise = Promise.resolve();\n\tstore;\n\tcache;\n\tmanager;\n\tinterruptAfter;\n\tinterruptBefore;\n\ttoInterrupt = [];\n\tdebug = false;\n\ttriggerToNodes;\n\tget isResuming() {\n\t\tlet hasChannelVersions = false;\n\t\tif (START in this.checkpoint.channel_versions) hasChannelVersions = true;\n\t\telse for (const chan in this.checkpoint.channel_versions) if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) {\n\t\t\thasChannelVersions = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst configHasResumingFlag = this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0;\n\t\tconst configIsResuming = configHasResumingFlag && this.config.configurable?.[CONFIG_KEY_RESUMING];\n\t\tconst inputIsNullOrUndefined = this.input === null || this.input === void 0;\n\t\tconst inputIsCommandResuming = isCommand(this.input) && this.input.resume != null;\n\t\tconst inputIsResuming = this.input === INPUT_RESUMING;\n\t\tconst runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== void 0 && this.checkpointMetadata?.run_id !== void 0 && this.config.metadata.run_id === this.checkpointMetadata?.run_id;\n\t\treturn hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious);\n\t}\n\tconstructor(params) {\n\t\tthis.input = params.input;\n\t\tthis.checkpointer = params.checkpointer;\n\t\tif (this.checkpointer !== void 0) this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer);\n\t\telse this.checkpointerGetNextVersion = increment;\n\t\tthis.checkpoint = params.checkpoint;\n\t\tthis.checkpointMetadata = params.checkpointMetadata;\n\t\tthis.checkpointPreviousVersions = params.checkpointPreviousVersions;\n\t\tthis.channels = params.channels;\n\t\tthis.checkpointPendingWrites = params.checkpointPendingWrites;\n\t\tthis.step = params.step;\n\t\tthis.stop = params.stop;\n\t\tthis.config = params.config;\n\t\tthis.checkpointConfig = params.checkpointConfig;\n\t\tthis.isNested = params.isNested;\n\t\tthis.manager = params.manager;\n\t\tthis.outputKeys = params.outputKeys;\n\t\tthis.streamKeys = params.streamKeys;\n\t\tthis.nodes = params.nodes;\n\t\tthis.skipDoneTasks = params.skipDoneTasks;\n\t\tthis.store = params.store;\n\t\tthis.cache = params.cache ? new AsyncBatchedCache(params.cache) : void 0;\n\t\tthis.stream = params.stream;\n\t\tthis.checkpointNamespace = params.checkpointNamespace;\n\t\tthis.prevCheckpointConfig = params.prevCheckpointConfig;\n\t\tthis.interruptAfter = params.interruptAfter;\n\t\tthis.interruptBefore = params.interruptBefore;\n\t\tthis.durability = params.durability;\n\t\tthis.debug = params.debug;\n\t\tthis.triggerToNodes = params.triggerToNodes;\n\t}\n\tstatic async initialize(params) {\n\t\tlet { config, stream } = params;\n\t\tif (stream !== void 0 && config.configurable?.[CONFIG_KEY_STREAM] !== void 0) stream = createDuplexStream(stream, config.configurable[CONFIG_KEY_STREAM]);\n\t\tconst skipDoneTasks = config.configurable ? !(\"checkpoint_id\" in config.configurable) : true;\n\t\tconst scratchpad = config.configurable?.[CONFIG_KEY_SCRATCHPAD];\n\t\tif (config.configurable && scratchpad) {\n\t\t\tif (scratchpad.subgraphCounter > 0) config = patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_NS]: [config.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join(CHECKPOINT_NAMESPACE_SEPARATOR) });\n\t\t\tscratchpad.subgraphCounter += 1;\n\t\t}\n\t\tconst isNested = CONFIG_KEY_READ in (config.configurable ?? {});\n\t\tif (!isNested && config.configurable?.checkpoint_ns !== void 0 && config.configurable?.checkpoint_ns !== \"\") config = patchConfigurable(config, {\n\t\t\tcheckpoint_ns: \"\",\n\t\t\tcheckpoint_id: void 0\n\t\t});\n\t\tlet checkpointConfig = config;\n\t\tif (config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP]?.[config.configurable?.checkpoint_ns]) checkpointConfig = patchConfigurable(config, { checkpoint_id: config.configurable[CONFIG_KEY_CHECKPOINT_MAP][config.configurable?.checkpoint_ns] });\n\t\tconst checkpointNamespace = config.configurable?.checkpoint_ns?.split(CHECKPOINT_NAMESPACE_SEPARATOR) ?? [];\n\t\tconst saved = await params.checkpointer?.getTuple(checkpointConfig) ?? {\n\t\t\tconfig,\n\t\t\tcheckpoint: emptyCheckpoint(),\n\t\t\tmetadata: {\n\t\t\t\tsource: \"input\",\n\t\t\t\tstep: -2,\n\t\t\t\tparents: {}\n\t\t\t},\n\t\t\tpendingWrites: []\n\t\t};\n\t\tcheckpointConfig = {\n\t\t\t...config,\n\t\t\t...saved.config,\n\t\t\tconfigurable: {\n\t\t\t\tcheckpoint_ns: \"\",\n\t\t\t\t...config.configurable,\n\t\t\t\t...saved.config.configurable\n\t\t\t}\n\t\t};\n\t\tconst prevCheckpointConfig = saved.parentConfig;\n\t\tconst checkpoint = copyCheckpoint(saved.checkpoint);\n\t\tconst checkpointMetadata = { ...saved.metadata };\n\t\tconst checkpointPendingWrites = saved.pendingWrites ?? [];\n\t\tconst channels = emptyChannels(params.channelSpecs, checkpoint);\n\t\tconst step = (checkpointMetadata.step ?? 0) + 1;\n\t\tconst stop = step + (config.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1;\n\t\tconst checkpointPreviousVersions = { ...checkpoint.channel_versions };\n\t\tconst store = params.store ? new AsyncBatchedStore(params.store) : void 0;\n\t\tif (store) await store.start();\n\t\treturn new PregelLoop({\n\t\t\tinput: params.input,\n\t\t\tconfig,\n\t\t\tcheckpointer: params.checkpointer,\n\t\t\tcheckpoint,\n\t\t\tcheckpointMetadata,\n\t\t\tcheckpointConfig,\n\t\t\tprevCheckpointConfig,\n\t\t\tcheckpointNamespace,\n\t\t\tchannels,\n\t\t\tisNested,\n\t\t\tmanager: params.manager,\n\t\t\tskipDoneTasks,\n\t\t\tstep,\n\t\t\tstop,\n\t\t\tcheckpointPreviousVersions,\n\t\t\tcheckpointPendingWrites,\n\t\t\toutputKeys: params.outputKeys ?? [],\n\t\t\tstreamKeys: params.streamKeys ?? [],\n\t\t\tnodes: params.nodes,\n\t\t\tstream,\n\t\t\tstore,\n\t\t\tcache: params.cache,\n\t\t\tinterruptAfter: params.interruptAfter,\n\t\t\tinterruptBefore: params.interruptBefore,\n\t\t\tdurability: params.durability,\n\t\t\tdebug: params.debug,\n\t\t\ttriggerToNodes: params.triggerToNodes\n\t\t});\n\t}\n\t_checkpointerPutAfterPrevious(input) {\n\t\tthis._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => {\n\t\t\treturn this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions);\n\t\t});\n\t\tthis.checkpointerPromises.push(this._checkpointerChainedPromise);\n\t}\n\t/**\n\t* Put writes for a task, to be read by the next tick.\n\t* @param taskId\n\t* @param writes\n\t*/\n\tputWrites(taskId, writes) {\n\t\tlet writesCopy = writes;\n\t\tif (writesCopy.length === 0) return;\n\t\tif (writesCopy.every(([key]) => key in WRITES_IDX_MAP)) writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values());\n\t\tthis.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId);\n\t\tfor (const [c, v] of writesCopy) this.checkpointPendingWrites.push([\n\t\t\ttaskId,\n\t\t\tc,\n\t\t\tv\n\t\t]);\n\t\tconst config = patchConfigurable(this.checkpointConfig, {\n\t\t\t[CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? \"\",\n\t\t\t[CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id\n\t\t});\n\t\tif (this.durability !== \"exit\" && this.checkpointer != null) this.checkpointerPromises.push(this.checkpointer.putWrites(config, writesCopy, taskId));\n\t\tif (this.tasks) this._outputWrites(taskId, writesCopy);\n\t\tif (!writes.length || !this.cache || !this.tasks) return;\n\t\tconst task = this.tasks[taskId];\n\t\tif (task == null || task.cache_key == null) return;\n\t\tif (writes[0][0] === ERROR || writes[0][0] === INTERRUPT) return;\n\t\tthis.cache.set([{\n\t\t\tkey: [task.cache_key.ns, task.cache_key.key],\n\t\t\tvalue: task.writes,\n\t\t\tttl: task.cache_key.ttl\n\t\t}]);\n\t}\n\t_outputWrites(taskId, writes, cached = false) {\n\t\tconst task = this.tasks[taskId];\n\t\tif (task !== void 0) {\n\t\t\tif (task.config !== void 0 && (task.config.tags ?? []).includes(TAG_HIDDEN)) return;\n\t\t\tif (writes.length > 0) {\n\t\t\t\tif (writes[0][0] === INTERRUPT) {\n\t\t\t\t\tif (task.path?.[0] === PUSH && task.path?.at(-1) === true) return;\n\t\t\t\t\tconst interruptWrites = writes.filter((w) => w[0] === INTERRUPT).flatMap((w) => w[1]);\n\t\t\t\t\tthis._emit([[\"updates\", { [INTERRUPT]: interruptWrites }], [\"values\", { [INTERRUPT]: interruptWrites }]]);\n\t\t\t\t} else if (writes[0][0] !== ERROR) this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached), \"updates\")));\n\t\t\t}\n\t\t\tif (!cached) this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), \"tasks\")));\n\t\t}\n\t}\n\tasync _matchCachedWrites() {\n\t\tif (!this.cache) return [];\n\t\tconst matched = [];\n\t\tconst serializeKey = ([ns, key]) => {\n\t\t\treturn `ns:${ns.join(\",\")}|key:${key}`;\n\t\t};\n\t\tconst keys = [];\n\t\tconst keyMap = {};\n\t\tfor (const task of Object.values(this.tasks)) if (task.cache_key != null && !task.writes.length) {\n\t\t\tkeys.push([task.cache_key.ns, task.cache_key.key]);\n\t\t\tkeyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task;\n\t\t}\n\t\tif (keys.length === 0) return [];\n\t\tconst cache = await this.cache.get(keys);\n\t\tfor (const { key, value } of cache) {\n\t\t\tconst task = keyMap[serializeKey(key)];\n\t\t\tif (task != null) {\n\t\t\t\ttask.writes.push(...value);\n\t\t\t\tmatched.push({\n\t\t\t\t\ttask,\n\t\t\t\t\tresult: value\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn matched;\n\t}\n\t/**\n\t* Execute a single iteration of the Pregel loop.\n\t* Returns true if more iterations are needed.\n\t* @param params\n\t*/\n\tasync tick(params) {\n\t\tif (this.store && !this.store.isRunning) await this.store?.start();\n\t\tconst { inputKeys = [] } = params;\n\t\tif (this.status !== \"pending\") throw new Error(`Cannot tick when status is no longer \"pending\". Current status: \"${this.status}\"`);\n\t\tif (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) await this._first(inputKeys);\n\t\telse if (this.toInterrupt.length > 0) {\n\t\t\tthis.status = \"interrupt_before\";\n\t\t\tthrow new GraphInterrupt();\n\t\t} else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) {\n\t\t\tconst writes = Object.values(this.tasks).flatMap((t) => t.writes);\n\t\t\tthis.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes);\n\t\t\tconst valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), \"values\"));\n\t\t\tthis._emit(valuesOutput);\n\t\t\tthis.checkpointPendingWrites = [];\n\t\t\tawait this._putCheckpoint({ source: \"loop\" });\n\t\t\tif (shouldInterrupt(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) {\n\t\t\t\tthis.status = \"interrupt_after\";\n\t\t\t\tthrow new GraphInterrupt();\n\t\t\t}\n\t\t\tif (this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0) delete this.config.configurable?.[CONFIG_KEY_RESUMING];\n\t\t} else return false;\n\t\tif (this.step > this.stop) {\n\t\t\tthis.status = \"out_of_steps\";\n\t\t\treturn false;\n\t\t}\n\t\tconst nextTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, {\n\t\t\tstep: this.step,\n\t\t\tcheckpointer: this.checkpointer,\n\t\t\tisResuming: this.isResuming,\n\t\t\tmanager: this.manager,\n\t\t\tstore: this.store,\n\t\t\tstream: this.stream,\n\t\t\ttriggerToNodes: this.triggerToNodes,\n\t\t\tupdatedChannels: this.updatedChannels\n\t\t});\n\t\tthis.tasks = nextTasks;\n\t\tif (this.checkpointer) this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), \"checkpoints\")));\n\t\tif (Object.values(this.tasks).length === 0) {\n\t\t\tthis.status = \"done\";\n\t\t\treturn false;\n\t\t}\n\t\tif (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) {\n\t\t\tfor (const [tid, k, v] of this.checkpointPendingWrites) {\n\t\t\t\tif (k === ERROR || k === INTERRUPT || k === RESUME) continue;\n\t\t\t\tconst task = Object.values(this.tasks).find((t) => t.id === tid);\n\t\t\t\tif (task) task.writes.push([k, v]);\n\t\t\t}\n\t\t\tfor (const task of Object.values(this.tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true);\n\t\t}\n\t\tif (Object.values(this.tasks).every((task) => task.writes.length > 0)) return this.tick({ inputKeys });\n\t\tif (shouldInterrupt(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) {\n\t\t\tthis.status = \"interrupt_before\";\n\t\t\tthrow new GraphInterrupt();\n\t\t}\n\t\tconst debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(Object.values(this.tasks)), \"tasks\"));\n\t\tthis._emit(debugOutput);\n\t\treturn true;\n\t}\n\tasync finishAndHandleError(error) {\n\t\tif (this.durability === \"exit\" && (!this.isNested || typeof error !== \"undefined\" || this.checkpointNamespace.every((part) => !part.includes(CHECKPOINT_NAMESPACE_END)))) {\n\t\t\tthis._putCheckpoint(this.checkpointMetadata);\n\t\t\tthis._flushPendingWrites();\n\t\t}\n\t\tconst suppress = this._suppressInterrupt(error);\n\t\tif (suppress || error === void 0) this.output = readChannels(this.channels, this.outputKeys);\n\t\tif (suppress) {\n\t\t\tif (this.tasks !== void 0 && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) {\n\t\t\t\tthis.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes);\n\t\t\t\tthis._emit(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), \"values\")));\n\t\t\t}\n\t\t\tif (isGraphInterrupt(error) && !error.interrupts.length) this._emit([[\"updates\", { [INTERRUPT]: [] }], [\"values\", { [INTERRUPT]: [] }]]);\n\t\t}\n\t\treturn suppress;\n\t}\n\tasync acceptPush(task, writeIdx, call) {\n\t\tif (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) {\n\t\t\tthis.toInterrupt.push(task);\n\t\t\treturn;\n\t\t}\n\t\tconst pushed = _prepareSingleTask([\n\t\t\tPUSH,\n\t\t\ttask.path ?? [],\n\t\t\twriteIdx,\n\t\t\ttask.id,\n\t\t\tcall\n\t\t], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, {\n\t\t\tstep: this.step,\n\t\t\tcheckpointer: this.checkpointer,\n\t\t\tmanager: this.manager,\n\t\t\tstore: this.store,\n\t\t\tstream: this.stream\n\t\t});\n\t\tif (!pushed) return;\n\t\tif (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) {\n\t\t\tthis.toInterrupt.push(pushed);\n\t\t\treturn;\n\t\t}\n\t\tthis._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), \"tasks\")));\n\t\tif (this.debug) printStepTasks(this.step, [pushed]);\n\t\tthis.tasks[pushed.id] = pushed;\n\t\tif (this.skipDoneTasks) this._matchWrites({ [pushed.id]: pushed });\n\t\tconst tasks = await this._matchCachedWrites();\n\t\tfor (const { task: task$1 } of tasks) this._outputWrites(task$1.id, task$1.writes, true);\n\t\treturn pushed;\n\t}\n\t_suppressInterrupt(e) {\n\t\treturn isGraphInterrupt(e) && !this.isNested;\n\t}\n\tasync _first(inputKeys) {\n\t\tconst { configurable } = this.config;\n\t\tconst scratchpad = configurable?.[CONFIG_KEY_SCRATCHPAD];\n\t\tif (scratchpad && scratchpad.nullResume !== void 0) this.putWrites(NULL_TASK_ID, [[RESUME, scratchpad.nullResume]]);\n\t\tif (isCommand(this.input)) {\n\t\t\tconst hasResume = this.input.resume != null;\n\t\t\tif (this.input.resume != null && typeof this.input.resume === \"object\" && Object.keys(this.input.resume).every(isXXH3)) {\n\t\t\t\tthis.config.configurable ??= {};\n\t\t\t\tthis.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume;\n\t\t\t}\n\t\t\tif (hasResume && this.checkpointer == null) throw new Error(\"Cannot use Command(resume=...) without checkpointer\");\n\t\t\tconst writes = {};\n\t\t\tfor (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) {\n\t\t\t\twrites[tid] ??= [];\n\t\t\t\twrites[tid].push([key, value]);\n\t\t\t}\n\t\t\tif (Object.keys(writes).length === 0) throw new EmptyInputError(\"Received empty Command input\");\n\t\t\tfor (const [tid, ws] of Object.entries(writes)) this.putWrites(tid, ws);\n\t\t}\n\t\tconst nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));\n\t\tif (nullWrites.length > 0) _applyWrites(this.checkpoint, this.channels, [{\n\t\t\tname: INPUT,\n\t\t\twrites: nullWrites,\n\t\t\ttriggers: []\n\t\t}], this.checkpointerGetNextVersion, this.triggerToNodes);\n\t\tconst isCommandUpdateOrGoto = isCommand(this.input) && nullWrites.length > 0;\n\t\tif (this.isResuming || isCommandUpdateOrGoto) {\n\t\t\tfor (const channelName in this.channels) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) continue;\n\t\t\t\tif (this.checkpoint.channel_versions[channelName] !== void 0) {\n\t\t\t\t\tconst version = this.checkpoint.channel_versions[channelName];\n\t\t\t\t\tthis.checkpoint.versions_seen[INTERRUPT] = {\n\t\t\t\t\t\t...this.checkpoint.versions_seen[INTERRUPT],\n\t\t\t\t\t\t[channelName]: version\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), \"values\"));\n\t\t\tthis._emit(valuesOutput);\n\t\t}\n\t\tif (this.isResuming) this.input = INPUT_RESUMING;\n\t\telse if (isCommandUpdateOrGoto) {\n\t\t\tawait this._putCheckpoint({ source: \"input\" });\n\t\t\tthis.input = INPUT_DONE;\n\t\t} else {\n\t\t\tconst inputWrites = await gatherIterator(mapInput(inputKeys, this.input));\n\t\t\tif (inputWrites.length > 0) {\n\t\t\t\tconst discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step });\n\t\t\t\tthis.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{\n\t\t\t\t\tname: INPUT,\n\t\t\t\t\twrites: inputWrites,\n\t\t\t\t\ttriggers: []\n\t\t\t\t}]), this.checkpointerGetNextVersion, this.triggerToNodes);\n\t\t\t\tawait this._putCheckpoint({ source: \"input\" });\n\t\t\t\tthis.input = INPUT_DONE;\n\t\t\t} else if (!(CONFIG_KEY_RESUMING in (this.config.configurable ?? {}))) throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`);\n\t\t\telse this.input = INPUT_DONE;\n\t\t}\n\t\tif (!this.isNested) this.config = patchConfigurable(this.config, { [CONFIG_KEY_RESUMING]: this.isResuming });\n\t}\n\t_emit(values) {\n\t\tfor (const [mode, payload] of values) {\n\t\t\tif (this.stream.modes.has(mode)) this.stream.push([\n\t\t\t\tthis.checkpointNamespace,\n\t\t\t\tmode,\n\t\t\t\tpayload\n\t\t\t]);\n\t\t\tif ((mode === \"checkpoints\" || mode === \"tasks\") && this.stream.modes.has(\"debug\")) {\n\t\t\t\tconst step = mode === \"checkpoints\" ? this.step - 1 : this.step;\n\t\t\t\tconst timestamp = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\t\tconst type = (() => {\n\t\t\t\t\tif (mode === \"checkpoints\") return \"checkpoint\";\n\t\t\t\t\telse if (typeof payload === \"object\" && payload != null && \"result\" in payload) return \"task_result\";\n\t\t\t\t\telse return \"task\";\n\t\t\t\t})();\n\t\t\t\tthis.stream.push([\n\t\t\t\t\tthis.checkpointNamespace,\n\t\t\t\t\t\"debug\",\n\t\t\t\t\t{\n\t\t\t\t\t\tstep,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tpayload\n\t\t\t\t\t}\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\t}\n\t_putCheckpoint(inputMetadata) {\n\t\tconst exiting = this.checkpointMetadata === inputMetadata;\n\t\tconst doCheckpoint = this.checkpointer != null && (this.durability !== \"exit\" || exiting);\n\t\tconst storeCheckpoint = (checkpoint) => {\n\t\t\tthis.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : void 0;\n\t\t\tthis.checkpointConfig = patchConfigurable(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? \"\" });\n\t\t\tconst channelVersions = { ...this.checkpoint.channel_versions };\n\t\t\tconst newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions);\n\t\t\tthis.checkpointPreviousVersions = channelVersions;\n\t\t\tthis._checkpointerPutAfterPrevious({\n\t\t\t\tconfig: { ...this.checkpointConfig },\n\t\t\t\tcheckpoint: copyCheckpoint(checkpoint),\n\t\t\t\tmetadata: { ...this.checkpointMetadata },\n\t\t\t\tnewVersions\n\t\t\t});\n\t\t\tthis.checkpointConfig = {\n\t\t\t\t...this.checkpointConfig,\n\t\t\t\tconfigurable: {\n\t\t\t\t\t...this.checkpointConfig.configurable,\n\t\t\t\t\tcheckpoint_id: this.checkpoint.id\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\tif (!exiting) this.checkpointMetadata = {\n\t\t\t...inputMetadata,\n\t\t\tstep: this.step,\n\t\t\tparents: this.config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] ?? {}\n\t\t};\n\t\tthis.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : void 0, this.step, exiting ? { id: this.checkpoint.id } : void 0);\n\t\tif (doCheckpoint) storeCheckpoint(this.checkpoint);\n\t\tif (!exiting) this.step += 1;\n\t}\n\t_flushPendingWrites() {\n\t\tif (this.checkpointer == null) return;\n\t\tif (this.checkpointPendingWrites.length === 0) return;\n\t\tconst config = patchConfigurable(this.checkpointConfig, {\n\t\t\t[CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? \"\",\n\t\t\t[CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id\n\t\t});\n\t\tconst byTask = {};\n\t\tfor (const [tid, key, value] of this.checkpointPendingWrites) {\n\t\t\tbyTask[tid] ??= [];\n\t\t\tbyTask[tid].push([key, value]);\n\t\t}\n\t\tfor (const [tid, ws] of Object.entries(byTask)) this.checkpointerPromises.push(this.checkpointer.putWrites(config, ws, tid));\n\t}\n\t_matchWrites(tasks) {\n\t\tfor (const [tid, k, v] of this.checkpointPendingWrites) {\n\t\t\tif (k === ERROR || k === INTERRUPT || k === RESUME) continue;\n\t\t\tconst task = Object.values(tasks).find((t) => t.id === tid);\n\t\t\tif (task) task.writes.push([k, v]);\n\t\t}\n\t\tfor (const task of Object.values(tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true);\n\t}\n};\n\n//#endregion\nexport { PregelLoop };\n//# sourceMappingURL=loop.js.map","import { TAG_HIDDEN, TAG_NOSTREAM } from \"../constants.js\";\nimport { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport { AIMessageChunk, isBaseMessage, isBaseMessageChunk, isToolMessage } from \"@langchain/core/messages\";\n\n//#region src/pregel/messages.ts\nfunction isChatGenerationChunk(x) {\n\treturn isBaseMessage(x?.message);\n}\n/**\n* A callback handler that implements stream_mode=messages.\n* Collects messages from (1) chat model stream events and (2) node outputs.\n*/\nvar StreamMessagesHandler = class extends BaseCallbackHandler {\n\tname = \"StreamMessagesHandler\";\n\tstreamFn;\n\tmetadatas = {};\n\tseen = {};\n\temittedChatModelRunIds = {};\n\tstableMessageIdMap = {};\n\tlc_prefer_streaming = true;\n\tconstructor(streamFn) {\n\t\tsuper();\n\t\tthis.streamFn = streamFn;\n\t}\n\t_emit(meta, message, runId, dedupe = false) {\n\t\tif (dedupe && message.id !== void 0 && this.seen[message.id] !== void 0) return;\n\t\tlet messageId = message.id;\n\t\tif (runId != null) if (isToolMessage(message)) messageId ??= `run-${runId}-tool-${message.tool_call_id}`;\n\t\telse {\n\t\t\tif (messageId == null || messageId === `run-${runId}`) messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`;\n\t\t\tthis.stableMessageIdMap[runId] ??= messageId;\n\t\t}\n\t\tif (messageId !== message.id) {\n\t\t\tmessage.id = messageId;\n\t\t\tmessage.lc_kwargs.id = messageId;\n\t\t}\n\t\tif (message.id != null) this.seen[message.id] = message;\n\t\tthis.streamFn([\n\t\t\tmeta[0],\n\t\t\t\"messages\",\n\t\t\t[message, meta[1]]\n\t\t]);\n\t}\n\thandleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) {\n\t\tif (metadata && (!tags || !tags.includes(TAG_NOSTREAM) && !tags.includes(\"nostream\"))) this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split(\"|\"), {\n\t\t\ttags,\n\t\t\tname,\n\t\t\t...metadata\n\t\t}];\n\t}\n\thandleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) {\n\t\tconst chunk = fields?.chunk;\n\t\tthis.emittedChatModelRunIds[runId] = true;\n\t\tif (this.metadatas[runId] !== void 0) if (isChatGenerationChunk(chunk)) this._emit(this.metadatas[runId], chunk.message, runId);\n\t\telse this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId);\n\t}\n\thandleLLMEnd(output, runId) {\n\t\tif (this.metadatas[runId] === void 0) return;\n\t\tif (!this.emittedChatModelRunIds[runId]) {\n\t\t\tconst chatGeneration = output.generations?.[0]?.[0];\n\t\t\tif (isBaseMessage(chatGeneration?.message)) this._emit(this.metadatas[runId], chatGeneration?.message, runId, true);\n\t\t\tdelete this.emittedChatModelRunIds[runId];\n\t\t}\n\t\tdelete this.metadatas[runId];\n\t\tdelete this.stableMessageIdMap[runId];\n\t}\n\thandleLLMError(_err, runId) {\n\t\tdelete this.metadatas[runId];\n\t}\n\thandleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) {\n\t\tif (metadata !== void 0 && name === metadata.langgraph_node && (tags === void 0 || !tags.includes(TAG_HIDDEN))) {\n\t\t\tthis.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split(\"|\"), {\n\t\t\t\ttags,\n\t\t\t\tname,\n\t\t\t\t...metadata\n\t\t\t}];\n\t\t\tif (typeof inputs === \"object\") {\n\t\t\t\tfor (const value of Object.values(inputs)) if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== void 0) this.seen[value.id] = value;\n\t\t\t\telse if (Array.isArray(value)) {\n\t\t\t\t\tfor (const item of value) if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== void 0) this.seen[item.id] = item;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\thandleChainEnd(outputs, runId) {\n\t\tconst metadata = this.metadatas[runId];\n\t\tdelete this.metadatas[runId];\n\t\tif (metadata !== void 0) {\n\t\t\tif (isBaseMessage(outputs)) this._emit(metadata, outputs, runId, true);\n\t\t\telse if (Array.isArray(outputs)) {\n\t\t\t\tfor (const value of outputs) if (isBaseMessage(value)) this._emit(metadata, value, runId, true);\n\t\t\t} else if (outputs != null && typeof outputs === \"object\") {\n\t\t\t\tfor (const value of Object.values(outputs)) if (isBaseMessage(value)) this._emit(metadata, value, runId, true);\n\t\t\t\telse if (Array.isArray(value)) {\n\t\t\t\t\tfor (const item of value) if (isBaseMessage(item)) this._emit(metadata, item, runId, true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\thandleChainError(_err, runId) {\n\t\tdelete this.metadatas[runId];\n\t}\n};\n\n//#endregion\nexport { StreamMessagesHandler };\n//# sourceMappingURL=messages.js.map","import { isGraphBubbleUp, isParentCommand } from \"../errors.js\";\nimport { CONFIG_KEY_RESUMING, Command } from \"../constants.js\";\nimport { getParentCheckpointNamespace } from \"./utils/config.js\";\nimport { patchConfigurable } from \"./utils/index.js\";\n\n//#region src/pregel/retry.ts\nconst DEFAULT_INITIAL_INTERVAL = 500;\nconst DEFAULT_BACKOFF_FACTOR = 2;\nconst DEFAULT_MAX_INTERVAL = 128e3;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_STATUS_NO_RETRY = [\n\t400,\n\t401,\n\t402,\n\t403,\n\t404,\n\t405,\n\t406,\n\t407,\n\t409\n];\nconst DEFAULT_RETRY_ON_HANDLER = (error) => {\n\tif (error.message.startsWith(\"Cancel\") || error.message.startsWith(\"AbortError\") || error.name === \"AbortError\") return false;\n\tif (error.name === \"GraphValueError\") return false;\n\tif (error?.code === \"ECONNABORTED\") return false;\n\tconst status = error?.response?.status ?? error?.status;\n\tif (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) return false;\n\tif (error?.error?.code === \"insufficient_quota\") return false;\n\treturn true;\n};\nasync function _runWithRetry(pregelTask, retryPolicy, configurable, signal) {\n\tconst resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy;\n\tlet interval = resolvedRetryPolicy !== void 0 ? resolvedRetryPolicy.initialInterval ?? DEFAULT_INITIAL_INTERVAL : 0;\n\tlet attempts = 0;\n\tlet error;\n\tlet result;\n\tlet { config } = pregelTask;\n\tif (configurable) config = patchConfigurable(config, configurable);\n\tconfig = {\n\t\t...config,\n\t\tsignal\n\t};\n\twhile (true) {\n\t\tif (signal?.aborted) break;\n\t\tpregelTask.writes.splice(0, pregelTask.writes.length);\n\t\terror = void 0;\n\t\ttry {\n\t\t\tresult = await pregelTask.proc.invoke(pregelTask.input, config);\n\t\t\tbreak;\n\t\t} catch (e) {\n\t\t\terror = e;\n\t\t\terror.pregelTaskId = pregelTask.id;\n\t\t\tif (isParentCommand(error)) {\n\t\t\t\tconst ns = config?.configurable?.checkpoint_ns;\n\t\t\t\tconst cmd = error.command;\n\t\t\t\tif (cmd.graph === ns) {\n\t\t\t\t\tfor (const writer of pregelTask.writers) await writer.invoke(cmd, config);\n\t\t\t\t\terror = void 0;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (cmd.graph === Command.PARENT) {\n\t\t\t\t\tconst parentNs = getParentCheckpointNamespace(ns);\n\t\t\t\t\terror.command = new Command({\n\t\t\t\t\t\t...error.command,\n\t\t\t\t\t\tgraph: parentNs\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isGraphBubbleUp(error)) break;\n\t\t\tif (resolvedRetryPolicy === void 0) break;\n\t\t\tattempts += 1;\n\t\t\tif (attempts >= (resolvedRetryPolicy.maxAttempts ?? DEFAULT_MAX_RETRIES)) break;\n\t\t\tconst retryOn = resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER;\n\t\t\tif (!retryOn(error)) break;\n\t\t\tinterval = Math.min(resolvedRetryPolicy.maxInterval ?? DEFAULT_MAX_INTERVAL, interval * (resolvedRetryPolicy.backoffFactor ?? DEFAULT_BACKOFF_FACTOR));\n\t\t\tconst intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1e3) : interval;\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, intervalWithJitter));\n\t\t\tconst errorName = error.name ?? error.constructor.unminifiable_name ?? error.constructor.name;\n\t\t\tif (resolvedRetryPolicy?.logWarning ?? true) console.log(`Retrying task \"${String(pregelTask.name)}\" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error}`);\n\t\t\tconfig = patchConfigurable(config, { [CONFIG_KEY_RESUMING]: true });\n\t\t}\n\t}\n\treturn {\n\t\ttask: pregelTask,\n\t\tresult,\n\t\terror,\n\t\tsignalAborted: signal?.aborted\n\t};\n}\n\n//#endregion\nexport { _runWithRetry };\n//# sourceMappingURL=retry.js.map","import { isGraphBubbleUp, isGraphInterrupt } from \"../errors.js\";\nimport { CONFIG_KEY_ABORT_SIGNALS, CONFIG_KEY_CALL, CONFIG_KEY_SCRATCHPAD, ERROR, INTERRUPT, NO_WRITES, RESUME, RETURN, TAG_HIDDEN } from \"../constants.js\";\nimport { Call } from \"./types.js\";\nimport { combineAbortSignals, patchConfigurable } from \"./utils/index.js\";\nimport { _runWithRetry } from \"./retry.js\";\n\n//#region src/pregel/runner.ts\nconst PROMISE_ADDED_SYMBOL = Symbol.for(\"promiseAdded\");\nfunction createPromiseBarrier() {\n\tconst barrier = {\n\t\tnext: () => void 0,\n\t\twait: Promise.resolve(PROMISE_ADDED_SYMBOL)\n\t};\n\tfunction waitHandler(resolve) {\n\t\tbarrier.next = () => {\n\t\t\tbarrier.wait = new Promise(waitHandler);\n\t\t\tresolve(PROMISE_ADDED_SYMBOL);\n\t\t};\n\t}\n\tbarrier.wait = new Promise(waitHandler);\n\treturn barrier;\n}\n/**\n* Responsible for handling task execution on each tick of the {@link PregelLoop}.\n*/\nvar PregelRunner = class {\n\tnodeFinished;\n\tloop;\n\t/**\n\t* Construct a new PregelRunner, which executes tasks from the provided PregelLoop.\n\t* @param loop - The PregelLoop that produces tasks for this runner to execute.\n\t*/\n\tconstructor({ loop, nodeFinished }) {\n\t\tthis.loop = loop;\n\t\tthis.nodeFinished = nodeFinished;\n\t}\n\t/**\n\t* Execute tasks from the current step of the PregelLoop.\n\t*\n\t* Note: this method does NOT call {@link PregelLoop}#tick. That must be handled externally.\n\t* @param options - Options for the execution.\n\t*/\n\tasync tick(options = {}) {\n\t\tconst { timeout, retryPolicy, onStepWrite, maxConcurrency } = options;\n\t\tconst nodeErrors = /* @__PURE__ */ new Set();\n\t\tlet graphBubbleUp;\n\t\tconst exceptionSignalController = new AbortController();\n\t\tconst exceptionSignal = exceptionSignalController.signal;\n\t\tconst stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : void 0;\n\t\tconst pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0);\n\t\tconst { signals, disposeCombinedSignal } = this._initializeAbortSignals({\n\t\t\texceptionSignal,\n\t\t\tstepTimeoutSignal,\n\t\t\tsignal: options.signal\n\t\t});\n\t\tconst taskStream = this._executeTasksWithRetry(pendingTasks, {\n\t\t\tsignals,\n\t\t\tretryPolicy,\n\t\t\tmaxConcurrency\n\t\t});\n\t\tfor await (const { task, error, signalAborted } of taskStream) {\n\t\t\tthis._commit(task, error);\n\t\t\tif (isGraphInterrupt(error)) graphBubbleUp = error;\n\t\t\telse if (isGraphBubbleUp(error) && !isGraphInterrupt(graphBubbleUp)) graphBubbleUp = error;\n\t\t\telse if (error && (nodeErrors.size === 0 || !signalAborted)) {\n\t\t\t\texceptionSignalController.abort();\n\t\t\t\tnodeErrors.add(error);\n\t\t\t}\n\t\t}\n\t\tdisposeCombinedSignal?.();\n\t\tonStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task) => task.writes).flat());\n\t\tif (nodeErrors.size === 1) throw Array.from(nodeErrors)[0];\n\t\telse if (nodeErrors.size > 1) throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the \"errors\" field of this exception for more details.`);\n\t\tif (isGraphInterrupt(graphBubbleUp)) throw graphBubbleUp;\n\t\tif (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) throw graphBubbleUp;\n\t}\n\t/**\n\t* Initializes the current AbortSignals for the PregelRunner, handling the various ways that\n\t* AbortSignals must be chained together so that the PregelLoop can be interrupted if necessary\n\t* while still allowing nodes to gracefully exit.\n\t*\n\t* This method must only be called once per PregelRunner#tick. It has the side effect of updating\n\t* the PregelLoop#config with the new AbortSignals so they may be propagated correctly to future\n\t* ticks and subgraph calls.\n\t*\n\t* @param options - Options for the initialization.\n\t* @returns The current abort signals.\n\t* @internal\n\t*/\n\t_initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) {\n\t\tconst previousSignals = this.loop.config.configurable?.[CONFIG_KEY_ABORT_SIGNALS] ?? {};\n\t\tconst externalAbortSignal = previousSignals.externalAbortSignal ?? signal;\n\t\tconst timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal;\n\t\tconst { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal);\n\t\tconst signals = {\n\t\t\texternalAbortSignal,\n\t\t\ttimeoutAbortSignal,\n\t\t\tcomposedAbortSignal\n\t\t};\n\t\tthis.loop.config = patchConfigurable(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals });\n\t\treturn {\n\t\t\tsignals,\n\t\t\tdisposeCombinedSignal\n\t\t};\n\t}\n\t/**\n\t* Concurrently executes tasks with the requested retry policy, yielding a {@link SettledPregelTask} for each task as it completes.\n\t* @param tasks - The tasks to execute.\n\t* @param options - Options for the execution.\n\t*/\n\tasync *_executeTasksWithRetry(tasks, options) {\n\t\tconst { retryPolicy, maxConcurrency, signals } = options ?? {};\n\t\tconst barrier = createPromiseBarrier();\n\t\tconst executingTasksMap = {};\n\t\tconst thisCall = {\n\t\t\texecutingTasksMap,\n\t\t\tbarrier,\n\t\t\tretryPolicy,\n\t\t\tscheduleTask: async (task, writeIdx, call$1) => this.loop.acceptPush(task, writeIdx, call$1)\n\t\t};\n\t\tif (signals?.composedAbortSignal?.aborted) throw new Error(\"Abort\");\n\t\tlet startedTasksCount = 0;\n\t\tlet listener;\n\t\tconst timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal);\n\t\tconst abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => {\n\t\t\tlistener = () => reject(/* @__PURE__ */ new Error(\"Abort\"));\n\t\t\ttimeoutOrCancelSignal.signal?.addEventListener(\"abort\", listener, { once: true });\n\t\t}) : void 0;\n\t\twhile ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) {\n\t\t\tfor (; Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) {\n\t\t\t\tconst task = tasks[startedTasksCount];\n\t\t\t\texecutingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [CONFIG_KEY_CALL]: call?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error) => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tsignalAborted: signals?.composedAbortSignal?.aborted\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst settledTask = await Promise.race([\n\t\t\t\t...Object.values(executingTasksMap),\n\t\t\t\t...abortPromise ? [abortPromise] : [],\n\t\t\t\tbarrier.wait\n\t\t\t]);\n\t\t\tif (settledTask === PROMISE_ADDED_SYMBOL) continue;\n\t\t\tyield settledTask;\n\t\t\tif (listener != null) {\n\t\t\t\ttimeoutOrCancelSignal.signal?.removeEventListener(\"abort\", listener);\n\t\t\t\ttimeoutOrCancelSignal.dispose?.();\n\t\t\t}\n\t\t\tdelete executingTasksMap[settledTask.task.id];\n\t\t}\n\t}\n\t/**\n\t* Determines what writes to apply based on whether the task completed successfully, and what type of error occurred.\n\t*\n\t* Throws an error if the error is a {@link GraphBubbleUp} error and {@link PregelLoop}#isNested is true.\n\t*\n\t* @param task - The task to commit.\n\t* @param error - The error that occurred, if any.\n\t*/\n\t_commit(task, error) {\n\t\tif (error !== void 0) if (isGraphInterrupt(error)) {\n\t\t\tif (error.interrupts.length) {\n\t\t\t\tconst interrupts = error.interrupts.map((interrupt) => [INTERRUPT, interrupt]);\n\t\t\t\tconst resumes = task.writes.filter((w) => w[0] === RESUME);\n\t\t\t\tif (resumes.length) interrupts.push(...resumes);\n\t\t\t\tthis.loop.putWrites(task.id, interrupts);\n\t\t\t}\n\t\t} else if (isGraphBubbleUp(error) && task.writes.length) this.loop.putWrites(task.id, task.writes);\n\t\telse this.loop.putWrites(task.id, [[ERROR, {\n\t\t\tmessage: error.message,\n\t\t\tname: error.name\n\t\t}]]);\n\t\telse {\n\t\t\tif (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes(TAG_HIDDEN))) this.nodeFinished(String(task.name));\n\t\t\tif (task.writes.length === 0) task.writes.push([NO_WRITES, null]);\n\t\t\tthis.loop.putWrites(task.id, task.writes);\n\t\t}\n\t}\n};\nasync function call(runner, task, func, name, input, options = {}) {\n\tconst scratchpad = task.config?.configurable?.[CONFIG_KEY_SCRATCHPAD];\n\tif (!scratchpad) throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`);\n\tconst cnt = scratchpad.callCounter;\n\tscratchpad.callCounter += 1;\n\tconst wcall = new Call({\n\t\tfunc,\n\t\tname,\n\t\tinput,\n\t\tcache: options.cache,\n\t\tretry: options.retry,\n\t\tcallbacks: options.callbacks\n\t});\n\tconst nextTask = await this.scheduleTask(task, cnt, wcall);\n\tif (!nextTask) return void 0;\n\tconst existingPromise = this.executingTasksMap[nextTask.id];\n\tif (existingPromise !== void 0) return existingPromise;\n\tif (nextTask.writes.length > 0) {\n\t\tconst returns = nextTask.writes.filter(([c]) => c === RETURN);\n\t\tconst errors = nextTask.writes.filter(([c]) => c === ERROR);\n\t\tif (returns.length > 0) {\n\t\t\tif (returns.length === 1) return Promise.resolve(returns[0][1]);\n\t\t\tthrow new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`);\n\t\t}\n\t\tif (errors.length > 0) {\n\t\t\tif (errors.length === 1) {\n\t\t\t\tconst errorValue = errors[0][1];\n\t\t\t\tconst error = errorValue instanceof Error ? errorValue : new Error(String(errorValue));\n\t\t\t\treturn Promise.reject(error);\n\t\t\t}\n\t\t\tthrow new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`);\n\t\t}\n\t\treturn void 0;\n\t} else {\n\t\tconst prom = _runWithRetry(nextTask, options.retry, { [CONFIG_KEY_CALL]: call.bind(this, runner, nextTask) });\n\t\tthis.executingTasksMap[nextTask.id] = prom;\n\t\tthis.barrier.next();\n\t\treturn prom.then(({ result, error }) => {\n\t\t\tif (error) return Promise.reject(error);\n\t\t\treturn result;\n\t\t});\n\t}\n}\n\n//#endregion\nexport { PregelRunner };\n//# sourceMappingURL=runner.js.map","import { INTERRUPT } from \"../constants.js\";\nimport { PregelNode } from \"./read.js\";\n\n//#region src/pregel/validate.ts\nvar GraphValidationError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"GraphValidationError\";\n\t}\n};\nfunction validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) {\n\tif (!channels) throw new GraphValidationError(\"Channels not provided\");\n\tconst subscribedChannels = /* @__PURE__ */ new Set();\n\tconst allOutputChannels = /* @__PURE__ */ new Set();\n\tfor (const [name, node] of Object.entries(nodes)) {\n\t\tif (name === INTERRUPT) throw new GraphValidationError(`\"Node name ${INTERRUPT} is reserved\"`);\n\t\tif (node.constructor === PregelNode) node.triggers.forEach((trigger) => subscribedChannels.add(trigger));\n\t\telse throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`);\n\t}\n\tfor (const chan of subscribedChannels) if (!(chan in channels)) throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`);\n\tif (!Array.isArray(inputChannels)) {\n\t\tif (!subscribedChannels.has(inputChannels)) throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`);\n\t} else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`);\n\tif (!Array.isArray(outputChannels)) allOutputChannels.add(outputChannels);\n\telse outputChannels.forEach((chan) => allOutputChannels.add(chan));\n\tif (streamChannels && !Array.isArray(streamChannels)) allOutputChannels.add(streamChannels);\n\telse if (Array.isArray(streamChannels)) streamChannels.forEach((chan) => allOutputChannels.add(chan));\n\tfor (const chan of allOutputChannels) if (!(chan in channels)) throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`);\n\tif (interruptAfterNodes && interruptAfterNodes !== \"*\") {\n\t\tfor (const node of interruptAfterNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`);\n\t}\n\tif (interruptBeforeNodes && interruptBeforeNodes !== \"*\") {\n\t\tfor (const node of interruptBeforeNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`);\n\t}\n}\nfunction validateKeys(keys, channels) {\n\tif (Array.isArray(keys)) {\n\t\tfor (const key of keys) if (!(key in channels)) throw new Error(`Key ${String(key)} not found in channels`);\n\t} else if (!(keys in channels)) throw new Error(`Key ${String(keys)} not found in channels`);\n}\n\n//#endregion\nexport { validateGraph, validateKeys };\n//# sourceMappingURL=validate.js.map","import { EmptyChannelError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\n\n//#region src/channels/topic.ts\n/**\n* A configurable PubSub Topic.\n*/\nvar Topic = class Topic extends BaseChannel {\n\tlc_graph_name = \"Topic\";\n\tunique = false;\n\taccumulate = false;\n\tseen;\n\tvalues;\n\tconstructor(fields) {\n\t\tsuper();\n\t\tthis.unique = fields?.unique ?? this.unique;\n\t\tthis.accumulate = fields?.accumulate ?? this.accumulate;\n\t\tthis.seen = /* @__PURE__ */ new Set();\n\t\tthis.values = [];\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new Topic({\n\t\t\tunique: this.unique,\n\t\t\taccumulate: this.accumulate\n\t\t});\n\t\tif (typeof checkpoint !== \"undefined\") {\n\t\t\tempty.seen = new Set(checkpoint[0]);\n\t\t\tempty.values = checkpoint[1];\n\t\t}\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tlet updated = false;\n\t\tif (!this.accumulate) {\n\t\t\tupdated = this.values.length > 0;\n\t\t\tthis.values = [];\n\t\t}\n\t\tconst flatValues = values.flat();\n\t\tif (flatValues.length > 0) if (this.unique) {\n\t\t\tfor (const value of flatValues) if (!this.seen.has(value)) {\n\t\t\t\tupdated = true;\n\t\t\t\tthis.seen.add(value);\n\t\t\t\tthis.values.push(value);\n\t\t\t}\n\t\t} else {\n\t\t\tupdated = true;\n\t\t\tthis.values.push(...flatValues);\n\t\t}\n\t\treturn updated;\n\t}\n\tget() {\n\t\tif (this.values.length === 0) throw new EmptyChannelError();\n\t\treturn this.values;\n\t}\n\tcheckpoint() {\n\t\treturn [[...this.seen], this.values];\n\t}\n\tisAvailable() {\n\t\treturn this.values.length !== 0;\n\t}\n};\n\n//#endregion\nexport { Topic };\n//# sourceMappingURL=topic.js.map","import { GraphRecursionError, GraphValueError, InvalidUpdateError } from \"../errors.js\";\nimport { createCheckpoint, emptyChannels, getOnlyChannels } from \"../channels/base.js\";\nimport { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_CHECKPOINT_NS, CONFIG_KEY_DURABILITY, CONFIG_KEY_NODE_FINISHED, CONFIG_KEY_READ, CONFIG_KEY_SEND, CONFIG_KEY_STREAM, CONFIG_KEY_TASK_ID, COPY, END, ERROR, INPUT, INTERRUPT, NULL_TASK_ID, PUSH, TASKS, isInterrupted } from \"../constants.js\";\nimport { ensureLangGraphConfig, getConfig, recastCheckpointNamespace } from \"./utils/config.js\";\nimport { gatherIterator, patchConfigurable } from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"./write.js\";\nimport { PregelNode } from \"./read.js\";\nimport { mapInput, readChannels } from \"./io.js\";\nimport { _coerceToDict, combineAbortSignals, combineCallbacks, getNewChannelVersions, patchCheckpointMap } from \"./utils/index.js\";\nimport { _applyWrites, _localRead, _prepareNextTasks } from \"./algo.js\";\nimport { findSubgraphPregel } from \"./utils/subgraph.js\";\nimport { printStepCheckpoint, printStepTasks, printStepWrites, tasksWithWrites } from \"./debug.js\";\nimport { IterableReadableStreamWithAbortSignal, IterableReadableWritableStream, toEventStream } from \"./stream.js\";\nimport { PregelLoop } from \"./loop.js\";\nimport { StreamMessagesHandler } from \"./messages.js\";\nimport { PregelRunner } from \"./runner.js\";\nimport { validateGraph, validateKeys } from \"./validate.js\";\nimport { Topic } from \"../channels/topic.js\";\nimport { interrupt } from \"../interrupt.js\";\nimport { SCHEDULED, compareChannelVersions, copyCheckpoint, emptyCheckpoint, uuid5 } from \"@langchain/langgraph-checkpoint\";\nimport { Runnable, RunnableSequence, _coerceToRunnable, getCallbackManagerForConfig, mergeConfigs, patchConfig } from \"@langchain/core/runnables\";\n\n//#region src/pregel/index.ts\n/**\n* Utility class for working with channels in the Pregel system.\n* Provides static methods for subscribing to channels and writing to them.\n*\n* Channels are the communication pathways between nodes in a Pregel graph.\n* They enable message passing and state updates between different parts of the graph.\n*/\nvar Channel = class {\n\tstatic subscribeTo(channels, options) {\n\t\tconst { key, tags } = {\n\t\t\tkey: void 0,\n\t\t\ttags: void 0,\n\t\t\t...options ?? {}\n\t\t};\n\t\tif (Array.isArray(channels) && key !== void 0) throw new Error(\"Can't specify a key when subscribing to multiple channels\");\n\t\tlet channelMappingOrArray;\n\t\tif (typeof channels === \"string\") if (key) channelMappingOrArray = { [key]: channels };\n\t\telse channelMappingOrArray = [channels];\n\t\telse channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));\n\t\tconst triggers = Array.isArray(channels) ? channels : [channels];\n\t\treturn new PregelNode({\n\t\t\tchannels: channelMappingOrArray,\n\t\t\ttriggers,\n\t\t\ttags\n\t\t});\n\t}\n\t/**\n\t* Creates a ChannelWrite that specifies how to write values to channels.\n\t* This is used to define how nodes send output to channels.\n\t*\n\t* @example\n\t* ```typescript\n\t* // Write to multiple channels\n\t* const write = Channel.writeTo([\"output\", \"state\"]);\n\t*\n\t* // Write with specific values\n\t* const write = Channel.writeTo([\"output\"], {\n\t* state: \"completed\",\n\t* result: calculateResult()\n\t* });\n\t*\n\t* // Write with a transformation function\n\t* const write = Channel.writeTo([\"output\"], {\n\t* result: (x) => processResult(x)\n\t* });\n\t* ```\n\t*\n\t* @param channels - Array of channel names to write to\n\t* @param writes - Optional map of channel names to values or transformations\n\t* @returns A ChannelWrite object that can be used to write to the specified channels\n\t*/\n\tstatic writeTo(channels, writes) {\n\t\tconst channelWriteEntries = [];\n\t\tfor (const channel of channels) channelWriteEntries.push({\n\t\t\tchannel,\n\t\t\tvalue: PASSTHROUGH,\n\t\t\tskipNone: false\n\t\t});\n\t\tfor (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === \"function\") channelWriteEntries.push({\n\t\t\tchannel: key,\n\t\t\tvalue: PASSTHROUGH,\n\t\t\tskipNone: true,\n\t\t\tmapper: _coerceToRunnable(value)\n\t\t});\n\t\telse channelWriteEntries.push({\n\t\t\tchannel: key,\n\t\t\tvalue,\n\t\t\tskipNone: false\n\t\t});\n\t\treturn new ChannelWrite(channelWriteEntries);\n\t}\n};\nvar PartialRunnable = class extends Runnable {\n\tlc_namespace = [\"langgraph\", \"pregel\"];\n\tinvoke(_input, _options) {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\twithConfig(_config) {\n\t\treturn super.withConfig(_config);\n\t}\n\tstream(input, options) {\n\t\treturn super.stream(input, options);\n\t}\n};\n/**\n* The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model\n* inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/).\n* It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.\n*\n* Key features:\n* - Message passing between nodes in discrete \"supersteps\"\n* - Built-in persistence layer through checkpointers\n* - First-class streaming support for values, updates, and events\n* - Human-in-the-loop capabilities via interrupts\n* - Support for parallel node execution within supersteps\n*\n* The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:\n* - {@link StateGraph}: The main graph class for building agent workflows\n* - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel`\n* - Functional API: A declarative approach using tasks and entrypoints\n* - A `Pregel` instance is returned by the {@link entrypoint} function\n*\n* @example\n* ```typescript\n* // Using StateGraph API\n* const graph = new StateGraph(annotation)\n* .addNode(\"nodeA\", myNodeFunction)\n* .addEdge(\"nodeA\", \"nodeB\")\n* .compile();\n*\n* // The compiled graph is a Pregel instance\n* const result = await graph.invoke(input);\n* ```\n*\n* @example\n* ```typescript\n* // Using Functional API\n* import { task, entrypoint } from \"@langchain/langgraph\";\n* import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n*\n* // Define tasks that can be composed\n* const addOne = task(\"add\", async (x: number) => x + 1);\n*\n* // Create a workflow using the entrypoint function\n* const workflow = entrypoint({\n* name: \"workflow\",\n* checkpointer: new MemorySaver()\n* }, async (numbers: number[]) => {\n* // Tasks can be run in parallel\n* const results = await Promise.all(numbers.map(n => addOne(n)));\n* return results;\n* });\n*\n* // The workflow is a Pregel instance\n* const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n* ```\n*\n* @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations\n* @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations\n* @typeParam ContextType - Type of context that can be passed to the graph\n* @typeParam InputType - Type of input values accepted by the graph\n* @typeParam OutputType - Type of output values produced by the graph\n*/\nvar Pregel = class extends PartialRunnable {\n\t/**\n\t* Name of the class when serialized\n\t* @internal\n\t*/\n\tstatic lc_name() {\n\t\treturn \"LangGraph\";\n\t}\n\t/** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */\n\tlc_namespace = [\"langgraph\", \"pregel\"];\n\t/** @internal Flag indicating this is a Pregel instance - necessary for serialization */\n\tlg_is_pregel = true;\n\t/** The nodes in the graph, mapping node names to their PregelNode instances */\n\tnodes;\n\t/** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */\n\tchannels;\n\t/**\n\t* The input channels for the graph. These channels receive the initial input when the graph is invoked.\n\t* Can be a single channel key or an array of channel keys.\n\t*/\n\tinputChannels;\n\t/**\n\t* The output channels for the graph. These channels contain the final output when the graph completes.\n\t* Can be a single channel key or an array of channel keys.\n\t*/\n\toutputChannels;\n\t/** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */\n\tautoValidate = true;\n\t/**\n\t* The streaming modes enabled for this graph. Defaults to [\"values\"].\n\t* Supported modes:\n\t* - \"values\": Streams the full state after each step\n\t* - \"updates\": Streams state updates after each step\n\t* - \"messages\": Streams messages from within nodes\n\t* - \"custom\": Streams custom events from within nodes\n\t* - \"debug\": Streams events related to the execution of the graph - useful for tracing & debugging graph execution\n\t*/\n\tstreamMode = [\"values\"];\n\t/**\n\t* Optional channels to stream. If not specified, all channels will be streamed.\n\t* Can be a single channel key or an array of channel keys.\n\t*/\n\tstreamChannels;\n\t/**\n\t* Optional array of node names or \"all\" to interrupt after executing these nodes.\n\t* Used for implementing human-in-the-loop workflows.\n\t*/\n\tinterruptAfter;\n\t/**\n\t* Optional array of node names or \"all\" to interrupt before executing these nodes.\n\t* Used for implementing human-in-the-loop workflows.\n\t*/\n\tinterruptBefore;\n\t/** Optional timeout in milliseconds for the execution of each superstep */\n\tstepTimeout;\n\t/** Whether to enable debug logging. Defaults to false. */\n\tdebug = false;\n\t/**\n\t* Optional checkpointer for persisting graph state.\n\t* When provided, saves a checkpoint of the graph state at every superstep.\n\t* When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state.\n\t*/\n\tcheckpointer;\n\t/** Optional retry policy for handling failures in node execution */\n\tretryPolicy;\n\t/** The default configuration for graph execution, can be overridden on a per-invocation basis */\n\tconfig;\n\t/**\n\t* Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads\n\t*/\n\tstore;\n\t/**\n\t* Optional cache for the graph, useful for caching tasks.\n\t*/\n\tcache;\n\t/**\n\t* Optional interrupt helper function.\n\t* @internal\n\t*/\n\tuserInterrupt;\n\t/**\n\t* The trigger to node mapping for the graph run.\n\t* @internal\n\t*/\n\ttriggerToNodes = {};\n\t/**\n\t* Constructor for Pregel - meant for internal use only.\n\t*\n\t* @internal\n\t*/\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tlet { streamMode } = fields;\n\t\tif (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode];\n\t\tthis.nodes = fields.nodes;\n\t\tthis.channels = fields.channels;\n\t\tif (TASKS in this.channels && \"lc_graph_name\" in this.channels[TASKS] && this.channels[TASKS].lc_graph_name !== \"Topic\") throw new Error(`Channel '${TASKS}' is reserved and cannot be used in the graph.`);\n\t\telse this.channels[TASKS] = new Topic({ accumulate: false });\n\t\tthis.autoValidate = fields.autoValidate ?? this.autoValidate;\n\t\tthis.streamMode = streamMode ?? this.streamMode;\n\t\tthis.inputChannels = fields.inputChannels;\n\t\tthis.outputChannels = fields.outputChannels;\n\t\tthis.streamChannels = fields.streamChannels ?? this.streamChannels;\n\t\tthis.interruptAfter = fields.interruptAfter;\n\t\tthis.interruptBefore = fields.interruptBefore;\n\t\tthis.stepTimeout = fields.stepTimeout ?? this.stepTimeout;\n\t\tthis.debug = fields.debug ?? this.debug;\n\t\tthis.checkpointer = fields.checkpointer;\n\t\tthis.retryPolicy = fields.retryPolicy;\n\t\tthis.config = fields.config;\n\t\tthis.store = fields.store;\n\t\tthis.cache = fields.cache;\n\t\tthis.name = fields.name;\n\t\tthis.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes;\n\t\tthis.userInterrupt = fields.userInterrupt;\n\t\tif (this.autoValidate) this.validate();\n\t}\n\t/**\n\t* Creates a new instance of the Pregel graph with updated configuration.\n\t* This method follows the immutable pattern - instead of modifying the current instance,\n\t* it returns a new instance with the merged configuration.\n\t*\n\t* @example\n\t* ```typescript\n\t* // Create a new instance with debug enabled\n\t* const debugGraph = graph.withConfig({ debug: true });\n\t*\n\t* // Create a new instance with a specific thread ID\n\t* const threadGraph = graph.withConfig({\n\t* configurable: { thread_id: \"123\" }\n\t* });\n\t* ```\n\t*\n\t* @param config - The configuration to merge with the current configuration\n\t* @returns A new Pregel instance with the merged configuration\n\t*/\n\twithConfig(config) {\n\t\tconst mergedConfig = mergeConfigs(this.config, config);\n\t\treturn new this.constructor({\n\t\t\t...this,\n\t\t\tconfig: mergedConfig\n\t\t});\n\t}\n\t/**\n\t* Validates the graph structure to ensure it is well-formed.\n\t* Checks for:\n\t* - No orphaned nodes\n\t* - Valid input/output channel configurations\n\t* - Valid interrupt configurations\n\t*\n\t* @returns this - The Pregel instance for method chaining\n\t* @throws {GraphValidationError} If the graph structure is invalid\n\t*/\n\tvalidate() {\n\t\tvalidateGraph({\n\t\t\tnodes: this.nodes,\n\t\t\tchannels: this.channels,\n\t\t\toutputChannels: this.outputChannels,\n\t\t\tinputChannels: this.inputChannels,\n\t\t\tstreamChannels: this.streamChannels,\n\t\t\tinterruptAfterNodes: this.interruptAfter,\n\t\t\tinterruptBeforeNodes: this.interruptBefore\n\t\t});\n\t\tfor (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) {\n\t\t\tthis.triggerToNodes[trigger] ??= [];\n\t\t\tthis.triggerToNodes[trigger].push(name);\n\t\t}\n\t\treturn this;\n\t}\n\t/**\n\t* Gets a list of all channels that should be streamed.\n\t* If streamChannels is specified, returns those channels.\n\t* Otherwise, returns all channels in the graph.\n\t*\n\t* @returns Array of channel keys to stream\n\t*/\n\tget streamChannelsList() {\n\t\tif (Array.isArray(this.streamChannels)) return this.streamChannels;\n\t\telse if (this.streamChannels) return [this.streamChannels];\n\t\telse return Object.keys(this.channels);\n\t}\n\t/**\n\t* Gets the channels to stream in their original format.\n\t* If streamChannels is specified, returns it as-is (either single key or array).\n\t* Otherwise, returns all channels in the graph as an array.\n\t*\n\t* @returns Channel keys to stream, either as a single key or array\n\t*/\n\tget streamChannelsAsIs() {\n\t\tif (this.streamChannels) return this.streamChannels;\n\t\telse return Object.keys(this.channels);\n\t}\n\t/**\n\t* Gets a drawable representation of the graph structure.\n\t* This is an async version of getGraph() and is the preferred method to use.\n\t*\n\t* @param config - Configuration for generating the graph visualization\n\t* @returns A representation of the graph that can be visualized\n\t*/\n\tasync getGraphAsync(config) {\n\t\treturn this.getGraph(config);\n\t}\n\t/**\n\t* Gets all subgraphs within this graph.\n\t* A subgraph is a Pregel instance that is nested within a node of this graph.\n\t*\n\t* @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release.\n\t* @param namespace - Optional namespace to filter subgraphs\n\t* @param recurse - Whether to recursively get subgraphs of subgraphs\n\t* @returns Generator yielding tuples of [name, subgraph]\n\t*/\n\t*getSubgraphs(namespace, recurse) {\n\t\tfor (const [name, node] of Object.entries(this.nodes)) {\n\t\t\tif (namespace !== void 0) {\n\t\t\t\tif (!namespace.startsWith(name)) continue;\n\t\t\t}\n\t\t\tconst candidates = node.subgraphs?.length ? node.subgraphs : [node.bound];\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst graph = findSubgraphPregel(candidate);\n\t\t\t\tif (graph !== void 0) {\n\t\t\t\t\tif (name === namespace) {\n\t\t\t\t\t\tyield [name, graph];\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (namespace === void 0) yield [name, graph];\n\t\t\t\t\tif (recurse) {\n\t\t\t\t\t\tlet newNamespace = namespace;\n\t\t\t\t\t\tif (namespace !== void 0) newNamespace = namespace.slice(name.length + 1);\n\t\t\t\t\t\tfor (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t* Gets all subgraphs within this graph asynchronously.\n\t* A subgraph is a Pregel instance that is nested within a node of this graph.\n\t*\n\t* @param namespace - Optional namespace to filter subgraphs\n\t* @param recurse - Whether to recursively get subgraphs of subgraphs\n\t* @returns AsyncGenerator yielding tuples of [name, subgraph]\n\t*/\n\tasync *getSubgraphsAsync(namespace, recurse) {\n\t\tyield* this.getSubgraphs(namespace, recurse);\n\t}\n\t/**\n\t* Prepares a state snapshot from saved checkpoint data.\n\t* This is an internal method used by getState and getStateHistory.\n\t*\n\t* @param config - Configuration for preparing the snapshot\n\t* @param saved - Optional saved checkpoint data\n\t* @param subgraphCheckpointer - Optional checkpointer for subgraphs\n\t* @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels\n\t* @returns A snapshot of the graph state\n\t* @internal\n\t*/\n\tasync _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) {\n\t\tif (saved === void 0) return {\n\t\t\tvalues: {},\n\t\t\tnext: [],\n\t\t\tconfig,\n\t\t\ttasks: []\n\t\t};\n\t\tconst channels = emptyChannels(this.channels, saved.checkpoint);\n\t\tif (saved.pendingWrites?.length) {\n\t\t\tconst nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]);\n\t\t\tif (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{\n\t\t\t\tname: INPUT,\n\t\t\t\twrites: nullWrites,\n\t\t\t\ttriggers: []\n\t\t\t}], void 0, this.triggerToNodes);\n\t\t}\n\t\tconst nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {\n\t\t\tstep: (saved.metadata?.step ?? -1) + 1,\n\t\t\tstore: this.store\n\t\t}));\n\t\tconst subgraphs = await gatherIterator(this.getSubgraphsAsync());\n\t\tconst parentNamespace = saved.config.configurable?.checkpoint_ns ?? \"\";\n\t\tconst taskStates = {};\n\t\tfor (const task of nextTasks) {\n\t\t\tconst matchingSubgraph = subgraphs.find(([name]) => name === task.name);\n\t\t\tif (!matchingSubgraph) continue;\n\t\t\tlet taskNs = `${String(task.name)}${CHECKPOINT_NAMESPACE_END}${task.id}`;\n\t\t\tif (parentNamespace) taskNs = `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`;\n\t\t\tif (subgraphCheckpointer === void 0) {\n\t\t\t\tconst config$1 = { configurable: {\n\t\t\t\t\tthread_id: saved.config.configurable?.thread_id,\n\t\t\t\t\tcheckpoint_ns: taskNs\n\t\t\t\t} };\n\t\t\t\ttaskStates[task.id] = config$1;\n\t\t\t} else {\n\t\t\t\tconst subgraphConfig = { configurable: {\n\t\t\t\t\t[CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer,\n\t\t\t\t\tthread_id: saved.config.configurable?.thread_id,\n\t\t\t\t\tcheckpoint_ns: taskNs\n\t\t\t\t} };\n\t\t\t\tconst pregel = matchingSubgraph[1];\n\t\t\t\ttaskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true });\n\t\t\t}\n\t\t}\n\t\tif (applyPendingWrites && saved.pendingWrites?.length) {\n\t\t\tconst nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task]));\n\t\t\tfor (const [taskId, channel, value] of saved.pendingWrites) {\n\t\t\t\tif ([\n\t\t\t\t\tERROR,\n\t\t\t\t\tINTERRUPT,\n\t\t\t\t\tSCHEDULED\n\t\t\t\t].includes(channel)) continue;\n\t\t\t\tif (!(taskId in nextTaskById)) continue;\n\t\t\t\tnextTaskById[taskId].writes.push([String(channel), value]);\n\t\t\t}\n\t\t\tconst tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0);\n\t\t\tif (tasksWithWrites$1.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes);\n\t\t}\n\t\tlet metadata = saved?.metadata;\n\t\tif (metadata && saved?.config?.configurable?.thread_id) metadata = {\n\t\t\t...metadata,\n\t\t\tthread_id: saved.config.configurable.thread_id\n\t\t};\n\t\tconst nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name);\n\t\treturn {\n\t\t\tvalues: readChannels(channels, this.streamChannelsAsIs),\n\t\t\tnext: nextList,\n\t\t\ttasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs),\n\t\t\tmetadata,\n\t\t\tconfig: patchCheckpointMap(saved.config, saved.metadata),\n\t\t\tcreatedAt: saved.checkpoint.ts,\n\t\t\tparentConfig: saved.parentConfig\n\t\t};\n\t}\n\t/**\n\t* Gets the current state of the graph.\n\t* Requires a checkpointer to be configured.\n\t*\n\t* @param config - Configuration for retrieving the state\n\t* @param options - Additional options\n\t* @returns A snapshot of the current graph state\n\t* @throws {GraphValueError} If no checkpointer is configured\n\t*/\n\tasync getState(config, options) {\n\t\tconst checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;\n\t\tif (!checkpointer) throw new GraphValueError(\"No checkpointer set\", { lc_error_code: \"MISSING_CHECKPOINTER\" });\n\t\tconst checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n\t\tif (checkpointNamespace !== \"\" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {\n\t\t\tconst recastNamespace = recastCheckpointNamespace(checkpointNamespace);\n\t\t\tfor await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs });\n\t\t\tthrow new Error(`Subgraph with namespace \"${recastNamespace}\" not found.`);\n\t\t}\n\t\tconst mergedConfig = mergeConfigs(this.config, config);\n\t\tconst saved = await checkpointer.getTuple(config);\n\t\tconst snapshot = await this._prepareStateSnapshot({\n\t\t\tconfig: mergedConfig,\n\t\t\tsaved,\n\t\t\tsubgraphCheckpointer: options?.subgraphs ? checkpointer : void 0,\n\t\t\tapplyPendingWrites: !config.configurable?.checkpoint_id\n\t\t});\n\t\treturn snapshot;\n\t}\n\t/**\n\t* Gets the history of graph states.\n\t* Requires a checkpointer to be configured.\n\t* Useful for:\n\t* - Debugging execution history\n\t* - Implementing time travel\n\t* - Analyzing graph behavior\n\t*\n\t* @param config - Configuration for retrieving the history\n\t* @param options - Options for filtering the history\n\t* @returns An async iterator of state snapshots\n\t* @throws {Error} If no checkpointer is configured\n\t*/\n\tasync *getStateHistory(config, options) {\n\t\tconst checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;\n\t\tif (!checkpointer) throw new GraphValueError(\"No checkpointer set\", { lc_error_code: \"MISSING_CHECKPOINTER\" });\n\t\tconst checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n\t\tif (checkpointNamespace !== \"\" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {\n\t\t\tconst recastNamespace = recastCheckpointNamespace(checkpointNamespace);\n\t\t\tfor await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) {\n\t\t\t\tyield* pregel.getStateHistory(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Subgraph with namespace \"${recastNamespace}\" not found.`);\n\t\t}\n\t\tconst mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } });\n\t\tfor await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({\n\t\t\tconfig: checkpointTuple.config,\n\t\t\tsaved: checkpointTuple\n\t\t});\n\t}\n\t/**\n\t* Apply updates to the graph state in bulk.\n\t* Requires a checkpointer to be configured.\n\t*\n\t* This method is useful for recreating a thread\n\t* from a list of updates, especially if a checkpoint\n\t* is created as a result of multiple tasks.\n\t*\n\t* @internal The API might change in the future.\n\t*\n\t* @param startConfig - Configuration for the update\n\t* @param updates - The list of updates to apply to graph state\n\t* @returns Updated configuration\n\t* @throws {GraphValueError} If no checkpointer is configured\n\t* @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence.\n\t*/\n\tasync bulkUpdateState(startConfig, supersteps) {\n\t\tconst checkpointer = startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;\n\t\tif (!checkpointer) throw new GraphValueError(\"No checkpointer set\", { lc_error_code: \"MISSING_CHECKPOINTER\" });\n\t\tif (supersteps.length === 0) throw new Error(\"No supersteps provided\");\n\t\tif (supersteps.some((s) => s.updates.length === 0)) throw new Error(\"No updates provided\");\n\t\tconst checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? \"\";\n\t\tif (checkpointNamespace !== \"\" && startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {\n\t\t\tconst recastNamespace = recastCheckpointNamespace(checkpointNamespace);\n\t\t\tfor await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps);\n\t\t\tthrow new Error(`Subgraph \"${recastNamespace}\" not found`);\n\t\t}\n\t\tconst updateSuperStep = async (inputConfig, updates) => {\n\t\t\tconst config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig;\n\t\t\tconst saved = await checkpointer.getTuple(config);\n\t\t\tconst checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint();\n\t\t\tconst checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions };\n\t\t\tconst step = saved?.metadata?.step ?? -1;\n\t\t\tlet checkpointConfig = patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? \"\" });\n\t\t\tlet checkpointMetadata = config.metadata ?? {};\n\t\t\tif (saved?.config.configurable) {\n\t\t\t\tcheckpointConfig = patchConfigurable(config, saved.config.configurable);\n\t\t\t\tcheckpointMetadata = {\n\t\t\t\t\t...saved.metadata,\n\t\t\t\t\t...checkpointMetadata\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst { values, asNode } = updates[0];\n\t\t\tif (values == null && asNode === void 0) {\n\t\t\t\tif (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`);\n\t\t\t\tconst nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), {\n\t\t\t\t\tsource: \"update\",\n\t\t\t\t\tstep: step + 1,\n\t\t\t\t\tparents: saved?.metadata?.parents ?? {}\n\t\t\t\t}, {});\n\t\t\t\treturn patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);\n\t\t\t}\n\t\t\tconst channels = emptyChannels(this.channels, checkpoint);\n\t\t\tif (values === null && asNode === END) {\n\t\t\t\tif (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`);\n\t\t\t\tif (saved) {\n\t\t\t\t\tconst nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, {\n\t\t\t\t\t\tstep: (saved.metadata?.step ?? -1) + 1,\n\t\t\t\t\t\tcheckpointer,\n\t\t\t\t\t\tstore: this.store\n\t\t\t\t\t});\n\t\t\t\t\tconst nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));\n\t\t\t\t\tif (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{\n\t\t\t\t\t\tname: INPUT,\n\t\t\t\t\t\twrites: nullWrites,\n\t\t\t\t\t\ttriggers: []\n\t\t\t\t\t}], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);\n\t\t\t\t\tfor (const [taskId, k, v] of saved.pendingWrites || []) {\n\t\t\t\t\t\tif ([\n\t\t\t\t\t\t\tERROR,\n\t\t\t\t\t\t\tINTERRUPT,\n\t\t\t\t\t\t\tSCHEDULED\n\t\t\t\t\t\t].includes(k)) continue;\n\t\t\t\t\t\tif (!(taskId in nextTasks)) continue;\n\t\t\t\t\t\tnextTasks[taskId].writes.push([k, v]);\n\t\t\t\t\t}\n\t\t\t\t\t_applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);\n\t\t\t\t}\n\t\t\t\tconst nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), {\n\t\t\t\t\t...checkpointMetadata,\n\t\t\t\t\tsource: \"update\",\n\t\t\t\t\tstep: step + 1,\n\t\t\t\t\tparents: saved?.metadata?.parents ?? {}\n\t\t\t\t}, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));\n\t\t\t\treturn patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);\n\t\t\t}\n\t\t\tif (asNode === COPY) {\n\t\t\t\tif (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`);\n\t\t\t\tif (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`);\n\t\t\t\tconst isCopyWithUpdates = (values$1) => {\n\t\t\t\t\tif (!Array.isArray(values$1)) return false;\n\t\t\t\t\tif (values$1.length === 0) return false;\n\t\t\t\t\treturn values$1.every((v) => Array.isArray(v) && v.length === 2);\n\t\t\t\t};\n\t\t\t\tconst nextCheckpoint = createCheckpoint(checkpoint, void 0, step);\n\t\t\t\tconst nextConfig$1 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, {\n\t\t\t\t\tsource: \"fork\",\n\t\t\t\t\tstep: step + 1,\n\t\t\t\t\tparents: saved.metadata?.parents ?? {}\n\t\t\t\t}, {});\n\t\t\t\tif (isCopyWithUpdates(values)) {\n\t\t\t\t\tconst nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 });\n\t\t\t\t\tconst tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => {\n\t\t\t\t\t\tacc[name] ??= [];\n\t\t\t\t\t\tacc[name].push({ id });\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, {});\n\t\t\t\t\tconst userGroupBy = values.reduce((acc, item) => {\n\t\t\t\t\t\tconst [values$1, asNode$1] = item;\n\t\t\t\t\t\tacc[asNode$1] ??= [];\n\t\t\t\t\t\tconst targetIdx = acc[asNode$1].length;\n\t\t\t\t\t\tconst taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id;\n\t\t\t\t\t\tacc[asNode$1].push({\n\t\t\t\t\t\t\tvalues: values$1,\n\t\t\t\t\t\t\tasNode: asNode$1,\n\t\t\t\t\t\t\ttaskId\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, {});\n\t\t\t\t\treturn updateSuperStep(patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat());\n\t\t\t\t}\n\t\t\t\treturn patchCheckpointMap(nextConfig$1, saved.metadata);\n\t\t\t}\n\t\t\tif (asNode === INPUT) {\n\t\t\t\tif (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`);\n\t\t\t\tconst inputWrites = await gatherIterator(mapInput(this.inputChannels, values));\n\t\t\t\tif (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`);\n\t\t\t\t_applyWrites(checkpoint, channels, [{\n\t\t\t\t\tname: INPUT,\n\t\t\t\t\twrites: inputWrites,\n\t\t\t\t\ttriggers: []\n\t\t\t\t}], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);\n\t\t\t\tconst nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1;\n\t\t\t\tconst nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), {\n\t\t\t\t\tsource: \"input\",\n\t\t\t\t\tstep: nextStep,\n\t\t\t\t\tparents: saved?.metadata?.parents ?? {}\n\t\t\t\t}, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));\n\t\t\t\tawait checkpointer.putWrites(nextConfig$1, inputWrites, uuid5(INPUT, checkpoint.id));\n\t\t\t\treturn patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);\n\t\t\t}\n\t\t\tif (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) {\n\t\t\t\tconst nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {\n\t\t\t\t\tstore: this.store,\n\t\t\t\t\tcheckpointer: this.checkpointer,\n\t\t\t\t\tstep: (saved.metadata?.step ?? -1) + 1\n\t\t\t\t});\n\t\t\t\tconst nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));\n\t\t\t\tif (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{\n\t\t\t\t\tname: INPUT,\n\t\t\t\t\twrites: nullWrites,\n\t\t\t\t\ttriggers: []\n\t\t\t\t}], void 0, this.triggerToNodes);\n\t\t\t\tfor (const [tid, k, v] of saved.pendingWrites) {\n\t\t\t\t\tif ([\n\t\t\t\t\t\tERROR,\n\t\t\t\t\t\tINTERRUPT,\n\t\t\t\t\t\tSCHEDULED\n\t\t\t\t\t].includes(k) || nextTasks[tid] === void 0) continue;\n\t\t\t\t\tnextTasks[tid].writes.push([k, v]);\n\t\t\t\t}\n\t\t\t\tconst tasks$1 = Object.values(nextTasks).filter((task) => {\n\t\t\t\t\treturn task.writes.length > 0;\n\t\t\t\t});\n\t\t\t\tif (tasks$1.length > 0) _applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes);\n\t\t\t}\n\t\t\tconst nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => {\n\t\t\t\treturn Object.values(seenVersions);\n\t\t\t}).flat().find((v) => !!v);\n\t\t\tconst validUpdates = [];\n\t\t\tif (updates.length === 1) {\n\t\t\t\tlet { values: values$1, asNode: asNode$1, taskId } = updates[0];\n\t\t\t\tif (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes);\n\t\t\t\telse if (asNode$1 === void 0 && nonNullVersion === void 0) {\n\t\t\t\t\tif (typeof this.inputChannels === \"string\" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels;\n\t\t\t\t} else if (asNode$1 === void 0) {\n\t\t\t\t\tconst lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => {\n\t\t\t\t\t\treturn Object.values(seen).map((v) => {\n\t\t\t\t\t\t\treturn [v, n];\n\t\t\t\t\t\t});\n\t\t\t\t\t}).flat().filter(([_, v]) => v !== INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber));\n\t\t\t\t\tif (lastSeenByNode) {\n\t\t\t\t\t\tif (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1];\n\t\t\t\t\t\telse if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (asNode$1 === void 0) throw new InvalidUpdateError(`Ambiguous update, specify \"asNode\"`);\n\t\t\t\tvalidUpdates.push({\n\t\t\t\t\tvalues: values$1,\n\t\t\t\t\tasNode: asNode$1,\n\t\t\t\t\ttaskId\n\t\t\t\t});\n\t\t\t} else for (const { asNode: asNode$1, values: values$1, taskId } of updates) {\n\t\t\t\tif (asNode$1 == null) throw new InvalidUpdateError(`\"asNode\" is required when applying multiple updates`);\n\t\t\t\tvalidUpdates.push({\n\t\t\t\t\tvalues: values$1,\n\t\t\t\t\tasNode: asNode$1,\n\t\t\t\t\ttaskId\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst tasks = [];\n\t\t\tfor (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) {\n\t\t\t\tif (this.nodes[asNode$1] === void 0) throw new InvalidUpdateError(`Node \"${asNode$1.toString()}\" does not exist`);\n\t\t\t\tconst writers = this.nodes[asNode$1].getWriters();\n\t\t\t\tif (!writers.length) throw new InvalidUpdateError(`No writers found for node \"${asNode$1.toString()}\"`);\n\t\t\t\ttasks.push({\n\t\t\t\t\tname: asNode$1,\n\t\t\t\t\tinput: values$1,\n\t\t\t\t\tproc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0],\n\t\t\t\t\twrites: [],\n\t\t\t\t\ttriggers: [INTERRUPT],\n\t\t\t\t\tid: taskId ?? uuid5(INTERRUPT, checkpoint.id),\n\t\t\t\t\twriters: []\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const task of tasks) await task.proc.invoke(task.input, patchConfig({\n\t\t\t\t...config,\n\t\t\t\tstore: config?.store ?? this.store\n\t\t\t}, {\n\t\t\t\trunName: config.runName ?? `${this.getName()}UpdateState`,\n\t\t\t\tconfigurable: {\n\t\t\t\t\t[CONFIG_KEY_SEND]: (items) => task.writes.push(...items),\n\t\t\t\t\t[CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_)\n\t\t\t\t}\n\t\t\t}));\n\t\t\tfor (const task of tasks) {\n\t\t\t\tconst channelWrites = task.writes.filter((w) => w[0] !== PUSH);\n\t\t\t\tif (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id);\n\t\t\t}\n\t\t\t_applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);\n\t\t\tconst newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions);\n\t\t\tconst nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), {\n\t\t\t\tsource: \"update\",\n\t\t\t\tstep: step + 1,\n\t\t\t\tparents: saved?.metadata?.parents ?? {}\n\t\t\t}, newVersions);\n\t\t\tfor (const task of tasks) {\n\t\t\t\tconst pushWrites = task.writes.filter((w) => w[0] === PUSH);\n\t\t\t\tif (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id);\n\t\t\t}\n\t\t\treturn patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0);\n\t\t};\n\t\tlet currentConfig = startConfig;\n\t\tfor (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates);\n\t\treturn currentConfig;\n\t}\n\t/**\n\t* Updates the state of the graph with new values.\n\t* Requires a checkpointer to be configured.\n\t*\n\t* This method can be used for:\n\t* - Implementing human-in-the-loop workflows\n\t* - Modifying graph state during breakpoints\n\t* - Integrating external inputs into the graph\n\t*\n\t* @param inputConfig - Configuration for the update\n\t* @param values - The values to update the state with\n\t* @param asNode - Optional node name to attribute the update to\n\t* @returns Updated configuration\n\t* @throws {GraphValueError} If no checkpointer is configured\n\t* @throws {InvalidUpdateError} If the update cannot be attributed to a node\n\t*/\n\tasync updateState(inputConfig, values, asNode) {\n\t\treturn this.bulkUpdateState(inputConfig, [{ updates: [{\n\t\t\tvalues,\n\t\t\tasNode\n\t\t}] }]);\n\t}\n\t/**\n\t* Gets the default values for various graph configuration options.\n\t* This is an internal method used to process and normalize configuration options.\n\t*\n\t* @param config - The input configuration options\n\t* @returns A tuple containing normalized values for:\n\t* - debug mode\n\t* - stream modes\n\t* - input keys\n\t* - output keys\n\t* - remaining config\n\t* - interrupt before nodes\n\t* - interrupt after nodes\n\t* - checkpointer\n\t* - store\n\t* - whether stream mode is single\n\t* - node cache\n\t* - whether checkpoint during is enabled\n\t* @internal\n\t*/\n\t_defaults(config) {\n\t\tconst { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config;\n\t\tlet streamModeSingle = true;\n\t\tconst defaultDebug = debug !== void 0 ? debug : this.debug;\n\t\tlet defaultOutputKeys = outputKeys;\n\t\tif (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs;\n\t\telse validateKeys(defaultOutputKeys, this.channels);\n\t\tlet defaultInputKeys = inputKeys;\n\t\tif (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels;\n\t\telse validateKeys(defaultInputKeys, this.channels);\n\t\tconst defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];\n\t\tconst defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];\n\t\tlet defaultStreamMode;\n\t\tif (streamMode !== void 0) {\n\t\t\tdefaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode];\n\t\t\tstreamModeSingle = typeof streamMode === \"string\";\n\t\t} else {\n\t\t\tif (config.configurable?.[CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = [\"values\"];\n\t\t\telse defaultStreamMode = this.streamMode;\n\t\t\tstreamModeSingle = true;\n\t\t}\n\t\tlet defaultCheckpointer;\n\t\tif (this.checkpointer === false) defaultCheckpointer = void 0;\n\t\telse if (config !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER];\n\t\telse if (this.checkpointer === true) throw new Error(\"checkpointer: true cannot be used for root graphs.\");\n\t\telse defaultCheckpointer = this.checkpointer;\n\t\tconst defaultStore = config.store ?? this.store;\n\t\tconst defaultCache = config.cache ?? this.cache;\n\t\tif (config.durability != null && config.checkpointDuring != null) throw new Error(\"Cannot use both `durability` and `checkpointDuring` at the same time.\");\n\t\tconst checkpointDuringDurability = (() => {\n\t\t\tif (config.checkpointDuring == null) return void 0;\n\t\t\tif (config.checkpointDuring === false) return \"exit\";\n\t\t\treturn \"async\";\n\t\t})();\n\t\tconst defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[CONFIG_KEY_DURABILITY] ?? \"async\";\n\t\treturn [\n\t\t\tdefaultDebug,\n\t\t\tdefaultStreamMode,\n\t\t\tdefaultInputKeys,\n\t\t\tdefaultOutputKeys,\n\t\t\trest,\n\t\t\tdefaultInterruptBefore,\n\t\t\tdefaultInterruptAfter,\n\t\t\tdefaultCheckpointer,\n\t\t\tdefaultStore,\n\t\t\tstreamModeSingle,\n\t\t\tdefaultCache,\n\t\t\tdefaultDurability\n\t\t];\n\t}\n\t/**\n\t* Streams the execution of the graph, emitting state updates as they occur.\n\t* This is the primary method for observing graph execution in real-time.\n\t*\n\t* Stream modes:\n\t* - \"values\": Emits complete state after each step\n\t* - \"updates\": Emits only state changes after each step\n\t* - \"debug\": Emits detailed debug information\n\t* - \"messages\": Emits messages from within nodes\n\t* - \"custom\": Emits custom events from within nodes\n\t* - \"checkpoints\": Emits checkpoints from within nodes\n\t* - \"tasks\": Emits tasks from within nodes\n\t*\n\t* @param input - The input to start graph execution with\n\t* @param options - Configuration options for streaming\n\t* @returns An async iterable stream of graph state updates\n\t*/\n\tasync stream(input, options) {\n\t\tconst abortController = new AbortController();\n\t\tconst config = {\n\t\t\trecursionLimit: this.config?.recursionLimit,\n\t\t\t...options,\n\t\t\tsignal: combineAbortSignals(options?.signal, abortController.signal).signal\n\t\t};\n\t\tconst stream = await super.stream(input, config);\n\t\treturn new IterableReadableStreamWithAbortSignal(options?.encoding === \"text/event-stream\" ? toEventStream(stream) : stream, abortController);\n\t}\n\tstreamEvents(input, options, streamOptions) {\n\t\tconst abortController = new AbortController();\n\t\tconst config = {\n\t\t\trecursionLimit: this.config?.recursionLimit,\n\t\t\t...options,\n\t\t\tcallbacks: combineCallbacks(this.config?.callbacks, options?.callbacks),\n\t\t\tsignal: combineAbortSignals(options?.signal, abortController.signal).signal\n\t\t};\n\t\treturn new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController);\n\t}\n\t/**\n\t* Validates the input for the graph.\n\t* @param input - The input to validate\n\t* @returns The validated input\n\t* @internal\n\t*/\n\tasync _validateInput(input) {\n\t\treturn input;\n\t}\n\t/**\n\t* Validates the context options for the graph.\n\t* @param context - The context options to validate\n\t* @returns The validated context options\n\t* @internal\n\t*/\n\tasync _validateContext(context) {\n\t\treturn context;\n\t}\n\t/**\n\t* Internal iterator used by stream() to generate state updates.\n\t* This method handles the core logic of graph execution and streaming.\n\t*\n\t* @param input - The input to start graph execution with\n\t* @param options - Configuration options for streaming\n\t* @returns AsyncGenerator yielding state updates\n\t* @internal\n\t*/\n\tasync *_streamIterator(input, options) {\n\t\tconst streamEncoding = \"version\" in (options ?? {}) ? void 0 : options?.encoding ?? void 0;\n\t\tconst streamSubgraphs = options?.subgraphs;\n\t\tconst inputConfig = ensureLangGraphConfig(this.config, options);\n\t\tif (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed \"recursionLimit\" must be at least 1.`);\n\t\tif (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following \"configurable\" keys: \"thread_id\", \"checkpoint_ns\", \"checkpoint_id\"`);\n\t\tconst validInput = await this._validateInput(input);\n\t\tconst { runId,...restConfig } = inputConfig;\n\t\tconst [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig);\n\t\tif (typeof config.context !== \"undefined\") config.context = await this._validateContext(config.context);\n\t\telse config.configurable = await this._validateContext(config.configurable);\n\t\tconst stream = new IterableReadableWritableStream({ modes: new Set(streamMode) });\n\t\tif (this.checkpointer === true) {\n\t\t\tconfig.configurable ??= {};\n\t\t\tconst ns = config.configurable[CONFIG_KEY_CHECKPOINT_NS] ?? \"\";\n\t\t\tconfig.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split(CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR);\n\t\t}\n\t\tif (streamMode.includes(\"messages\")) {\n\t\t\tconst messageStreamer = new StreamMessagesHandler((chunk) => stream.push(chunk));\n\t\t\tconst { callbacks } = config;\n\t\t\tif (callbacks === void 0) config.callbacks = [messageStreamer];\n\t\t\telse if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer);\n\t\t\telse {\n\t\t\t\tconst copiedCallbacks = callbacks.copy();\n\t\t\t\tcopiedCallbacks.addHandler(messageStreamer, true);\n\t\t\t\tconfig.callbacks = copiedCallbacks;\n\t\t\t}\n\t\t}\n\t\tconfig.writer ??= (chunk) => {\n\t\t\tif (!streamMode.includes(\"custom\")) return;\n\t\t\tconst ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split(CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1);\n\t\t\tstream.push([\n\t\t\t\tns ?? [],\n\t\t\t\t\"custom\",\n\t\t\t\tchunk\n\t\t\t]);\n\t\t};\n\t\tconfig.interrupt ??= this.userInterrupt ?? interrupt;\n\t\tconst callbackManager = await getCallbackManagerForConfig(config);\n\t\tconst runManager = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(input, \"input\"), runId, void 0, void 0, void 0, config?.runName ?? this.getName());\n\t\tconst channelSpecs = getOnlyChannels(this.channels);\n\t\tlet loop;\n\t\tlet loopError;\n\t\t/**\n\t\t* The PregelLoop will yield events from concurrent tasks as soon as they are\n\t\t* generated. Each task can push multiple events onto the stream in any order.\n\t\t*\n\t\t* We use a separate background method and stream here in order to yield events\n\t\t* from the loop to the main stream and therefore back to the user as soon as\n\t\t* they are available.\n\t\t*/\n\t\tconst createAndRunLoop = async () => {\n\t\t\ttry {\n\t\t\t\tloop = await PregelLoop.initialize({\n\t\t\t\t\tinput: validInput,\n\t\t\t\t\tconfig,\n\t\t\t\t\tcheckpointer,\n\t\t\t\t\tnodes: this.nodes,\n\t\t\t\t\tchannelSpecs,\n\t\t\t\t\toutputKeys,\n\t\t\t\t\tstreamKeys: this.streamChannelsAsIs,\n\t\t\t\t\tstore,\n\t\t\t\t\tcache,\n\t\t\t\t\tstream,\n\t\t\t\t\tinterruptAfter,\n\t\t\t\t\tinterruptBefore,\n\t\t\t\t\tmanager: runManager,\n\t\t\t\t\tdebug: this.debug,\n\t\t\t\t\ttriggerToNodes: this.triggerToNodes,\n\t\t\t\t\tdurability\n\t\t\t\t});\n\t\t\t\tconst runner = new PregelRunner({\n\t\t\t\t\tloop,\n\t\t\t\t\tnodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED]\n\t\t\t\t});\n\t\t\t\tif (options?.subgraphs) loop.config.configurable = {\n\t\t\t\t\t...loop.config.configurable,\n\t\t\t\t\t[CONFIG_KEY_STREAM]: loop.stream\n\t\t\t\t};\n\t\t\t\tawait this._runLoop({\n\t\t\t\t\tloop,\n\t\t\t\t\trunner,\n\t\t\t\t\tdebug,\n\t\t\t\t\tconfig\n\t\t\t\t});\n\t\t\t\tif (durability === \"sync\") await Promise.all(loop?.checkpointerPromises ?? []);\n\t\t\t} catch (e) {\n\t\t\t\tloopError = e;\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tif (loop) {\n\t\t\t\t\t\tawait loop.store?.stop();\n\t\t\t\t\t\tawait loop.cache?.stop();\n\t\t\t\t\t}\n\t\t\t\t\tawait Promise.all(loop?.checkpointerPromises ?? []);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tloopError = loopError ?? e;\n\t\t\t\t}\n\t\t\t\tif (loopError) stream.error(loopError);\n\t\t\t\telse stream.close();\n\t\t\t}\n\t\t};\n\t\tconst runLoopPromise = createAndRunLoop();\n\t\ttry {\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tif (chunk === void 0) throw new Error(\"Data structure error.\");\n\t\t\t\tconst [namespace, mode, payload] = chunk;\n\t\t\t\tif (streamMode.includes(mode)) {\n\t\t\t\t\tif (streamEncoding === \"text/event-stream\") {\n\t\t\t\t\t\tif (streamSubgraphs) yield [\n\t\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\t\tmode,\n\t\t\t\t\t\t\tpayload\n\t\t\t\t\t\t];\n\t\t\t\t\t\telse yield [\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\tmode,\n\t\t\t\t\t\t\tpayload\n\t\t\t\t\t\t];\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (streamSubgraphs && !streamModeSingle) yield [\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tmode,\n\t\t\t\t\t\tpayload\n\t\t\t\t\t];\n\t\t\t\t\telse if (!streamModeSingle) yield [mode, payload];\n\t\t\t\t\telse if (streamSubgraphs) yield [namespace, payload];\n\t\t\t\t\telse yield payload;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tawait runManager?.handleChainError(loopError);\n\t\t\tthrow e;\n\t\t} finally {\n\t\t\tawait runLoopPromise;\n\t\t}\n\t\tawait runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0);\n\t}\n\t/**\n\t* Run the graph with a single input and config.\n\t* @param input The input to the graph.\n\t* @param options The configuration to use for the run.\n\t*/\n\tasync invoke(input, options) {\n\t\tconst streamMode = options?.streamMode ?? \"values\";\n\t\tconst config = {\n\t\t\t...options,\n\t\t\toutputKeys: options?.outputKeys ?? this.outputChannels,\n\t\t\tstreamMode,\n\t\t\tencoding: void 0\n\t\t};\n\t\tconst chunks = [];\n\t\tconst stream = await this.stream(input, config);\n\t\tconst interruptChunks = [];\n\t\tlet latest;\n\t\tfor await (const chunk of stream) if (streamMode === \"values\") if (isInterrupted(chunk)) interruptChunks.push(chunk[INTERRUPT]);\n\t\telse latest = chunk;\n\t\telse chunks.push(chunk);\n\t\tif (streamMode === \"values\") {\n\t\t\tif (interruptChunks.length > 0) {\n\t\t\t\tconst interrupts = interruptChunks.flat(1);\n\t\t\t\tif (latest == null) return { [INTERRUPT]: interrupts };\n\t\t\t\tif (typeof latest === \"object\") return {\n\t\t\t\t\t...latest,\n\t\t\t\t\t[INTERRUPT]: interrupts\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn latest;\n\t\t}\n\t\treturn chunks;\n\t}\n\tasync _runLoop(params) {\n\t\tconst { loop, runner, debug, config } = params;\n\t\tlet tickError;\n\t\ttry {\n\t\t\twhile (await loop.tick({ inputKeys: this.inputChannels })) {\n\t\t\t\tfor (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true);\n\t\t\t\tif (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);\n\t\t\t\tif (debug) printStepTasks(loop.step, Object.values(loop.tasks));\n\t\t\t\tawait runner.tick({\n\t\t\t\t\ttimeout: this.stepTimeout,\n\t\t\t\t\tretryPolicy: this.retryPolicy,\n\t\t\t\t\tonStepWrite: (step, writes) => {\n\t\t\t\t\t\tif (debug) printStepWrites(step, writes, this.streamChannelsList);\n\t\t\t\t\t},\n\t\t\t\t\tmaxConcurrency: config.maxConcurrency,\n\t\t\t\t\tsignal: config.signal\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (loop.status === \"out_of_steps\") throw new GraphRecursionError([\n\t\t\t\t`Recursion limit of ${config.recursionLimit} reached`,\n\t\t\t\t\"without hitting a stop condition. You can increase the\",\n\t\t\t\t`limit by setting the \"recursionLimit\" config key.`\n\t\t\t].join(\" \"), { lc_error_code: \"GRAPH_RECURSION_LIMIT\" });\n\t\t} catch (e) {\n\t\t\ttickError = e;\n\t\t\tconst suppress = await loop.finishAndHandleError(tickError);\n\t\t\tif (!suppress) throw e;\n\t\t} finally {\n\t\t\tif (tickError === void 0) await loop.finishAndHandleError();\n\t\t}\n\t}\n\tasync clearCache() {\n\t\tawait this.cache?.clear([]);\n\t}\n};\n\n//#endregion\nexport { Channel, Pregel };\n//# sourceMappingURL=index.js.map","import { EmptyChannelError, InvalidUpdateError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\n\n//#region src/channels/ephemeral_value.ts\n/**\n* Stores the value received in the step immediately preceding, clears after.\n*/\nvar EphemeralValue = class EphemeralValue extends BaseChannel {\n\tlc_graph_name = \"EphemeralValue\";\n\tguard;\n\tvalue = [];\n\tconstructor(guard = true) {\n\t\tsuper();\n\t\tthis.guard = guard;\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new EphemeralValue(this.guard);\n\t\tif (typeof checkpoint !== \"undefined\") empty.value = [checkpoint];\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tif (values.length === 0) {\n\t\t\tconst updated = this.value.length > 0;\n\t\t\tthis.value = [];\n\t\t\treturn updated;\n\t\t}\n\t\tif (values.length !== 1 && this.guard) throw new InvalidUpdateError(\"EphemeralValue can only receive one value per step.\");\n\t\tthis.value = [values[values.length - 1]];\n\t\treturn true;\n\t}\n\tget() {\n\t\tif (this.value.length === 0) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tcheckpoint() {\n\t\tif (this.value.length === 0) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tisAvailable() {\n\t\treturn this.value.length !== 0;\n\t}\n};\n\n//#endregion\nexport { EphemeralValue };\n//# sourceMappingURL=ephemeral_value.js.map","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => inst.issues.push(issue),\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => inst.issues.push(...issues),\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n inst.def = def;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }\n // { parent: true }\n );\n };\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst.element = def.element;\n inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return literal(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodType.init(inst, def);\n util.defineLazy(inst, \"shape\", () => def.shape);\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n // inst.nonstrict = () => inst.clone({ ...inst._zod.def, catchall: api.unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n get shape() {\n util.assignProp(this, \"shape\", { ...shape });\n return this.shape;\n },\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n get shape() {\n util.assignProp(this, \"shape\", { ...shape });\n return this.shape;\n },\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n get shape() {\n util.assignProp(this, \"shape\", { ...shape });\n return this.shape;\n },\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType: union([keyType, never()]),\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n _issue.continue ?? (_issue.continue = true);\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : defaultValue;\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : defaultValue;\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n const ch = check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort);\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\nfunction _instanceof(cls, params = {\n error: `Input not instance of ${cls.name}`,\n}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Pipe: ZodPipe,\n Boolean: ZodBoolean,\n String: ZodString,\n Transform: ZodTransform,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","import uuid from './dist/index.js';\nexport const v1 = uuid.v1;\nexport const v1ToV6 = uuid.v1ToV6;\nexport const v3 = uuid.v3;\nexport const v4 = uuid.v4;\nexport const v5 = uuid.v5;\nexport const v6 = uuid.v6;\nexport const v6ToV1 = uuid.v6ToV1;\nexport const v7 = uuid.v7;\nexport const NIL = uuid.NIL;\nexport const MAX = uuid.MAX;\nexport const version = uuid.version;\nexport const validate = uuid.validate;\nexport const stringify = uuid.stringify;\nexport const parse = uuid.parse;\n","import { InvalidUpdateError, NodeInterrupt, UnreachableNodeError } from \"../errors.js\";\nimport { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, END, START, TAG_HIDDEN, _isSend } from \"../constants.js\";\nimport { RunnableCallable, gatherIterator, gatherIteratorSync } from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport { isPregelLike } from \"../pregel/utils/subgraph.js\";\nimport { Channel, Pregel } from \"../pregel/index.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { Runnable, _coerceToRunnable } from \"@langchain/core/runnables\";\nimport { Graph } from \"@langchain/core/runnables/graph\";\nimport { z } from \"zod/v4\";\nimport { validate } from \"uuid\";\n\n//#region src/graph/graph.ts\nvar Branch = class {\n\tpath;\n\tends;\n\tconstructor(options) {\n\t\tif (Runnable.isRunnable(options.path)) this.path = options.path;\n\t\telse this.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch` });\n\t\tthis.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n) => {\n\t\t\tacc[n] = n;\n\t\t\treturn acc;\n\t\t}, {}) : options.pathMap;\n\t}\n\trun(writer, reader) {\n\t\treturn ChannelWrite.registerWriter(new RunnableCallable({\n\t\t\tname: \"\",\n\t\t\ttrace: false,\n\t\t\tfunc: async (input, config) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this._route(input, config, writer, reader);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (e.name === NodeInterrupt.unminifiable_name) console.warn(\"[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\\nNodeInterrupt should only be thrown inside a node, not in edge conditions.\");\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t}\n\t\t}));\n\t}\n\tasync _route(input, config, writer, reader) {\n\t\tlet result = await this.path.invoke(reader ? reader(config) : input, config);\n\t\tif (!Array.isArray(result)) result = [result];\n\t\tlet destinations;\n\t\tif (this.ends) destinations = result.map((r) => _isSend(r) ? r : this.ends[r]);\n\t\telse destinations = result;\n\t\tif (destinations.some((dest) => !dest)) throw new Error(\"Branch condition returned unknown or null destination\");\n\t\tif (destinations.filter(_isSend).some((packet) => packet.node === END)) throw new InvalidUpdateError(\"Cannot send a packet to the END node\");\n\t\tconst writeResult = await writer(destinations, config);\n\t\treturn writeResult ?? input;\n\t}\n};\nvar Graph$1 = class {\n\tnodes;\n\tedges;\n\tbranches;\n\tentryPoint;\n\tcompiled = false;\n\tconstructor() {\n\t\tthis.nodes = {};\n\t\tthis.edges = /* @__PURE__ */ new Set();\n\t\tthis.branches = {};\n\t}\n\twarnIfCompiled(message) {\n\t\tif (this.compiled) console.warn(message);\n\t}\n\tget allEdges() {\n\t\treturn this.edges;\n\t}\n\taddNode(...args) {\n\t\tfunction isMutlipleNodes(args$1) {\n\t\t\treturn args$1.length >= 1 && typeof args$1[0] !== \"string\";\n\t\t}\n\t\tconst nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[\n\t\t\targs[0],\n\t\t\targs[1],\n\t\t\targs[2]\n\t\t]];\n\t\tif (nodes.length === 0) throw new Error(\"No nodes provided in `addNode`\");\n\t\tfor (const [key, action, options] of nodes) {\n\t\t\tfor (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`\"${reservedChar}\" is a reserved character and is not allowed in node names.`);\n\t\t\tthis.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`);\n\t\t\tif (key in this.nodes) throw new Error(`Node \\`${key}\\` already present.`);\n\t\t\tif (key === END) throw new Error(`Node \\`${key}\\` is reserved.`);\n\t\t\tconst runnable = _coerceToRunnable(action);\n\t\t\tthis.nodes[key] = {\n\t\t\t\trunnable,\n\t\t\t\tmetadata: options?.metadata,\n\t\t\t\tsubgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs,\n\t\t\t\tends: options?.ends\n\t\t\t};\n\t\t}\n\t\treturn this;\n\t}\n\taddEdge(startKey, endKey) {\n\t\tthis.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`);\n\t\tif (startKey === END) throw new Error(\"END cannot be a start node\");\n\t\tif (endKey === START) throw new Error(\"START cannot be an end node\");\n\t\tif (Array.from(this.edges).some(([start]) => start === startKey) && !(\"channels\" in this)) throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`);\n\t\tthis.edges.add([startKey, endKey]);\n\t\treturn this;\n\t}\n\taddConditionalEdges(source, path, pathMap) {\n\t\tconst options = typeof source === \"object\" ? source : {\n\t\t\tsource,\n\t\t\tpath,\n\t\t\tpathMap\n\t\t};\n\t\tthis.warnIfCompiled(\"Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.\");\n\t\tif (!Runnable.isRunnable(options.path)) {\n\t\t\tconst pathDisplayValues = Array.isArray(options.pathMap) ? options.pathMap.join(\",\") : Object.keys(options.pathMap ?? {}).join(\",\");\n\t\t\toptions.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch<${options.source}${pathDisplayValues !== \"\" ? `,${pathDisplayValues}` : \"\"}>`.slice(0, 63) });\n\t\t}\n\t\tconst name = options.path.getName() === \"RunnableLambda\" ? \"condition\" : options.path.getName();\n\t\tif (this.branches[options.source] && this.branches[options.source][name]) throw new Error(`Condition \\`${name}\\` already present for node \\`${source}\\``);\n\t\tthis.branches[options.source] ??= {};\n\t\tthis.branches[options.source][name] = new Branch(options);\n\t\treturn this;\n\t}\n\t/**\n\t* @deprecated use `addEdge(START, key)` instead\n\t*/\n\tsetEntryPoint(key) {\n\t\tthis.warnIfCompiled(\"Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph.\");\n\t\treturn this.addEdge(START, key);\n\t}\n\t/**\n\t* @deprecated use `addEdge(key, END)` instead\n\t*/\n\tsetFinishPoint(key) {\n\t\tthis.warnIfCompiled(\"Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph.\");\n\t\treturn this.addEdge(key, END);\n\t}\n\tcompile({ checkpointer, interruptBefore, interruptAfter, name } = {}) {\n\t\tthis.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]);\n\t\tconst compiled = new CompiledGraph({\n\t\t\tbuilder: this,\n\t\t\tcheckpointer,\n\t\t\tinterruptAfter,\n\t\t\tinterruptBefore,\n\t\t\tautoValidate: false,\n\t\t\tnodes: {},\n\t\t\tchannels: {\n\t\t\t\t[START]: new EphemeralValue(),\n\t\t\t\t[END]: new EphemeralValue()\n\t\t\t},\n\t\t\tinputChannels: START,\n\t\t\toutputChannels: END,\n\t\t\tstreamChannels: [],\n\t\t\tstreamMode: \"values\",\n\t\t\tname\n\t\t});\n\t\tfor (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node);\n\t\tfor (const [start, end] of this.edges) compiled.attachEdge(start, end);\n\t\tfor (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch);\n\t\treturn compiled.validate();\n\t}\n\tvalidate(interrupt) {\n\t\tconst allSources = new Set([...this.allEdges].map(([src, _]) => src));\n\t\tfor (const [start] of Object.entries(this.branches)) allSources.add(start);\n\t\tfor (const source of allSources) if (source !== START && !(source in this.nodes)) throw new Error(`Found edge starting at unknown node \\`${source}\\``);\n\t\tconst allTargets = new Set([...this.allEdges].map(([_, target]) => target));\n\t\tfor (const [start, branches] of Object.entries(this.branches)) for (const branch of Object.values(branches)) if (branch.ends != null) for (const end of Object.values(branch.ends)) allTargets.add(end);\n\t\telse {\n\t\t\tallTargets.add(END);\n\t\t\tfor (const node of Object.keys(this.nodes)) if (node !== start) allTargets.add(node);\n\t\t}\n\t\tfor (const node of Object.values(this.nodes)) for (const target of node.ends ?? []) allTargets.add(target);\n\t\tfor (const node of Object.keys(this.nodes)) if (!allTargets.has(node)) throw new UnreachableNodeError([\n\t\t\t`Node \\`${node}\\` is not reachable.`,\n\t\t\t\"\",\n\t\t\t\"If you are returning Command objects from your node,\",\n\t\t\t\"make sure you are passing names of potential destination nodes as an \\\"ends\\\" array\",\n\t\t\t\"into \\\".addNode(..., { ends: [\\\"node1\\\", \\\"node2\\\"] })\\\".\"\n\t\t].join(\"\\n\"), { lc_error_code: \"UNREACHABLE_NODE\" });\n\t\tfor (const target of allTargets) if (target !== END && !(target in this.nodes)) throw new Error(`Found edge ending at unknown node \\`${target}\\``);\n\t\tif (interrupt) {\n\t\t\tfor (const node of interrupt) if (!(node in this.nodes)) throw new Error(`Interrupt node \\`${node}\\` is not present`);\n\t\t}\n\t\tthis.compiled = true;\n\t}\n};\nvar CompiledGraph = class extends Pregel {\n\tbuilder;\n\tconstructor({ builder,...rest }) {\n\t\tsuper(rest);\n\t\tthis.builder = builder;\n\t}\n\tattachNode(key, node) {\n\t\tthis.channels[key] = new EphemeralValue();\n\t\tthis.nodes[key] = new PregelNode({\n\t\t\tchannels: [],\n\t\t\ttriggers: [],\n\t\t\tmetadata: node.metadata,\n\t\t\tsubgraphs: node.subgraphs,\n\t\t\tends: node.ends\n\t\t}).pipe(node.runnable).pipe(new ChannelWrite([{\n\t\t\tchannel: key,\n\t\t\tvalue: PASSTHROUGH\n\t\t}], [TAG_HIDDEN]));\n\t\tthis.streamChannels.push(key);\n\t}\n\tattachEdge(start, end) {\n\t\tif (end === END) {\n\t\t\tif (start === START) throw new Error(\"Cannot have an edge from START to END\");\n\t\t\tthis.nodes[start].writers.push(new ChannelWrite([{\n\t\t\t\tchannel: END,\n\t\t\t\tvalue: PASSTHROUGH\n\t\t\t}], [TAG_HIDDEN]));\n\t\t} else {\n\t\t\tthis.nodes[end].triggers.push(start);\n\t\t\tthis.nodes[end].channels.push(start);\n\t\t}\n\t}\n\tattachBranch(start, name, branch) {\n\t\tif (start === START && !this.nodes[START]) this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] });\n\t\tthis.nodes[start].pipe(branch.run((dests) => {\n\t\t\tconst writes = dests.map((dest) => {\n\t\t\t\tif (_isSend(dest)) return dest;\n\t\t\t\treturn {\n\t\t\t\t\tchannel: dest === END ? END : `branch:${start}:${name}:${dest}`,\n\t\t\t\t\tvalue: PASSTHROUGH\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn new ChannelWrite(writes, [TAG_HIDDEN]);\n\t\t}));\n\t\tconst ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes);\n\t\tfor (const end of ends) if (end !== END) {\n\t\t\tconst channelName = `branch:${start}:${name}:${end}`;\n\t\t\tthis.channels[channelName] = new EphemeralValue();\n\t\t\tthis.nodes[end].triggers.push(channelName);\n\t\t\tthis.nodes[end].channels.push(channelName);\n\t\t}\n\t}\n\t/**\n\t* Returns a drawable representation of the computation graph.\n\t*/\n\tasync getGraphAsync(config) {\n\t\tconst xray = config?.xray;\n\t\tconst graph = new Graph();\n\t\tconst startNodes = { [START]: graph.addNode({ schema: z.any() }, START) };\n\t\tconst endNodes = {};\n\t\tlet subgraphs = {};\n\t\tif (xray) subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1])));\n\t\tfunction addEdge(start, end, label, conditional = false) {\n\t\t\tif (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: z.any() }, END);\n\t\t\tif (startNodes[start] === void 0) return;\n\t\t\tif (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`);\n\t\t\treturn graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional);\n\t\t}\n\t\tfor (const [key, nodeSpec] of Object.entries(this.builder.nodes)) {\n\t\t\tconst displayKey = _escapeMermaidKeywords(key);\n\t\t\tconst node = nodeSpec.runnable;\n\t\t\tconst metadata = nodeSpec.metadata ?? {};\n\t\t\tif (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = \"before,after\";\n\t\t\telse if (this.interruptBefore?.includes(key)) metadata.__interrupt = \"before\";\n\t\t\telse if (this.interruptAfter?.includes(key)) metadata.__interrupt = \"after\";\n\t\t\tif (xray) {\n\t\t\t\tconst newXrayValue = typeof xray === \"number\" ? xray - 1 : xray;\n\t\t\t\tconst drawableSubgraph = subgraphs[key] !== void 0 ? await subgraphs[key].getGraphAsync({\n\t\t\t\t\t...config,\n\t\t\t\t\txray: newXrayValue\n\t\t\t\t}) : node.getGraph(config);\n\t\t\t\tdrawableSubgraph.trimFirstNode();\n\t\t\t\tdrawableSubgraph.trimLastNode();\n\t\t\t\tif (Object.keys(drawableSubgraph.nodes).length > 1) {\n\t\t\t\t\tconst [e, s] = graph.extend(drawableSubgraph, displayKey);\n\t\t\t\t\tif (e === void 0) throw new Error(`Could not extend subgraph \"${key}\" due to missing entrypoint.`);\n\t\t\t\t\tfunction _isRunnableInterface(thing) {\n\t\t\t\t\t\treturn thing ? thing.lc_runnable : false;\n\t\t\t\t\t}\n\t\t\t\t\tfunction _nodeDataStr(id, data) {\n\t\t\t\t\t\tif (id !== void 0 && !validate(id)) return id;\n\t\t\t\t\t\telse if (_isRunnableInterface(data)) try {\n\t\t\t\t\t\t\tlet dataStr = data.getName();\n\t\t\t\t\t\t\tdataStr = dataStr.startsWith(\"Runnable\") ? dataStr.slice(8) : dataStr;\n\t\t\t\t\t\t\treturn dataStr;\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treturn data.getName();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse return data.name ?? \"UnknownSchema\";\n\t\t\t\t\t}\n\t\t\t\t\tif (s !== void 0) startNodes[displayKey] = {\n\t\t\t\t\t\tname: _nodeDataStr(s.id, s.data),\n\t\t\t\t\t\t...s\n\t\t\t\t\t};\n\t\t\t\t\tendNodes[displayKey] = {\n\t\t\t\t\t\tname: _nodeDataStr(e.id, e.data),\n\t\t\t\t\t\t...e\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tconst newNode = graph.addNode(node, displayKey, metadata);\n\t\t\t\t\tstartNodes[displayKey] = newNode;\n\t\t\t\t\tendNodes[displayKey] = newNode;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst newNode = graph.addNode(node, displayKey, metadata);\n\t\t\t\tstartNodes[displayKey] = newNode;\n\t\t\t\tendNodes[displayKey] = newNode;\n\t\t\t}\n\t\t}\n\t\tconst sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => {\n\t\t\tif (a < b) return -1;\n\t\t\telse if (b > a) return 1;\n\t\t\telse return 0;\n\t\t});\n\t\tfor (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end));\n\t\tfor (const [start, branches] of Object.entries(this.builder.branches)) {\n\t\t\tconst defaultEnds = {\n\t\t\t\t...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])),\n\t\t\t\t[END]: END\n\t\t\t};\n\t\t\tfor (const branch of Object.values(branches)) {\n\t\t\t\tlet ends;\n\t\t\t\tif (branch.ends !== void 0) ends = branch.ends;\n\t\t\t\telse ends = defaultEnds;\n\t\t\t\tfor (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true);\n\t\t\t}\n\t\t}\n\t\tfor (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true);\n\t\treturn graph;\n\t}\n\t/**\n\t* Returns a drawable representation of the computation graph.\n\t*\n\t* @deprecated Use getGraphAsync instead. The async method will be the default in the next minor core release.\n\t*/\n\tgetGraph(config) {\n\t\tconst xray = config?.xray;\n\t\tconst graph = new Graph();\n\t\tconst startNodes = { [START]: graph.addNode({ schema: z.any() }, START) };\n\t\tconst endNodes = {};\n\t\tlet subgraphs = {};\n\t\tif (xray) subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1])));\n\t\tfunction addEdge(start, end, label, conditional = false) {\n\t\t\tif (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: z.any() }, END);\n\t\t\treturn graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional);\n\t\t}\n\t\tfor (const [key, nodeSpec] of Object.entries(this.builder.nodes)) {\n\t\t\tconst displayKey = _escapeMermaidKeywords(key);\n\t\t\tconst node = nodeSpec.runnable;\n\t\t\tconst metadata = nodeSpec.metadata ?? {};\n\t\t\tif (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = \"before,after\";\n\t\t\telse if (this.interruptBefore?.includes(key)) metadata.__interrupt = \"before\";\n\t\t\telse if (this.interruptAfter?.includes(key)) metadata.__interrupt = \"after\";\n\t\t\tif (xray) {\n\t\t\t\tconst newXrayValue = typeof xray === \"number\" ? xray - 1 : xray;\n\t\t\t\tconst drawableSubgraph = subgraphs[key] !== void 0 ? subgraphs[key].getGraph({\n\t\t\t\t\t...config,\n\t\t\t\t\txray: newXrayValue\n\t\t\t\t}) : node.getGraph(config);\n\t\t\t\tdrawableSubgraph.trimFirstNode();\n\t\t\t\tdrawableSubgraph.trimLastNode();\n\t\t\t\tif (Object.keys(drawableSubgraph.nodes).length > 1) {\n\t\t\t\t\tconst [e, s] = graph.extend(drawableSubgraph, displayKey);\n\t\t\t\t\tif (e === void 0) throw new Error(`Could not extend subgraph \"${key}\" due to missing entrypoint.`);\n\t\t\t\t\tfunction _isRunnableInterface(thing) {\n\t\t\t\t\t\treturn thing ? thing.lc_runnable : false;\n\t\t\t\t\t}\n\t\t\t\t\tfunction _nodeDataStr(id, data) {\n\t\t\t\t\t\tif (id !== void 0 && !validate(id)) return id;\n\t\t\t\t\t\telse if (_isRunnableInterface(data)) try {\n\t\t\t\t\t\t\tlet dataStr = data.getName();\n\t\t\t\t\t\t\tdataStr = dataStr.startsWith(\"Runnable\") ? dataStr.slice(8) : dataStr;\n\t\t\t\t\t\t\treturn dataStr;\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treturn data.getName();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse return data.name ?? \"UnknownSchema\";\n\t\t\t\t\t}\n\t\t\t\t\tif (s !== void 0) startNodes[displayKey] = {\n\t\t\t\t\t\tname: _nodeDataStr(s.id, s.data),\n\t\t\t\t\t\t...s\n\t\t\t\t\t};\n\t\t\t\t\tendNodes[displayKey] = {\n\t\t\t\t\t\tname: _nodeDataStr(e.id, e.data),\n\t\t\t\t\t\t...e\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tconst newNode = graph.addNode(node, displayKey, metadata);\n\t\t\t\t\tstartNodes[displayKey] = newNode;\n\t\t\t\t\tendNodes[displayKey] = newNode;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst newNode = graph.addNode(node, displayKey, metadata);\n\t\t\t\tstartNodes[displayKey] = newNode;\n\t\t\t\tendNodes[displayKey] = newNode;\n\t\t\t}\n\t\t}\n\t\tconst sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => {\n\t\t\tif (a < b) return -1;\n\t\t\telse if (b > a) return 1;\n\t\t\telse return 0;\n\t\t});\n\t\tfor (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end));\n\t\tfor (const [start, branches] of Object.entries(this.builder.branches)) {\n\t\t\tconst defaultEnds = {\n\t\t\t\t...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])),\n\t\t\t\t[END]: END\n\t\t\t};\n\t\t\tfor (const branch of Object.values(branches)) {\n\t\t\t\tlet ends;\n\t\t\t\tif (branch.ends !== void 0) ends = branch.ends;\n\t\t\t\telse ends = defaultEnds;\n\t\t\t\tfor (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true);\n\t\t\t}\n\t\t}\n\t\treturn graph;\n\t}\n};\nfunction isCompiledGraph(x) {\n\treturn typeof x.attachNode === \"function\" && typeof x.attachEdge === \"function\";\n}\nfunction _escapeMermaidKeywords(key) {\n\tif (key === \"subgraph\") return `\"${key}\"`;\n\treturn key;\n}\n\n//#endregion\nexport { Branch, CompiledGraph, Graph$1 as Graph };\n//# sourceMappingURL=graph.js.map","import { EmptyChannelError, InvalidUpdateError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\n\n//#region src/channels/named_barrier_value.ts\nconst areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value));\n/**\n* A channel that waits until all named values are received before making the value available.\n*\n* This ensures that if node N and node M both write to channel C, the value of C will not be updated\n* until N and M have completed updating.\n*/\nvar NamedBarrierValue = class NamedBarrierValue extends BaseChannel {\n\tlc_graph_name = \"NamedBarrierValue\";\n\tnames;\n\tseen;\n\tconstructor(names) {\n\t\tsuper();\n\t\tthis.names = names;\n\t\tthis.seen = /* @__PURE__ */ new Set();\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new NamedBarrierValue(this.names);\n\t\tif (typeof checkpoint !== \"undefined\") empty.seen = new Set(checkpoint);\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tlet updated = false;\n\t\tfor (const nodeName of values) if (this.names.has(nodeName)) {\n\t\t\tif (!this.seen.has(nodeName)) {\n\t\t\t\tthis.seen.add(nodeName);\n\t\t\t\tupdated = true;\n\t\t\t}\n\t\t} else throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`);\n\t\treturn updated;\n\t}\n\tget() {\n\t\tif (!areSetsEqual(this.names, this.seen)) throw new EmptyChannelError();\n\t\treturn void 0;\n\t}\n\tcheckpoint() {\n\t\treturn [...this.seen];\n\t}\n\tconsume() {\n\t\tif (this.seen && this.names && areSetsEqual(this.seen, this.names)) {\n\t\t\tthis.seen = /* @__PURE__ */ new Set();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tisAvailable() {\n\t\treturn !!this.names && areSetsEqual(this.names, this.seen);\n\t}\n};\n/**\n* A channel that waits until all named values are received before making the value ready to be made available.\n* It is only made available after finish() is called.\n* @internal\n*/\nvar NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish extends BaseChannel {\n\tlc_graph_name = \"NamedBarrierValueAfterFinish\";\n\tnames;\n\tseen;\n\tfinished;\n\tconstructor(names) {\n\t\tsuper();\n\t\tthis.names = names;\n\t\tthis.seen = /* @__PURE__ */ new Set();\n\t\tthis.finished = false;\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new NamedBarrierValueAfterFinish(this.names);\n\t\tif (typeof checkpoint !== \"undefined\") {\n\t\t\tconst [seen, finished] = checkpoint;\n\t\t\tempty.seen = new Set(seen);\n\t\t\tempty.finished = finished;\n\t\t}\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tlet updated = false;\n\t\tfor (const nodeName of values) if (this.names.has(nodeName) && !this.seen.has(nodeName)) {\n\t\t\tthis.seen.add(nodeName);\n\t\t\tupdated = true;\n\t\t} else if (!this.names.has(nodeName)) throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`);\n\t\treturn updated;\n\t}\n\tget() {\n\t\tif (!this.finished || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError();\n\t\treturn void 0;\n\t}\n\tcheckpoint() {\n\t\treturn [[...this.seen], this.finished];\n\t}\n\tconsume() {\n\t\tif (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) {\n\t\t\tthis.seen = /* @__PURE__ */ new Set();\n\t\t\tthis.finished = false;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tfinish() {\n\t\tif (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) {\n\t\t\tthis.finished = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tisAvailable() {\n\t\treturn this.finished && !!this.names && areSetsEqual(this.names, this.seen);\n\t}\n};\n\n//#endregion\nexport { NamedBarrierValue, NamedBarrierValueAfterFinish, areSetsEqual };\n//# sourceMappingURL=named_barrier_value.js.map","import { BinaryOperatorAggregate } from \"../../channels/binop.js\";\nimport { LastValue } from \"../../channels/last_value.js\";\nimport { extendInteropZodObject, getInteropZodDefaultGetter, getInteropZodObjectShape, getSchemaDescription, interopZodObjectPartial, isZodSchemaV3 } from \"@langchain/core/utils/types\";\n\n//#region src/graph/zod/meta.ts\nconst META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\n/**\n* A registry for storing and managing metadata associated with schemas.\n* This class provides methods to get, extend, remove, and check metadata for a given schema.\n*/\nvar SchemaMetaRegistry = class {\n\t/**\n\t* Internal map storing schema metadata.\n\t* @internal\n\t*/\n\t_map = /* @__PURE__ */ new WeakMap();\n\t/**\n\t* Cache for extended schfemas.\n\t* @internal\n\t*/\n\t_extensionCache = /* @__PURE__ */ new Map();\n\t/**\n\t* Retrieves the metadata associated with a given schema.\n\t* @template TValue The value type of the schema.\n\t* @template TUpdate The update type of the schema (defaults to TValue).\n\t* @param schema The schema to retrieve metadata for.\n\t* @returns The associated SchemaMeta, or undefined if not present.\n\t*/\n\tget(schema) {\n\t\treturn this._map.get(schema);\n\t}\n\t/**\n\t* Extends or sets the metadata for a given schema.\n\t* @template TValue The value type of the schema.\n\t* @template TUpdate The update type of the schema (defaults to TValue).\n\t* @param schema The schema to extend metadata for.\n\t* @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata.\n\t*/\n\textend(schema, predicate) {\n\t\tconst existingMeta = this.get(schema);\n\t\tthis._map.set(schema, predicate(existingMeta));\n\t}\n\t/**\n\t* Removes the metadata associated with a given schema.\n\t* @param schema The schema to remove metadata for.\n\t* @returns The SchemaMetaRegistry instance (for chaining).\n\t*/\n\tremove(schema) {\n\t\tthis._map.delete(schema);\n\t\treturn this;\n\t}\n\t/**\n\t* Checks if metadata exists for a given schema.\n\t* @param schema The schema to check.\n\t* @returns True if metadata exists, false otherwise.\n\t*/\n\thas(schema) {\n\t\treturn this._map.has(schema);\n\t}\n\t/**\n\t* Returns a mapping of channel instances for each property in the schema\n\t* using the associated metadata in the registry.\n\t*\n\t* This is used to create the `channels` object that's passed to the `Graph` constructor.\n\t*\n\t* @template T The shape of the schema.\n\t* @param schema The schema to extract channels from.\n\t* @returns A mapping from property names to channel instances.\n\t*/\n\tgetChannelsForSchema(schema) {\n\t\tconst channels = {};\n\t\tconst shape = getInteropZodObjectShape(schema);\n\t\tfor (const [key, channelSchema] of Object.entries(shape)) {\n\t\t\tconst meta = this.get(channelSchema);\n\t\t\tif (meta?.reducer) channels[key] = new BinaryOperatorAggregate(meta.reducer.fn, meta.default);\n\t\t\telse channels[key] = new LastValue();\n\t\t}\n\t\treturn channels;\n\t}\n\t/**\n\t* Returns a modified schema that introspectively looks at all keys of the provided\n\t* object schema, and applies the augmentations based on meta provided with those keys\n\t* in the registry and the selectors provided in the `effects` parameter.\n\t*\n\t* This assumes that the passed in schema is the \"root\" schema object for a graph where\n\t* the keys of the schema are the channels of the graph. Because we need to represent\n\t* the input of a graph in a couple of different ways, the `effects` parameter allows\n\t* us to apply those augmentations based on pre determined conditions.\n\t*\n\t* @param schema The root schema object to extend.\n\t* @param effects The effects that are being applied.\n\t* @returns The extended schema.\n\t*/\n\tgetExtendedChannelSchemas(schema, effects) {\n\t\tif (Object.keys(effects).length === 0) return schema;\n\t\tconst cacheKey = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join(\"|\");\n\t\tconst cache = this._extensionCache.get(cacheKey) ?? /* @__PURE__ */ new WeakMap();\n\t\tif (cache.has(schema)) return cache.get(schema);\n\t\tlet modifiedSchema = schema;\n\t\tif (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) {\n\t\t\tconst newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema$1]) => {\n\t\t\t\tconst meta = this.get(schema$1);\n\t\t\t\tlet outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema$1 : schema$1;\n\t\t\t\tif (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) {\n\t\t\t\t\tconst description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema$1);\n\t\t\t\t\tconst strExtras = JSON.stringify({\n\t\t\t\t\t\t...meta.jsonSchemaExtra,\n\t\t\t\t\t\tdescription\n\t\t\t\t\t});\n\t\t\t\t\toutputSchema = outputSchema.describe(`${META_EXTRAS_DESCRIPTION_PREFIX}${strExtras}`);\n\t\t\t\t}\n\t\t\t\treturn [key, outputSchema];\n\t\t\t});\n\t\t\tmodifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries));\n\t\t\tif (isZodSchemaV3(modifiedSchema)) modifiedSchema._def.unknownKeys = \"strip\";\n\t\t}\n\t\tif (effects.asPartial) modifiedSchema = interopZodObjectPartial(modifiedSchema);\n\t\tcache.set(schema, modifiedSchema);\n\t\tthis._extensionCache.set(cacheKey, cache);\n\t\treturn modifiedSchema;\n\t}\n};\nconst schemaMetaRegistry = new SchemaMetaRegistry();\nfunction withLangGraph(schema, meta) {\n\tif (meta.reducer && !meta.default) {\n\t\tconst defaultValueGetter = getInteropZodDefaultGetter(schema);\n\t\tif (defaultValueGetter != null) meta.default = defaultValueGetter;\n\t}\n\tif (meta.reducer) {\n\t\tconst schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta.reducer?.schema ?? schema });\n\t\tschemaMetaRegistry.extend(schemaWithReducer, () => meta);\n\t\treturn schemaWithReducer;\n\t} else {\n\t\tschemaMetaRegistry.extend(schema, () => meta);\n\t\treturn schema;\n\t}\n}\n\n//#endregion\nexport { META_EXTRAS_DESCRIPTION_PREFIX, SchemaMetaRegistry, schemaMetaRegistry, withLangGraph };\n//# sourceMappingURL=meta.js.map","import { InvalidUpdateError, ParentCommand } from \"../errors.js\";\nimport { isBaseChannel } from \"../channels/base.js\";\nimport { LastValueAfterFinish } from \"../channels/last_value.js\";\nimport { getChannel } from \"./annotation.js\";\nimport { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, Command, END, SELF, START, TAG_HIDDEN, _isSend, isCommand, isInterrupted } from \"../constants.js\";\nimport { RunnableCallable } from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\nimport { ChannelRead, PregelNode } from \"../pregel/read.js\";\nimport { isPregelLike } from \"../pregel/utils/subgraph.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { Branch, CompiledGraph, Graph } from \"./graph.js\";\nimport { NamedBarrierValue, NamedBarrierValueAfterFinish } from \"../channels/named_barrier_value.js\";\nimport { schemaMetaRegistry } from \"./zod/meta.js\";\nimport { Runnable, _coerceToRunnable } from \"@langchain/core/runnables\";\nimport { interopParse, interopZodObjectPartial, isInteropZodObject } from \"@langchain/core/utils/types\";\n\n//#region src/graph/state.ts\nconst ROOT = \"__root__\";\nconst PartialStateSchema = Symbol.for(\"langgraph.state.partial\");\n/**\n* A graph whose nodes communicate by reading and writing to a shared state.\n* Each node takes a defined `State` as input and returns a `Partial`.\n*\n* Each state key can optionally be annotated with a reducer function that\n* will be used to aggregate the values of that key received from multiple nodes.\n* The signature of a reducer function is (left: Value, right: UpdateValue) => Value.\n*\n* See {@link Annotation} for more on defining state.\n*\n* After adding nodes and edges to your graph, you must call `.compile()` on it before\n* you can use it.\n*\n* @example\n* ```ts\n* import {\n* type BaseMessage,\n* AIMessage,\n* HumanMessage,\n* } from \"@langchain/core/messages\";\n* import { StateGraph, Annotation } from \"@langchain/langgraph\";\n*\n* // Define a state with a single key named \"messages\" that will\n* // combine a returned BaseMessage or arrays of BaseMessages\n* const StateAnnotation = Annotation.Root({\n* sentiment: Annotation,\n* messages: Annotation({\n* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => {\n* if (Array.isArray(right)) {\n* return left.concat(right);\n* }\n* return left.concat([right]);\n* },\n* default: () => [],\n* }),\n* });\n*\n* const graphBuilder = new StateGraph(StateAnnotation);\n*\n* // A node in the graph that returns an object with a \"messages\" key\n* // will update the state by combining the existing value with the returned one.\n* const myNode = (state: typeof StateAnnotation.State) => {\n* return {\n* messages: [new AIMessage(\"Some new response\")],\n* sentiment: \"positive\",\n* };\n* };\n*\n* const graph = graphBuilder\n* .addNode(\"myNode\", myNode)\n* .addEdge(\"__start__\", \"myNode\")\n* .addEdge(\"myNode\", \"__end__\")\n* .compile();\n*\n* await graph.invoke({ messages: [new HumanMessage(\"how are you?\")] });\n*\n* // {\n* // messages: [HumanMessage(\"how are you?\"), AIMessage(\"Some new response\")],\n* // sentiment: \"positive\",\n* // }\n* ```\n*/\nvar StateGraph = class extends Graph {\n\tchannels = {};\n\twaitingEdges = /* @__PURE__ */ new Set();\n\t/** @internal */\n\t_schemaDefinition;\n\t/** @internal */\n\t_schemaRuntimeDefinition;\n\t/** @internal */\n\t_inputDefinition;\n\t/** @internal */\n\t_inputRuntimeDefinition;\n\t/** @internal */\n\t_outputDefinition;\n\t/** @internal */\n\t_outputRuntimeDefinition;\n\t/**\n\t* Map schemas to managed values\n\t* @internal\n\t*/\n\t_schemaDefinitions = /* @__PURE__ */ new Map();\n\t/** @internal */\n\t_metaRegistry = schemaMetaRegistry;\n\t/** @internal Used only for typing. */\n\t_configSchema;\n\t/** @internal */\n\t_configRuntimeSchema;\n\t/** @internal */\n\t_interrupt;\n\t/** @internal */\n\t_writer;\n\tconstructor(fields, contextSchema) {\n\t\tsuper();\n\t\tif (isZodStateGraphArgsWithStateSchema(fields)) {\n\t\t\tconst stateDef = this._metaRegistry.getChannelsForSchema(fields.state);\n\t\t\tconst inputDef = fields.input != null ? this._metaRegistry.getChannelsForSchema(fields.input) : stateDef;\n\t\t\tconst outputDef = fields.output != null ? this._metaRegistry.getChannelsForSchema(fields.output) : stateDef;\n\t\t\tthis._schemaDefinition = stateDef;\n\t\t\tthis._schemaRuntimeDefinition = fields.state;\n\t\t\tthis._inputDefinition = inputDef;\n\t\t\tthis._inputRuntimeDefinition = fields.input ?? PartialStateSchema;\n\t\t\tthis._outputDefinition = outputDef;\n\t\t\tthis._outputRuntimeDefinition = fields.output ?? fields.state;\n\t\t} else if (isInteropZodObject(fields)) {\n\t\t\tconst stateDef = this._metaRegistry.getChannelsForSchema(fields);\n\t\t\tthis._schemaDefinition = stateDef;\n\t\t\tthis._schemaRuntimeDefinition = fields;\n\t\t\tthis._inputDefinition = stateDef;\n\t\t\tthis._inputRuntimeDefinition = PartialStateSchema;\n\t\t\tthis._outputDefinition = stateDef;\n\t\t\tthis._outputRuntimeDefinition = fields;\n\t\t} else if (isStateGraphArgsWithInputOutputSchemas(fields)) {\n\t\t\tthis._schemaDefinition = fields.input.spec;\n\t\t\tthis._inputDefinition = fields.input.spec;\n\t\t\tthis._outputDefinition = fields.output.spec;\n\t\t} else if (isStateGraphArgsWithStateSchema(fields)) {\n\t\t\tthis._schemaDefinition = fields.stateSchema.spec;\n\t\t\tthis._inputDefinition = fields.input?.spec ?? this._schemaDefinition;\n\t\t\tthis._outputDefinition = fields.output?.spec ?? this._schemaDefinition;\n\t\t} else if (isStateDefinition(fields) || isAnnotationRoot(fields)) {\n\t\t\tconst spec = isAnnotationRoot(fields) ? fields.spec : fields;\n\t\t\tthis._schemaDefinition = spec;\n\t\t} else if (isStateGraphArgs(fields)) {\n\t\t\tconst spec = _getChannels(fields.channels);\n\t\t\tthis._schemaDefinition = spec;\n\t\t} else throw new Error(\"Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.\");\n\t\tthis._inputDefinition ??= this._schemaDefinition;\n\t\tthis._outputDefinition ??= this._schemaDefinition;\n\t\tthis._addSchema(this._schemaDefinition);\n\t\tthis._addSchema(this._inputDefinition);\n\t\tthis._addSchema(this._outputDefinition);\n\t\tfunction isOptions(options) {\n\t\t\treturn typeof options === \"object\" && options != null && !(\"spec\" in options) && !isInteropZodObject(options);\n\t\t}\n\t\tif (isOptions(contextSchema)) {\n\t\t\tif (isInteropZodObject(contextSchema.context)) this._configRuntimeSchema = contextSchema.context;\n\t\t\tthis._interrupt = contextSchema.interrupt;\n\t\t\tthis._writer = contextSchema.writer;\n\t\t} else if (isInteropZodObject(contextSchema)) this._configRuntimeSchema = contextSchema;\n\t}\n\tget allEdges() {\n\t\treturn new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]);\n\t}\n\t_addSchema(stateDefinition) {\n\t\tif (this._schemaDefinitions.has(stateDefinition)) return;\n\t\tthis._schemaDefinitions.set(stateDefinition, stateDefinition);\n\t\tfor (const [key, val] of Object.entries(stateDefinition)) {\n\t\t\tlet channel;\n\t\t\tif (typeof val === \"function\") channel = val();\n\t\t\telse channel = val;\n\t\t\tif (this.channels[key] !== void 0) {\n\t\t\t\tif (this.channels[key] !== channel) {\n\t\t\t\t\tif (channel.lc_graph_name !== \"LastValue\") throw new Error(`Channel \"${key}\" already exists with a different type.`);\n\t\t\t\t}\n\t\t\t} else this.channels[key] = channel;\n\t\t}\n\t}\n\taddNode(...args) {\n\t\tfunction isMultipleNodes(args$1) {\n\t\t\treturn args$1.length >= 1 && typeof args$1[0] !== \"string\";\n\t\t}\n\t\tconst nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[\n\t\t\targs[0],\n\t\t\targs[1],\n\t\t\targs[2]\n\t\t]];\n\t\tif (nodes.length === 0) throw new Error(\"No nodes provided in `addNode`\");\n\t\tfor (const [key, action, options] of nodes) {\n\t\t\tif (key in this.channels) throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);\n\t\t\tfor (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`\"${reservedChar}\" is a reserved character and is not allowed in node names.`);\n\t\t\tthis.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`);\n\t\t\tif (key in this.nodes) throw new Error(`Node \\`${key}\\` already present.`);\n\t\t\tif (key === END || key === START) throw new Error(`Node \\`${key}\\` is reserved.`);\n\t\t\tlet inputSpec = this._schemaDefinition;\n\t\t\tif (options?.input !== void 0) {\n\t\t\t\tif (isInteropZodObject(options.input)) inputSpec = this._metaRegistry.getChannelsForSchema(options.input);\n\t\t\t\telse if (options.input.spec !== void 0) inputSpec = options.input.spec;\n\t\t\t}\n\t\t\tif (inputSpec !== void 0) this._addSchema(inputSpec);\n\t\t\tlet runnable;\n\t\t\tif (Runnable.isRunnable(action)) runnable = action;\n\t\t\telse if (typeof action === \"function\") runnable = new RunnableCallable({\n\t\t\t\tfunc: action,\n\t\t\t\tname: key,\n\t\t\t\ttrace: false\n\t\t\t});\n\t\t\telse runnable = _coerceToRunnable(action);\n\t\t\tlet cachePolicy = options?.cachePolicy;\n\t\t\tif (typeof cachePolicy === \"boolean\") cachePolicy = cachePolicy ? {} : void 0;\n\t\t\tconst nodeSpec = {\n\t\t\t\trunnable,\n\t\t\t\tretryPolicy: options?.retryPolicy,\n\t\t\t\tcachePolicy,\n\t\t\t\tmetadata: options?.metadata,\n\t\t\t\tinput: inputSpec ?? this._schemaDefinition,\n\t\t\t\tsubgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs,\n\t\t\t\tends: options?.ends,\n\t\t\t\tdefer: options?.defer\n\t\t\t};\n\t\t\tthis.nodes[key] = nodeSpec;\n\t\t}\n\t\treturn this;\n\t}\n\taddEdge(startKey, endKey) {\n\t\tif (typeof startKey === \"string\") return super.addEdge(startKey, endKey);\n\t\tif (this.compiled) console.warn(\"Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.\");\n\t\tfor (const start of startKey) {\n\t\t\tif (start === END) throw new Error(\"END cannot be a start node\");\n\t\t\tif (!Object.keys(this.nodes).some((node) => node === start)) throw new Error(`Need to add a node named \"${start}\" first`);\n\t\t}\n\t\tif (endKey === END) throw new Error(\"END cannot be an end node\");\n\t\tif (!Object.keys(this.nodes).some((node) => node === endKey)) throw new Error(`Need to add a node named \"${endKey}\" first`);\n\t\tthis.waitingEdges.add([startKey, endKey]);\n\t\treturn this;\n\t}\n\taddSequence(nodes) {\n\t\tconst parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes);\n\t\tif (parsedNodes.length === 0) throw new Error(\"Sequence requires at least one node.\");\n\t\tlet previousNode;\n\t\tfor (const [key, action, options] of parsedNodes) {\n\t\t\tif (key in this.nodes) throw new Error(`Node names must be unique: node with the name \"${key}\" already exists.`);\n\t\t\tconst validKey = key;\n\t\t\tthis.addNode(validKey, action, options);\n\t\t\tif (previousNode != null) this.addEdge(previousNode, validKey);\n\t\t\tpreviousNode = validKey;\n\t\t}\n\t\treturn this;\n\t}\n\tcompile({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description } = {}) {\n\t\tthis.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]);\n\t\tconst outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition));\n\t\tconst outputChannels = outputKeys.length === 1 && outputKeys[0] === ROOT ? ROOT : outputKeys;\n\t\tconst streamKeys = Object.keys(this.channels);\n\t\tconst streamChannels = streamKeys.length === 1 && streamKeys[0] === ROOT ? ROOT : streamKeys;\n\t\tconst userInterrupt = this._interrupt;\n\t\tconst compiled = new CompiledStateGraph({\n\t\t\tbuilder: this,\n\t\t\tcheckpointer,\n\t\t\tinterruptAfter,\n\t\t\tinterruptBefore,\n\t\t\tautoValidate: false,\n\t\t\tnodes: {},\n\t\t\tchannels: {\n\t\t\t\t...this.channels,\n\t\t\t\t[START]: new EphemeralValue()\n\t\t\t},\n\t\t\tinputChannels: START,\n\t\t\toutputChannels,\n\t\t\tstreamChannels,\n\t\t\tstreamMode: \"updates\",\n\t\t\tstore,\n\t\t\tcache,\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tuserInterrupt\n\t\t});\n\t\tcompiled.attachNode(START);\n\t\tfor (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node);\n\t\tcompiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false });\n\t\tfor (const [key] of Object.entries(this.nodes)) compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false });\n\t\tfor (const [start, end] of this.edges) compiled.attachEdge(start, end);\n\t\tfor (const [starts, end] of this.waitingEdges) compiled.attachEdge(starts, end);\n\t\tfor (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch);\n\t\treturn compiled.validate();\n\t}\n};\nfunction _getChannels(schema) {\n\tconst channels = {};\n\tfor (const [name, val] of Object.entries(schema)) if (name === ROOT) channels[name] = getChannel(val);\n\telse channels[name] = getChannel(val);\n\treturn channels;\n}\n/**\n* Final result from building and compiling a {@link StateGraph}.\n* Should not be instantiated directly, only using the StateGraph `.compile()`\n* instance method.\n*/\nvar CompiledStateGraph = class extends CompiledGraph {\n\t/**\n\t* The description of the compiled graph.\n\t* This is used by the supervisor agent to describe the handoff to the agent.\n\t*/\n\tdescription;\n\t/** @internal */\n\t_metaRegistry = schemaMetaRegistry;\n\tconstructor({ description,...rest }) {\n\t\tsuper(rest);\n\t\tthis.description = description;\n\t}\n\tattachNode(key, node) {\n\t\tlet outputKeys;\n\t\tif (key === START) outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k);\n\t\telse outputKeys = Object.keys(this.builder.channels);\n\t\tfunction _getRoot(input) {\n\t\t\tif (isCommand(input)) {\n\t\t\t\tif (input.graph === Command.PARENT) return null;\n\t\t\t\treturn input._updateAsTuples();\n\t\t\t} else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) {\n\t\t\t\tconst updates = [];\n\t\t\t\tfor (const i of input) if (isCommand(i)) {\n\t\t\t\t\tif (i.graph === Command.PARENT) continue;\n\t\t\t\t\tupdates.push(...i._updateAsTuples());\n\t\t\t\t} else updates.push([ROOT, i]);\n\t\t\t\treturn updates;\n\t\t\t} else if (input != null) return [[ROOT, input]];\n\t\t\treturn null;\n\t\t}\n\t\tconst nodeKey = key;\n\t\tfunction _getUpdates(input) {\n\t\t\tif (!input) return null;\n\t\t\telse if (isCommand(input)) {\n\t\t\t\tif (input.graph === Command.PARENT) return null;\n\t\t\t\treturn input._updateAsTuples().filter(([k]) => outputKeys.includes(k));\n\t\t\t} else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) {\n\t\t\t\tconst updates = [];\n\t\t\t\tfor (const item of input) if (isCommand(item)) {\n\t\t\t\t\tif (item.graph === Command.PARENT) continue;\n\t\t\t\t\tupdates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k)));\n\t\t\t\t} else {\n\t\t\t\t\tconst itemUpdates = _getUpdates(item);\n\t\t\t\t\tif (itemUpdates) updates.push(...itemUpdates ?? []);\n\t\t\t\t}\n\t\t\t\treturn updates;\n\t\t\t} else if (typeof input === \"object\" && !Array.isArray(input)) return Object.entries(input).filter(([k]) => outputKeys.includes(k));\n\t\t\telse {\n\t\t\t\tconst typeofInput = Array.isArray(input) ? \"array\" : typeof input;\n\t\t\t\tthrow new InvalidUpdateError(`Expected node \"${nodeKey.toString()}\" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: \"INVALID_GRAPH_NODE_RETURN_VALUE\" });\n\t\t\t}\n\t\t}\n\t\tconst stateWriteEntries = [{\n\t\t\tvalue: PASSTHROUGH,\n\t\t\tmapper: new RunnableCallable({\n\t\t\t\tfunc: outputKeys.length && outputKeys[0] === ROOT ? _getRoot : _getUpdates,\n\t\t\t\ttrace: false,\n\t\t\t\trecurse: false\n\t\t\t})\n\t\t}];\n\t\tif (key === START) this.nodes[key] = new PregelNode({\n\t\t\ttags: [TAG_HIDDEN],\n\t\t\ttriggers: [START],\n\t\t\tchannels: [START],\n\t\t\twriters: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])]\n\t\t});\n\t\telse {\n\t\t\tconst inputDefinition = node?.input ?? this.builder._schemaDefinition;\n\t\t\tconst inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k]));\n\t\t\tconst isSingleInput = Object.keys(inputValues).length === 1 && ROOT in inputValues;\n\t\t\tconst branchChannel = `branch:to:${key}`;\n\t\t\tthis.channels[branchChannel] = node?.defer ? new LastValueAfterFinish() : new EphemeralValue(false);\n\t\t\tthis.nodes[key] = new PregelNode({\n\t\t\t\ttriggers: [branchChannel],\n\t\t\t\tchannels: isSingleInput ? Object.keys(inputValues) : inputValues,\n\t\t\t\twriters: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])],\n\t\t\t\tmapper: isSingleInput ? void 0 : (input) => {\n\t\t\t\t\treturn Object.fromEntries(Object.entries(input).filter(([k]) => k in inputValues));\n\t\t\t\t},\n\t\t\t\tbound: node?.runnable,\n\t\t\t\tmetadata: node?.metadata,\n\t\t\t\tretryPolicy: node?.retryPolicy,\n\t\t\t\tcachePolicy: node?.cachePolicy,\n\t\t\t\tsubgraphs: node?.subgraphs,\n\t\t\t\tends: node?.ends\n\t\t\t});\n\t\t}\n\t}\n\tattachEdge(starts, end) {\n\t\tif (end === END) return;\n\t\tif (typeof starts === \"string\") this.nodes[starts].writers.push(new ChannelWrite([{\n\t\t\tchannel: `branch:to:${end}`,\n\t\t\tvalue: null\n\t\t}], [TAG_HIDDEN]));\n\t\telse if (Array.isArray(starts)) {\n\t\t\tconst channelName = `join:${starts.join(\"+\")}:${end}`;\n\t\t\tthis.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts));\n\t\t\tthis.nodes[end].triggers.push(channelName);\n\t\t\tfor (const start of starts) this.nodes[start].writers.push(new ChannelWrite([{\n\t\t\t\tchannel: channelName,\n\t\t\t\tvalue: start\n\t\t\t}], [TAG_HIDDEN]));\n\t\t}\n\t}\n\tattachBranch(start, _, branch, options = { withReader: true }) {\n\t\tconst branchWriter = async (packets, config) => {\n\t\t\tconst filteredPackets = packets.filter((p) => p !== END);\n\t\t\tif (!filteredPackets.length) return;\n\t\t\tconst writes = filteredPackets.map((p) => {\n\t\t\t\tif (_isSend(p)) return p;\n\t\t\t\treturn {\n\t\t\t\t\tchannel: p === END ? p : `branch:to:${p}`,\n\t\t\t\t\tvalue: start\n\t\t\t\t};\n\t\t\t});\n\t\t\tawait ChannelWrite.doWrite({\n\t\t\t\t...config,\n\t\t\t\ttags: (config.tags ?? []).concat([TAG_HIDDEN])\n\t\t\t}, writes);\n\t\t};\n\t\tthis.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config) => ChannelRead.doRead(config, this.streamChannels ?? this.outputChannels, true) : void 0));\n\t}\n\tasync _validateInput(input) {\n\t\tif (input == null) return input;\n\t\tconst schema = (() => {\n\t\t\tconst input$1 = this.builder._inputRuntimeDefinition;\n\t\t\tconst schema$1 = this.builder._schemaRuntimeDefinition;\n\t\t\tconst apply = (schema$2) => {\n\t\t\t\tif (schema$2 == null) return void 0;\n\t\t\t\treturn this._metaRegistry.getExtendedChannelSchemas(schema$2, { withReducerSchema: true });\n\t\t\t};\n\t\t\tif (isInteropZodObject(input$1)) return apply(input$1);\n\t\t\tif (input$1 === PartialStateSchema) return interopZodObjectPartial(apply(schema$1));\n\t\t\treturn void 0;\n\t\t})();\n\t\tif (isCommand(input)) {\n\t\t\tconst parsedInput = input;\n\t\t\tif (input.update && schema != null) parsedInput.update = interopParse(schema, input.update);\n\t\t\treturn parsedInput;\n\t\t}\n\t\tif (schema != null) return interopParse(schema, input);\n\t\treturn input;\n\t}\n\tisInterrupted(input) {\n\t\treturn isInterrupted(input);\n\t}\n\tasync _validateContext(config) {\n\t\tconst configSchema = this.builder._configRuntimeSchema;\n\t\tif (isInteropZodObject(configSchema)) interopParse(configSchema, config);\n\t\treturn config;\n\t}\n};\nfunction isStateDefinition(obj) {\n\treturn typeof obj === \"object\" && obj !== null && !Array.isArray(obj) && Object.keys(obj).length > 0 && Object.values(obj).every((v) => typeof v === \"function\" || isBaseChannel(v));\n}\nfunction isAnnotationRoot(obj) {\n\treturn typeof obj === \"object\" && obj !== null && \"lc_graph_name\" in obj && obj.lc_graph_name === \"AnnotationRoot\";\n}\nfunction isStateGraphArgs(obj) {\n\treturn typeof obj === \"object\" && obj !== null && obj.channels !== void 0;\n}\nfunction isStateGraphArgsWithStateSchema(obj) {\n\treturn typeof obj === \"object\" && obj !== null && obj.stateSchema !== void 0;\n}\nfunction isStateGraphArgsWithInputOutputSchemas(obj) {\n\treturn typeof obj === \"object\" && obj !== null && obj.stateSchema === void 0 && obj.input !== void 0 && obj.output !== void 0;\n}\nfunction isZodStateGraphArgsWithStateSchema(value) {\n\tif (typeof value !== \"object\" || value == null) return false;\n\tif (!(\"state\" in value) || !isInteropZodObject(value.state)) return false;\n\tif (\"input\" in value && !isInteropZodObject(value.input)) return false;\n\tif (\"output\" in value && !isInteropZodObject(value.output)) return false;\n\treturn true;\n}\nfunction _controlBranch(value) {\n\tif (_isSend(value)) return [value];\n\tconst commands = [];\n\tif (isCommand(value)) commands.push(value);\n\telse if (Array.isArray(value)) commands.push(...value.filter(isCommand));\n\tconst destinations = [];\n\tfor (const command of commands) {\n\t\tif (command.graph === Command.PARENT) throw new ParentCommand(command);\n\t\tif (_isSend(command.goto)) destinations.push(command.goto);\n\t\telse if (typeof command.goto === \"string\") destinations.push(command.goto);\n\t\telse if (Array.isArray(command.goto)) destinations.push(...command.goto);\n\t}\n\treturn destinations;\n}\nfunction _getControlBranch() {\n\tconst CONTROL_BRANCH_PATH = new RunnableCallable({\n\t\tfunc: _controlBranch,\n\t\ttags: [TAG_HIDDEN],\n\t\ttrace: false,\n\t\trecurse: false,\n\t\tname: \"\"\n\t});\n\treturn new Branch({ path: CONTROL_BRANCH_PATH });\n}\n\n//#endregion\nexport { CompiledStateGraph, StateGraph };\n//# sourceMappingURL=state.js.map","import { ensureLangGraphConfig } from \"../pregel/utils/config.js\";\nimport { StateGraph } from \"./state.js\";\nimport { v4 } from \"uuid\";\nimport { coerceMessageLikeToMessage } from \"@langchain/core/messages\";\n\n//#region src/graph/message.ts\nconst REMOVE_ALL_MESSAGES = \"__remove_all__\";\n/**\n* Prebuilt reducer that combines returned messages.\n* Can handle standard messages and special modifiers like {@link RemoveMessage}\n* instances.\n*/\nfunction messagesStateReducer(left, right) {\n\tconst leftArray = Array.isArray(left) ? left : [left];\n\tconst rightArray = Array.isArray(right) ? right : [right];\n\tconst leftMessages = leftArray.map(coerceMessageLikeToMessage);\n\tconst rightMessages = rightArray.map(coerceMessageLikeToMessage);\n\tfor (const m of leftMessages) if (m.id === null || m.id === void 0) {\n\t\tm.id = v4();\n\t\tm.lc_kwargs.id = m.id;\n\t}\n\tlet removeAllIdx;\n\tfor (let i = 0; i < rightMessages.length; i += 1) {\n\t\tconst m = rightMessages[i];\n\t\tif (m.id === null || m.id === void 0) {\n\t\t\tm.id = v4();\n\t\t\tm.lc_kwargs.id = m.id;\n\t\t}\n\t\tif (m.getType() === \"remove\" && m.id === REMOVE_ALL_MESSAGES) removeAllIdx = i;\n\t}\n\tif (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1);\n\tconst merged = [...leftMessages];\n\tconst mergedById = new Map(merged.map((m, i) => [m.id, i]));\n\tconst idsToRemove = /* @__PURE__ */ new Set();\n\tfor (const m of rightMessages) {\n\t\tconst existingIdx = mergedById.get(m.id);\n\t\tif (existingIdx !== void 0) if (m.getType() === \"remove\") idsToRemove.add(m.id);\n\t\telse {\n\t\t\tidsToRemove.delete(m.id);\n\t\t\tmerged[existingIdx] = m;\n\t\t}\n\t\telse {\n\t\t\tif (m.getType() === \"remove\") throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`);\n\t\t\tmergedById.set(m.id, merged.length);\n\t\t\tmerged.push(m);\n\t\t}\n\t}\n\treturn merged.filter((m) => !idsToRemove.has(m.id));\n}\n/** @ignore */\nvar MessageGraph = class extends StateGraph {\n\tconstructor() {\n\t\tsuper({ channels: { __root__: {\n\t\t\treducer: messagesStateReducer,\n\t\t\tdefault: () => []\n\t\t} } });\n\t}\n};\n/**\n* Manually push a message to a message stream.\n*\n* This is useful when you need to push a manually created message before the node\n* has finished executing.\n*\n* When a message is pushed, it will be automatically persisted to the state after the node has finished executing.\n* To disable persisting, set `options.stateKey` to `null`.\n*\n* @param message The message to push. The message must have an ID set, otherwise an error will be thrown.\n* @param options RunnableConfig / Runtime coming from node context.\n*/\nfunction pushMessage(message, options) {\n\tconst { stateKey: userStateKey,...userConfig } = options ?? {};\n\tconst config = ensureLangGraphConfig(userConfig);\n\tlet stateKey = userStateKey ?? \"messages\";\n\tif (userStateKey === null) stateKey = void 0;\n\tconst validMessage = coerceMessageLikeToMessage(message);\n\tif (!validMessage.id) throw new Error(\"Message ID is required.\");\n\tconst callbacks = (() => {\n\t\tif (Array.isArray(config.callbacks)) return config.callbacks;\n\t\tif (typeof config.callbacks !== \"undefined\") return config.callbacks.handlers;\n\t\treturn [];\n\t})();\n\tconst messagesHandler = callbacks.find((cb) => \"name\" in cb && cb.name === \"StreamMessagesHandler\");\n\tif (messagesHandler) {\n\t\tconst metadata = config.metadata ?? {};\n\t\tconst namespace = (metadata.langgraph_checkpoint_ns ?? \"\").split(\"|\");\n\t\tmessagesHandler._emit([namespace, metadata], validMessage, void 0, false);\n\t}\n\tif (stateKey) config.configurable?.__pregel_send?.([[stateKey, validMessage]]);\n\treturn validMessage;\n}\n\n//#endregion\nexport { MessageGraph, REMOVE_ALL_MESSAGES, messagesStateReducer, pushMessage };\n//# sourceMappingURL=message.js.map","import { LastValue } from \"../channels/last_value.js\";\nimport { CONFIG_KEY_PREVIOUS_STATE, END, PREVIOUS, START, TAG_HIDDEN } from \"../constants.js\";\nimport { RunnableCallable, isAsyncGeneratorFunction, isGeneratorFunction } from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport { call, getRunnableForEntrypoint } from \"../pregel/call.js\";\nimport { Pregel } from \"../pregel/index.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\n\n//#region src/func/index.ts\n/**\n* Define a LangGraph task using the `task` function.\n*\n* Tasks can only be called from within an {@link entrypoint} or from within a StateGraph.\n* A task can be called like a regular function with the following differences:\n*\n* - When a checkpointer is enabled, the function inputs and outputs must be serializable.\n* - The wrapped function can only be called from within an entrypoint or StateGraph.\n* - Calling the function produces a promise. This makes it easy to parallelize tasks.\n*\n* @typeParam ArgsT - The type of arguments the task function accepts\n* @typeParam OutputT - The type of value the task function returns\n* @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task\n* @param func - The function that executes this task\n* @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise\n*\n* @example basic example\n* ```typescript\n* const addOne = task(\"add\", async (a: number) => a + 1);\n*\n* const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n* const promises = numbers.map(n => addOne(n));\n* const results = await Promise.all(promises);\n* return results;\n* });\n*\n* // Call the entrypoint\n* await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n* ```\n*\n* @example using a retry policy\n* ```typescript\n* const addOne = task({\n* name: \"add\",\n* retry: { maxAttempts: 3 }\n* },\n* async (a: number) => a + 1\n* );\n*\n* const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n* const promises = numbers.map(n => addOne(n));\n* const results = await Promise.all(promises);\n* return results;\n* });\n* ```\n* @category Functional API\n*/\nfunction task(optionsOrName, func) {\n\tconst options = typeof optionsOrName === \"string\" ? {\n\t\tname: optionsOrName,\n\t\tretry: void 0,\n\t\tcachePolicy: void 0\n\t} : optionsOrName;\n\tconst { name, retry } = options;\n\tif (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error(\"Generators are disallowed as tasks. For streaming responses, use config.write.\");\n\tconst cachePolicy = options.cachePolicy ?? (\"cache\" in options ? options.cache : void 0);\n\tlet cache;\n\tif (typeof cachePolicy === \"boolean\") cache = cachePolicy ? {} : void 0;\n\telse cache = cachePolicy;\n\treturn (...args) => {\n\t\treturn call({\n\t\t\tfunc,\n\t\t\tname,\n\t\t\tretry,\n\t\t\tcache\n\t\t}, ...args);\n\t};\n}\n/**\n* Define a LangGraph workflow using the `entrypoint` function.\n*\n* ### Function signature\n*\n* The wrapped function must accept at most **two parameters**. The first parameter\n* is the input to the function. The second (optional) parameter is a\n* {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to\n* the function, you can pass them as an object.\n*\n* ### Helper functions\n*\n* #### Streaming\n* To write data to the \"custom\" stream, use the {@link getWriter} function, or the\n* {@link LangGraphRunnableConfig.writer} property.\n*\n* #### State management\n* The {@link getPreviousState} function can be used to access the previous state\n* that was returned from the last invocation of the entrypoint on the same thread id.\n*\n* If you wish to save state other than the return value, you can use the\n* {@link entrypoint.final} function.\n*\n* @typeParam InputT - The type of input the entrypoint accepts\n* @typeParam OutputT - The type of output the entrypoint produces\n* @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint\n* @param func - The function that executes this entrypoint\n* @returns A {@link Pregel} instance that can be run to execute the workflow\n*\n* @example Using entrypoint and tasks\n* ```typescript\n* import { task, entrypoint } from \"@langchain/langgraph\";\n* import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n* import { interrupt, Command } from \"@langchain/langgraph\";\n*\n* const composeEssay = task(\"compose\", async (topic: string) => {\n* await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation\n* return `An essay about ${topic}`;\n* });\n*\n* const reviewWorkflow = entrypoint({\n* name: \"review\",\n* checkpointer: new MemorySaver()\n* }, async (topic: string) => {\n* const essay = await composeEssay(topic);\n* const humanReview = await interrupt({\n* question: \"Please provide a review\",\n* essay\n* });\n* return {\n* essay,\n* review: humanReview\n* };\n* });\n*\n* // Example configuration for the workflow\n* const config = {\n* configurable: {\n* thread_id: \"some_thread\"\n* }\n* };\n*\n* // Topic for the essay\n* const topic = \"cats\";\n*\n* // Stream the workflow to generate the essay and await human review\n* for await (const result of reviewWorkflow.stream(topic, config)) {\n* console.log(result);\n* }\n*\n* // Example human review provided after the interrupt\n* const humanReview = \"This essay is great.\";\n*\n* // Resume the workflow with the provided human review\n* for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) {\n* console.log(result);\n* }\n* ```\n*\n* @example Accessing the previous return value\n* ```typescript\n* import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n* import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n*\n* const accumulator = entrypoint({\n* name: \"accumulator\",\n* checkpointer: new MemorySaver()\n* }, async (input: string) => {\n* const previous = getPreviousState();\n* return previous !== undefined ? `${previous } ${input}` : input;\n* });\n*\n* const config = {\n* configurable: {\n* thread_id: \"some_thread\"\n* }\n* };\n* await accumulator.invoke(\"hello\", config); // returns \"hello\"\n* await accumulator.invoke(\"world\", config); // returns \"hello world\"\n* ```\n*\n* @example Using entrypoint.final to save a value\n* ```typescript\n* import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n* import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n*\n* const myWorkflow = entrypoint({\n* name: \"accumulator\",\n* checkpointer: new MemorySaver()\n* }, async (num: number) => {\n* const previous = getPreviousState();\n*\n* // This will return the previous value to the caller, saving\n* // 2 * num to the checkpoint, which will be used in the next invocation\n* // for the `previous` parameter.\n* return entrypoint.final({\n* value: previous ?? 0,\n* save: 2 * num\n* });\n* });\n*\n* const config = {\n* configurable: {\n* thread_id: \"some_thread\"\n* }\n* };\n*\n* await myWorkflow.invoke(3, config); // 0 (previous was undefined)\n* await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation)\n* ```\n* @category Functional API\n*/\nconst entrypoint = function entrypoint$1(optionsOrName, func) {\n\tconst { name, checkpointer, store, cache } = typeof optionsOrName === \"string\" ? {\n\t\tname: optionsOrName,\n\t\tcheckpointer: void 0,\n\t\tstore: void 0\n\t} : optionsOrName;\n\tif (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error(\"Generators are disallowed as entrypoints. For streaming responses, use config.write.\");\n\tconst streamMode = \"updates\";\n\tconst bound = getRunnableForEntrypoint(name, func);\n\tfunction isEntrypointFinal(value) {\n\t\treturn typeof value === \"object\" && value !== null && \"__lg_type\" in value && value.__lg_type === \"__pregel_final\";\n\t}\n\tconst pluckReturnValue = new RunnableCallable({\n\t\tname: \"pluckReturnValue\",\n\t\tfunc: (value) => {\n\t\t\treturn isEntrypointFinal(value) ? value.value : value;\n\t\t}\n\t});\n\tconst pluckSaveValue = new RunnableCallable({\n\t\tname: \"pluckSaveValue\",\n\t\tfunc: (value) => {\n\t\t\treturn isEntrypointFinal(value) ? value.save : value;\n\t\t}\n\t});\n\tconst entrypointNode = new PregelNode({\n\t\tbound,\n\t\ttriggers: [START],\n\t\tchannels: [START],\n\t\twriters: [new ChannelWrite([{\n\t\t\tchannel: END,\n\t\t\tvalue: PASSTHROUGH,\n\t\t\tmapper: pluckReturnValue\n\t\t}, {\n\t\t\tchannel: PREVIOUS,\n\t\t\tvalue: PASSTHROUGH,\n\t\t\tmapper: pluckSaveValue\n\t\t}], [TAG_HIDDEN])]\n\t});\n\treturn new Pregel({\n\t\tname,\n\t\tcheckpointer,\n\t\tnodes: { [name]: entrypointNode },\n\t\tchannels: {\n\t\t\t[START]: new EphemeralValue(),\n\t\t\t[END]: new LastValue(),\n\t\t\t[PREVIOUS]: new LastValue()\n\t\t},\n\t\tinputChannels: START,\n\t\toutputChannels: END,\n\t\tstreamChannels: END,\n\t\tstreamMode,\n\t\tstore,\n\t\tcache\n\t});\n};\nentrypoint.final = function final({ value, save }) {\n\treturn {\n\t\tvalue,\n\t\tsave,\n\t\t__lg_type: \"__pregel_final\"\n\t};\n};\n/**\n* A helper utility function for use with the functional API that returns the previous\n* state from the checkpoint from the last invocation of the current thread.\n*\n* This function allows workflows to access state that was saved in previous runs\n* using {@link entrypoint.final}.\n*\n* @typeParam StateT - The type of the state that was previously saved\n* @returns The previous saved state from the last invocation of the current thread\n*\n* @example\n* ```typescript\n* const previousState = getPreviousState<{ counter: number }>();\n* const newCount = (previousState?.counter ?? 0) + 1;\n* ```\n* @category Functional API\n*/\nfunction getPreviousState() {\n\tconst config = AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\treturn config.configurable?.[CONFIG_KEY_PREVIOUS_STATE];\n}\n\n//#endregion\nexport { entrypoint, getPreviousState, task };\n//# sourceMappingURL=index.js.map","import { Annotation } from \"./annotation.js\";\nimport { withLangGraph } from \"./zod/meta.js\";\nimport { messagesStateReducer } from \"./message.js\";\nimport { z } from \"zod/v3\";\n\n//#region src/graph/messages_annotation.ts\n/**\n* Prebuilt state annotation that combines returned messages.\n* Can handle standard messages and special modifiers like {@link RemoveMessage}\n* instances.\n*\n* Specifically, importing and using the prebuilt MessagesAnnotation like this:\n*\n* @example\n* ```ts\n* import { MessagesAnnotation, StateGraph } from \"@langchain/langgraph\";\n*\n* const graph = new StateGraph(MessagesAnnotation)\n* .addNode(...)\n* ...\n* ```\n*\n* Is equivalent to initializing your state manually like this:\n*\n* @example\n* ```ts\n* import { BaseMessage } from \"@langchain/core/messages\";\n* import { Annotation, StateGraph, messagesStateReducer } from \"@langchain/langgraph\";\n*\n* export const StateAnnotation = Annotation.Root({\n* messages: Annotation({\n* reducer: messagesStateReducer,\n* default: () => [],\n* }),\n* });\n*\n* const graph = new StateGraph(StateAnnotation)\n* .addNode(...)\n* ...\n* ```\n*/\nconst MessagesAnnotation = Annotation.Root({ messages: Annotation({\n\treducer: messagesStateReducer,\n\tdefault: () => []\n}) });\n/**\n* Prebuilt schema meta for Zod state definition.\n*\n* @example\n* ```ts\n* import { z } from \"zod/v4-mini\";\n* import { MessagesZodState, StateGraph } from \"@langchain/langgraph\";\n*\n* const AgentState = z.object({\n* messages: z.custom().register(registry, MessagesZodMeta),\n* });\n* ```\n*/\nconst MessagesZodMeta = {\n\treducer: { fn: messagesStateReducer },\n\tjsonSchemaExtra: { langgraph_type: \"messages\" },\n\tdefault: () => []\n};\n/**\n* Prebuilt state object that uses Zod to combine returned messages.\n* This utility is synonymous with the `MessagesAnnotation` annotation,\n* but uses Zod as the way to express messages state.\n*\n* You can use import and use this prebuilt schema like this:\n*\n* @example\n* ```ts\n* import { MessagesZodState, StateGraph } from \"@langchain/langgraph\";\n*\n* const graph = new StateGraph(MessagesZodState)\n* .addNode(...)\n* ...\n* ```\n*\n* Which is equivalent to initializing the schema object manually like this:\n*\n* @example\n* ```ts\n* import { z } from \"zod\";\n* import type { BaseMessage, BaseMessageLike } from \"@langchain/core/messages\";\n* import { StateGraph, messagesStateReducer } from \"@langchain/langgraph\";\n* import \"@langchain/langgraph/zod\";\n*\n* const AgentState = z.object({\n* messages: z\n* .custom()\n* .default(() => [])\n* .langgraph.reducer(\n* messagesStateReducer,\n* z.custom()\n* ),\n* });\n* const graph = new StateGraph(AgentState)\n* .addNode(...)\n* ...\n* ```\n*/\nconst MessagesZodState = z.object({ messages: withLangGraph(z.custom(), MessagesZodMeta) });\n\n//#endregion\nexport { MessagesAnnotation, MessagesZodMeta, MessagesZodState };\n//# sourceMappingURL=messages_annotation.js.map","import { Annotation, AnnotationRoot } from \"./annotation.js\";\nimport { CommandInstance } from \"../constants.js\";\nimport { Graph } from \"./graph.js\";\nimport { CompiledStateGraph, StateGraph } from \"./state.js\";\nimport { MessageGraph, REMOVE_ALL_MESSAGES, messagesStateReducer, pushMessage } from \"./message.js\";\n\nexport { };","import { EmptyChannelError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\n\n//#region src/channels/any_value.ts\n/**\n* Stores the last value received, assumes that if multiple values are received, they are all equal.\n*\n* Note: Unlike 'LastValue' if multiple nodes write to this channel in a single step, the values\n* will be continuously overwritten.\n*/\nvar AnyValue = class AnyValue extends BaseChannel {\n\tlc_graph_name = \"AnyValue\";\n\tvalue = [];\n\tconstructor() {\n\t\tsuper();\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new AnyValue();\n\t\tif (typeof checkpoint !== \"undefined\") empty.value = [checkpoint];\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tif (values.length === 0) {\n\t\t\tconst updated = this.value.length > 0;\n\t\t\tthis.value = [];\n\t\t\treturn updated;\n\t\t}\n\t\tthis.value = [values[values.length - 1]];\n\t\treturn false;\n\t}\n\tget() {\n\t\tif (this.value.length === 0) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tcheckpoint() {\n\t\tif (this.value.length === 0) throw new EmptyChannelError();\n\t\treturn this.value[0];\n\t}\n\tisAvailable() {\n\t\treturn this.value.length !== 0;\n\t}\n};\n\n//#endregion\nexport { AnyValue };\n//# sourceMappingURL=any_value.js.map","import { EmptyChannelError, InvalidUpdateError } from \"../errors.js\";\nimport { BaseChannel } from \"./base.js\";\nimport { areSetsEqual } from \"./named_barrier_value.js\";\n\n//#region src/channels/dynamic_barrier_value.ts\nfunction isWaitForNames(v) {\n\treturn v.__names !== void 0;\n}\n/**\n* A channel that switches between two states\n*\n* - in the \"priming\" state it can't be read from.\n* - if it receives a WaitForNames update, it switches to the \"waiting\" state.\n* - in the \"waiting\" state it collects named values until all are received.\n* - once all named values are received, it can be read once, and it switches\n* back to the \"priming\" state.\n*/\nvar DynamicBarrierValue = class DynamicBarrierValue extends BaseChannel {\n\tlc_graph_name = \"DynamicBarrierValue\";\n\tnames;\n\tseen;\n\tconstructor() {\n\t\tsuper();\n\t\tthis.names = void 0;\n\t\tthis.seen = /* @__PURE__ */ new Set();\n\t}\n\tfromCheckpoint(checkpoint) {\n\t\tconst empty = new DynamicBarrierValue();\n\t\tif (typeof checkpoint !== \"undefined\") {\n\t\t\tempty.names = new Set(checkpoint[0]);\n\t\t\tempty.seen = new Set(checkpoint[1]);\n\t\t}\n\t\treturn empty;\n\t}\n\tupdate(values) {\n\t\tconst waitForNames = values.filter(isWaitForNames);\n\t\tif (waitForNames.length > 0) {\n\t\t\tif (waitForNames.length > 1) throw new InvalidUpdateError(\"Received multiple WaitForNames updates in the same step.\");\n\t\t\tthis.names = new Set(waitForNames[0].__names);\n\t\t\treturn true;\n\t\t} else if (this.names !== void 0) {\n\t\t\tlet updated = false;\n\t\t\tfor (const value of values) {\n\t\t\t\tif (isWaitForNames(value)) throw new Error(\"Assertion Error: Received unexpected WaitForNames instance.\");\n\t\t\t\tif (this.names.has(value) && !this.seen.has(value)) {\n\t\t\t\t\tthis.seen.add(value);\n\t\t\t\t\tupdated = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn updated;\n\t\t}\n\t\treturn false;\n\t}\n\tconsume() {\n\t\tif (this.seen && this.names && areSetsEqual(this.seen, this.names)) {\n\t\t\tthis.seen = /* @__PURE__ */ new Set();\n\t\t\tthis.names = void 0;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tget() {\n\t\tif (!this.names || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError();\n\t\treturn void 0;\n\t}\n\tcheckpoint() {\n\t\treturn [this.names ? [...this.names] : void 0, [...this.seen]];\n\t}\n\tisAvailable() {\n\t\treturn !!this.names && areSetsEqual(this.names, this.seen);\n\t}\n};\n\n//#endregion\nexport { DynamicBarrierValue };\n//# sourceMappingURL=dynamic_barrier_value.js.map","import { BaseChannel, createCheckpoint, emptyChannels } from \"./base.js\";\nimport { BinaryOperatorAggregate } from \"./binop.js\";\nimport { LastValue, LastValueAfterFinish } from \"./last_value.js\";\nimport { Topic } from \"./topic.js\";\nimport { EphemeralValue } from \"./ephemeral_value.js\";\nimport { NamedBarrierValue, NamedBarrierValueAfterFinish } from \"./named_barrier_value.js\";\nimport { AnyValue } from \"./any_value.js\";\nimport { DynamicBarrierValue } from \"./dynamic_barrier_value.js\";\n\nexport { AnyValue, BaseChannel, BinaryOperatorAggregate, DynamicBarrierValue, EphemeralValue, LastValue, LastValueAfterFinish, NamedBarrierValue, NamedBarrierValueAfterFinish, Topic, createCheckpoint, emptyChannels as empty };","import { BaseLangGraphError, EmptyChannelError, EmptyInputError, GraphBubbleUp, GraphInterrupt, GraphRecursionError, GraphValueError, InvalidUpdateError, MultipleSubgraphsError, NodeInterrupt, ParentCommand, RemoteException, UnreachableNodeError, getSubgraphsSeenSet, isGraphBubbleUp, isGraphInterrupt, isParentCommand } from \"./errors.js\";\nimport { BaseChannel } from \"./channels/base.js\";\nimport { BinaryOperatorAggregate } from \"./channels/binop.js\";\nimport { Annotation } from \"./graph/annotation.js\";\nimport { Command, END, INTERRUPT, START, Send, isCommand, isInterrupted } from \"./constants.js\";\nimport { Graph } from \"./graph/graph.js\";\nimport { CompiledStateGraph, StateGraph } from \"./graph/state.js\";\nimport { MessageGraph, REMOVE_ALL_MESSAGES, messagesStateReducer } from \"./graph/message.js\";\nimport \"./graph/index.js\";\nimport \"./channels/index.js\";\nimport { entrypoint, task } from \"./func/index.js\";\nimport { MessagesAnnotation, MessagesZodMeta, MessagesZodState } from \"./graph/messages_annotation.js\";\nimport { AsyncBatchedStore, BaseCheckpointSaver, BaseStore, InMemoryStore, MemorySaver, copyCheckpoint, emptyCheckpoint } from \"@langchain/langgraph-checkpoint\";\n\nexport { Annotation, AsyncBatchedStore, BaseChannel, BaseCheckpointSaver, BaseLangGraphError, BaseStore, BinaryOperatorAggregate, Command, CompiledStateGraph, END, EmptyChannelError, EmptyInputError, Graph, GraphBubbleUp, GraphInterrupt, GraphRecursionError, GraphValueError, INTERRUPT, InMemoryStore, InvalidUpdateError, MemorySaver, MessageGraph, MessagesAnnotation, MessagesZodMeta, MessagesZodState, MultipleSubgraphsError, NodeInterrupt, ParentCommand, REMOVE_ALL_MESSAGES, RemoteException, START, Send, StateGraph, UnreachableNodeError, messagesStateReducer as addMessages, copyCheckpoint, emptyCheckpoint, entrypoint, getSubgraphsSeenSet, isCommand, isGraphBubbleUp, isGraphInterrupt, isInterrupted, isParentCommand, messagesStateReducer, task };","import { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\n\n//#region src/writer.ts\nfunction writer(chunk) {\n\tconst config = AsyncLocalStorageProviderSingleton.getRunnableConfig();\n\tif (!config) throw new Error(\"Called interrupt() outside the context of a graph.\");\n\tconst conf = config.configurable;\n\tif (!conf) throw new Error(\"No configurable found in config\");\n\treturn conf.writer?.(chunk);\n}\n\n//#endregion\nexport { writer };\n//# sourceMappingURL=writer.js.map","import { initializeAsyncLocalStorageSingleton } from \"./setup/async_local_storage.js\";\nimport { BaseLangGraphError, EmptyChannelError, EmptyInputError, GraphBubbleUp, GraphInterrupt, GraphRecursionError, GraphValueError, InvalidUpdateError, MultipleSubgraphsError, NodeInterrupt, ParentCommand, RemoteException, UnreachableNodeError, getSubgraphsSeenSet, isGraphBubbleUp, isGraphInterrupt, isParentCommand } from \"./errors.js\";\nimport { BaseChannel } from \"./channels/base.js\";\nimport { BinaryOperatorAggregate } from \"./channels/binop.js\";\nimport { Annotation } from \"./graph/annotation.js\";\nimport { Command, END, INTERRUPT, START, Send, isCommand, isInterrupted } from \"./constants.js\";\nimport { getConfig, getCurrentTaskInput, getStore, getWriter } from \"./pregel/utils/config.js\";\nimport { interrupt } from \"./interrupt.js\";\nimport { Graph } from \"./graph/graph.js\";\nimport { CompiledStateGraph, StateGraph } from \"./graph/state.js\";\nimport { MessageGraph, REMOVE_ALL_MESSAGES, messagesStateReducer, pushMessage } from \"./graph/message.js\";\nimport { entrypoint, getPreviousState, task } from \"./func/index.js\";\nimport { MessagesAnnotation, MessagesZodMeta, MessagesZodState } from \"./graph/messages_annotation.js\";\nimport { AsyncBatchedStore, BaseCheckpointSaver, BaseStore, InMemoryStore, MemorySaver, copyCheckpoint, emptyCheckpoint } from \"./web.js\";\nimport { writer } from \"./writer.js\";\n\n//#region src/index.ts\ninitializeAsyncLocalStorageSingleton();\n\n//#endregion\nexport { Annotation, AsyncBatchedStore, BaseChannel, BaseCheckpointSaver, BaseLangGraphError, BaseStore, BinaryOperatorAggregate, Command, CompiledStateGraph, END, EmptyChannelError, EmptyInputError, Graph, GraphBubbleUp, GraphInterrupt, GraphRecursionError, GraphValueError, INTERRUPT, InMemoryStore, InvalidUpdateError, MemorySaver, MessageGraph, MessagesAnnotation, MessagesZodMeta, MessagesZodState, MultipleSubgraphsError, NodeInterrupt, ParentCommand, REMOVE_ALL_MESSAGES, RemoteException, START, Send, StateGraph, UnreachableNodeError, messagesStateReducer as addMessages, copyCheckpoint, emptyCheckpoint, entrypoint, getConfig, getCurrentTaskInput, getPreviousState, getStore, getSubgraphsSeenSet, getWriter, interrupt, isCommand, isGraphBubbleUp, isGraphInterrupt, isInterrupted, isParentCommand, messagesStateReducer, pushMessage, task, writer };\n//# sourceMappingURL=index.js.map","/**\n * PR Analysis Tools for LangChain Agent\n * These tools are used by the agent to analyze different aspects of PR changes\n */\n\nimport { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { DiffFile } from '../types/agent.types.js';\n\n/**\n * Parse git diff into structured file changes\n */\nexport function parseDiff(diff: string): DiffFile[] {\n const files: DiffFile[] = [];\n const lines = diff.split('\\n');\n let currentFile: Partial | null = null;\n let currentDiff: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // New file detected\n if (line.startsWith('diff --git')) {\n // Save previous file\n if (currentFile) {\n files.push({\n ...currentFile,\n diff: currentDiff.join('\\n'),\n } as DiffFile);\n }\n\n // Parse file path\n const match = line.match(/^diff --git a\\/(.+?) b\\/(.+?)$/);\n if (match) {\n const filePath = match[2] !== '/dev/null' ? match[2] : match[1];\n currentFile = {\n path: filePath,\n additions: 0,\n deletions: 0,\n language: detectLanguage(filePath),\n };\n currentDiff = [line];\n }\n } else if (line.startsWith('new file') && currentFile) {\n currentFile.status = 'A';\n currentDiff.push(line);\n } else if (line.startsWith('deleted file') && currentFile) {\n currentFile.status = 'D';\n currentDiff.push(line);\n } else if (line.startsWith('rename from') && currentFile) {\n currentFile.status = 'R';\n const oldPath = line.replace('rename from ', '').trim();\n currentFile.oldPath = oldPath;\n currentDiff.push(line);\n } else if (line.startsWith('+') && !line.startsWith('+++') && currentFile) {\n currentFile.additions = (currentFile.additions || 0) + 1;\n currentDiff.push(line);\n } else if (line.startsWith('-') && !line.startsWith('---') && currentFile) {\n currentFile.deletions = (currentFile.deletions || 0) + 1;\n currentDiff.push(line);\n } else if (currentFile) {\n currentDiff.push(line);\n }\n }\n\n // Save last file\n if (currentFile) {\n files.push({\n ...currentFile,\n diff: currentDiff.join('\\n'),\n } as DiffFile);\n }\n\n return files;\n}\n\n/**\n * Detect programming language from file extension\n */\nfunction detectLanguage(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase();\n const languageMap: Record = {\n ts: 'typescript',\n tsx: 'typescript',\n js: 'javascript',\n jsx: 'javascript',\n py: 'python',\n java: 'java',\n go: 'go',\n rs: 'rust',\n rb: 'ruby',\n php: 'php',\n cs: 'csharp',\n cpp: 'cpp',\n c: 'c',\n swift: 'swift',\n kt: 'kotlin',\n yaml: 'yaml',\n yml: 'yaml',\n json: 'json',\n md: 'markdown',\n };\n return languageMap[ext || ''] || 'unknown';\n}\n\n/**\n * Create file analyzer tool\n */\nexport function createFileAnalyzerTool() {\n return new DynamicStructuredTool({\n name: 'analyze_file',\n description: 'Analyze a specific file from the diff to identify risks, complexity, and provide recommendations',\n schema: z.object({\n filePath: z.string().describe('Path of the file to analyze'),\n diffContent: z.string().describe('The diff content for this file'),\n }),\n func: async ({ filePath, diffContent }) => {\n // Parse the diff to extract changes\n const additions = (diffContent.match(/^\\+[^+]/gm) || []).length;\n const deletions = (diffContent.match(/^-[^-]/gm) || []).length;\n const totalChanges = additions + deletions;\n\n // Basic complexity scoring\n let complexity = 1;\n if (totalChanges > 100) complexity = 4;\n else if (totalChanges > 50) complexity = 3;\n else if (totalChanges > 20) complexity = 2;\n\n // Detect potential risks\n const risks: string[] = [];\n \n // Check for security-related patterns\n if (/eval\\(|exec\\(|system\\(/i.test(diffContent)) {\n risks.push('Potentially dangerous function calls detected (eval, exec, system)');\n }\n if (/password|secret|api[_-]?key|token/i.test(diffContent) && /['\"]/i.test(diffContent)) {\n risks.push('Possible hardcoded credentials or secrets');\n }\n if (/TODO|FIXME|XXX|HACK/i.test(diffContent)) {\n risks.push('Contains TODO/FIXME comments indicating incomplete work');\n }\n if (totalChanges > 200) {\n risks.push('Very large change set - difficult to review thoroughly');\n }\n\n // Check for error handling\n const hasTryCatch = /try\\s*{|catch\\s*\\(/i.test(diffContent);\n const hasThrow = /throw\\s+/i.test(diffContent);\n if (hasThrow && !hasTryCatch) {\n risks.push('Throws errors without apparent error handling');\n }\n\n return JSON.stringify({\n path: filePath,\n additions,\n deletions,\n complexity,\n risks,\n language: detectLanguage(filePath),\n });\n },\n });\n}\n\n/**\n * Create risk detector tool\n */\nexport function createRiskDetectorTool() {\n return new DynamicStructuredTool({\n name: 'detect_risks',\n description: 'Detect security, quality, and breaking change risks in the PR',\n schema: z.object({\n diff: z.string().describe('The full diff to analyze for risks'),\n context: z.string().optional().describe('Additional context about the changes'),\n }),\n func: async ({ diff, context }) => {\n const risks: Array<{ type: string; severity: string; description: string }> = [];\n\n // Security risks\n if (/sql.*=.*\\+|SQL.*=.*\\+/i.test(diff)) {\n risks.push({\n type: 'security',\n severity: 'high',\n description: 'Potential SQL injection - string concatenation in SQL queries',\n });\n }\n\n if (/innerHTML|dangerouslySetInnerHTML/i.test(diff)) {\n risks.push({\n type: 'security',\n severity: 'medium',\n description: 'XSS risk - using innerHTML or dangerouslySetInnerHTML',\n });\n }\n\n // Breaking changes\n if (/export\\s+(interface|type|class|function)\\s+\\w+/i.test(diff) && /-.*export/i.test(diff)) {\n risks.push({\n type: 'breaking',\n severity: 'high',\n description: 'Potential breaking change - modified or removed export',\n });\n }\n\n // Code quality\n if ((diff.match(/console\\.log/g) || []).length > 3) {\n risks.push({\n type: 'quality',\n severity: 'low',\n description: 'Multiple console.log statements - consider using proper logging',\n });\n }\n\n // Performance\n if (/for.*for|while.*while/i.test(diff) && /O\\(n\\^2\\)/i.test(diff)) {\n risks.push({\n type: 'performance',\n severity: 'medium',\n description: 'Nested loops detected - potential O(n²) complexity',\n });\n }\n\n return JSON.stringify({\n riskCount: risks.length,\n risks,\n context: context || 'No additional context provided',\n });\n },\n });\n}\n\n/**\n * Create complexity scorer tool\n */\nexport function createComplexityScorerTool() {\n return new DynamicStructuredTool({\n name: 'score_complexity',\n description: 'Calculate overall complexity score for the PR (1-5 scale)',\n schema: z.object({\n filesAnalyzed: z.array(z.any()).describe('Array of analyzed files'),\n totalChanges: z.number().describe('Total lines changed'),\n }),\n func: async ({ filesAnalyzed, totalChanges }) => {\n let score = 1;\n \n // Factor 1: Total changes\n if (totalChanges > 500) score = Math.max(score, 5);\n else if (totalChanges > 300) score = Math.max(score, 4);\n else if (totalChanges > 150) score = Math.max(score, 3);\n else if (totalChanges > 50) score = Math.max(score, 2);\n\n // Factor 2: Number of files\n const fileCount = filesAnalyzed.length;\n if (fileCount > 20) score = Math.max(score, 5);\n else if (fileCount > 10) score = Math.max(score, 4);\n else if (fileCount > 5) score = Math.max(score, 3);\n\n // Factor 3: File complexity average\n const avgFileComplexity = filesAnalyzed.reduce((sum: number, f: any) => sum + (f.complexity || 1), 0) / Math.max(fileCount, 1);\n if (avgFileComplexity >= 4) score = Math.max(score, 5);\n else if (avgFileComplexity >= 3) score = Math.max(score, 4);\n\n return JSON.stringify({\n overallComplexity: Math.min(score, 5),\n factors: {\n totalChanges,\n fileCount,\n avgFileComplexity: avgFileComplexity.toFixed(1),\n },\n recommendation: score >= 4\n ? 'High complexity - consider breaking into smaller PRs'\n : score >= 3\n ? 'Moderate complexity - ensure thorough testing'\n : 'Low complexity - straightforward changes',\n });\n },\n });\n}\n\n/**\n * Create summary generator tool\n */\nexport function createSummaryGeneratorTool() {\n return new DynamicStructuredTool({\n name: 'generate_summary',\n description: 'Generate a concise summary of PR changes',\n schema: z.object({\n files: z.array(z.any()).describe('Array of changed files'),\n title: z.string().optional().describe('PR title'),\n }),\n func: async ({ files, title }) => {\n const filesByType: Record = {};\n let totalAdditions = 0;\n let totalDeletions = 0;\n\n files.forEach((file: any) => {\n const lang = file.language || 'other';\n filesByType[lang] = (filesByType[lang] || 0) + 1;\n totalAdditions += file.additions || 0;\n totalDeletions += file.deletions || 0;\n });\n\n const mainLanguage = Object.entries(filesByType).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';\n\n return JSON.stringify({\n title: title || 'Untitled PR',\n fileCount: files.length,\n totalAdditions,\n totalDeletions,\n netChange: totalAdditions - totalDeletions,\n mainLanguage,\n filesByType,\n summary: `Changes ${files.length} file(s) with ${totalAdditions} additions and ${totalDeletions} deletions. Primary language: ${mainLanguage}.`,\n });\n },\n });\n}\n\n/**\n * Create code suggestion tool for fixing issues based on reviewer comments\n */\nexport function createCodeSuggestionTool() {\n return new DynamicStructuredTool({\n name: 'suggest_code_fix',\n description: 'Generate a code fix suggestion based on a reviewer comment and the associated code snippet',\n schema: z.object({\n reviewerComment: z.string().describe('The reviewer\\'s comment describing the issue'),\n codeSnippet: z.string().describe('The original code snippet to be fixed'),\n filePath: z.string().describe('Path of the file containing the code'),\n prTitle: z.string().optional().describe('PR title for context'),\n prContext: z.string().optional().describe('Additional PR context (repo, branch, etc.)'),\n }),\n func: async ({ reviewerComment, codeSnippet, filePath, prTitle, prContext }) => {\n // Build the fix prompt\n const prompt = `You are an expert software engineer and code-fixer. You will take a reviewer comment and the associated code snippet and produce the corrected code snippet only.\n\nContext:\n${prContext || '(no additional context)'}\n- PR Title: ${prTitle || '(unknown)'}\n- File: ${filePath}\n\nReviewer comment:\n${reviewerComment.trim()}\n\nOriginal code snippet:\n\\`\\`\\`\n${codeSnippet}\n\\`\\`\\`\n\nTask:\n1) Apply the reviewer's requested changes to the provided code snippet.\n2) Output rules (MUST follow exactly):\n - Return only the corrected code snippet (no explanations, no markdown fences, no extra text).\n - If only a few lines changed you may return only the updated lines, but prefer returning the full corrected snippet when structural/context changes are required.\n - Preserve original code style and indentation.\n - If no changes are needed, reply with exactly: NO CHANGE\n - Do not include filenames, metadata, or commentary.\n\nProduce the corrected code now.`;\n\n return JSON.stringify({\n filePath,\n originalCode: codeSnippet,\n reviewerComment,\n prompt,\n status: 'ready',\n message: 'Code suggestion prompt prepared. The agent will use this to generate the fix.',\n });\n },\n });\n}\n\n","/**\n * Arch-Docs Parser\n * Parses .arch-docs markdown files for RAG system\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport interface ArchDoc {\n filename: string;\n title: string;\n content: string;\n sections: ArchDocSection[];\n metadata?: Record;\n}\n\nexport interface ArchDocSection {\n heading: string;\n level: number;\n content: string;\n lineStart: number;\n lineEnd: number;\n}\n\n/**\n * Check if .arch-docs folder exists\n */\nexport function archDocsExists(repoPath: string = process.cwd()): boolean {\n const archDocsPath = path.join(repoPath, '.arch-docs');\n return fs.existsSync(archDocsPath) && fs.statSync(archDocsPath).isDirectory();\n}\n\n/**\n * Get all markdown files from .arch-docs folder\n */\nexport function getArchDocsFiles(repoPath: string = process.cwd()): string[] {\n const archDocsPath = path.join(repoPath, '.arch-docs');\n \n if (!archDocsExists(repoPath)) {\n return [];\n }\n\n try {\n const files = fs.readdirSync(archDocsPath);\n return files\n .filter(file => file.endsWith('.md'))\n .map(file => path.join(archDocsPath, file));\n } catch (error) {\n console.warn('Error reading .arch-docs folder:', error);\n return [];\n }\n}\n\n/**\n * Parse a markdown file into structured sections\n */\nexport function parseMarkdownFile(filePath: string): ArchDoc {\n const content = fs.readFileSync(filePath, 'utf-8');\n const filename = path.basename(filePath, '.md');\n const lines = content.split('\\n');\n \n const sections: ArchDocSection[] = [];\n let currentSection: ArchDocSection | undefined;\n let title = filename.charAt(0).toUpperCase() + filename.slice(1).replace(/-/g, ' ');\n\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index];\n const headingMatch = line.match(/^(#{1,6})\\s+(.+)$/);\n \n if (headingMatch) {\n // Save previous section\n if (currentSection) {\n currentSection.lineEnd = index - 1;\n sections.push(currentSection);\n }\n\n // Extract title from first heading\n if (sections.length === 0 && headingMatch[1].length === 1) {\n title = headingMatch[2];\n }\n\n // Start new section\n currentSection = {\n heading: headingMatch[2],\n level: headingMatch[1].length,\n content: '',\n lineStart: index,\n lineEnd: index,\n };\n } else if (currentSection) {\n // Add content to current section\n currentSection.content += line + '\\n';\n }\n }\n\n // Save last section\n if (currentSection) {\n currentSection.lineEnd = lines.length - 1;\n sections.push(currentSection);\n }\n\n return {\n filename,\n title,\n content,\n sections,\n };\n}\n\n/**\n * Parse all arch-docs files\n */\nexport function parseAllArchDocs(repoPath: string = process.cwd()): ArchDoc[] {\n const files = getArchDocsFiles(repoPath);\n return files.map(file => parseMarkdownFile(file));\n}\n\n/**\n * Search arch-docs by keyword (simple text search)\n */\nexport function searchArchDocs(\n docs: ArchDoc[],\n query: string,\n maxResults: number = 5\n): Array<{ doc: ArchDoc; section: ArchDocSection; relevance: number }> {\n const results: Array<{ doc: ArchDoc; section: ArchDocSection; relevance: number }> = [];\n const queryLower = query.toLowerCase();\n const queryWords = queryLower.split(/\\s+/).filter(w => w.length > 2);\n\n for (const doc of docs) {\n for (const section of doc.sections) {\n const sectionText = (section.heading + ' ' + section.content).toLowerCase();\n \n // Calculate relevance score\n let relevance = 0;\n \n // Exact phrase match\n if (sectionText.includes(queryLower)) {\n relevance += 10;\n }\n\n // Word matches\n for (const word of queryWords) {\n const matches = (sectionText.match(new RegExp(word, 'g')) || []).length;\n relevance += matches * 2;\n }\n\n // Heading match bonus\n if (section.heading.toLowerCase().includes(queryLower)) {\n relevance += 5;\n }\n\n if (relevance > 0) {\n results.push({ doc, section, relevance });\n }\n }\n }\n\n // Sort by relevance and return top results\n return results\n .sort((a, b) => b.relevance - a.relevance)\n .slice(0, maxResults);\n}\n\n/**\n * Get specific arch-docs by filename\n */\nexport function getArchDocByFilename(\n docs: ArchDoc[],\n filename: string\n): ArchDoc | undefined {\n return docs.find(doc => doc.filename === filename);\n}\n\n/**\n * Get arch-docs summary (index.md content if available)\n */\nexport function getArchDocsSummary(docs: ArchDoc[]): string {\n const indexDoc = getArchDocByFilename(docs, 'index');\n if (indexDoc) {\n return indexDoc.content;\n }\n\n // Fallback: create summary from available docs\n const fileList = docs.map(doc => `- ${doc.title} (${doc.filename}.md)`).join('\\n');\n return `Available Architecture Documentation:\\n\\n${fileList}`;\n}\n\n","/**\n * Arch-Docs RAG System\n * Retrieval Augmented Generation for architecture documentation\n */\n\nimport { ArchDoc, ArchDocSection, searchArchDocs } from './arch-docs-parser.js';\n\nexport interface ArchDocsContext {\n available: boolean;\n summary: string;\n relevantDocs: Array<{\n filename: string;\n title: string;\n section: string;\n content: string;\n relevance: number;\n }>;\n totalDocs: number;\n}\n\n/**\n * Build context from arch-docs based on PR analysis needs\n */\nexport function buildArchDocsContext(\n docs: ArchDoc[],\n prContext: {\n title?: string;\n files: Array<{ path: string; diff?: string }>;\n diff?: string;\n }\n): ArchDocsContext {\n if (docs.length === 0) {\n return {\n available: false,\n summary: '',\n relevantDocs: [],\n totalDocs: 0,\n };\n }\n\n // Extract keywords from PR context\n const keywords = extractKeywords(prContext);\n \n // Search for relevant sections\n const relevantResults: Map = new Map();\n \n // Search for each keyword and aggregate results\n for (const keyword of keywords) {\n const results = searchArchDocs(docs, keyword, 3);\n for (const result of results) {\n const key = `${result.doc.filename}:${result.section.heading}`;\n const existing = relevantResults.get(key);\n if (!existing || result.relevance > existing.relevance) {\n relevantResults.set(key, result);\n }\n }\n }\n\n // Also always include key documents\n const keyDocs = ['architecture', 'patterns', 'file-structure', 'security'];\n for (const keyDoc of keyDocs) {\n const doc = docs.find(d => d.filename === keyDoc);\n if (doc && doc.sections.length > 0) {\n const key = `${doc.filename}:${doc.sections[0].heading}`;\n if (!relevantResults.has(key)) {\n relevantResults.set(key, {\n doc,\n section: doc.sections[0],\n relevance: 3, // Base relevance for key docs\n });\n }\n }\n }\n\n // Convert to array and sort by relevance\n const sortedResults = Array.from(relevantResults.values())\n .sort((a, b) => b.relevance - a.relevance)\n .slice(0, 10); // Top 10 most relevant sections\n\n // Build context\n const relevantDocs = sortedResults.map(result => ({\n filename: result.doc.filename,\n title: result.doc.title,\n section: result.section.heading,\n content: result.section.content.trim(),\n relevance: result.relevance,\n }));\n\n // Build summary\n const summary = buildContextSummary(docs, relevantDocs);\n\n return {\n available: true,\n summary,\n relevantDocs,\n totalDocs: docs.length,\n };\n}\n\n/**\n * Extract keywords from PR context for semantic search\n */\nfunction extractKeywords(prContext: {\n title?: string;\n files: Array<{ path: string; diff?: string }>;\n diff?: string;\n}): string[] {\n const keywords = new Set();\n\n // From title\n if (prContext.title) {\n const titleWords = prContext.title\n .toLowerCase()\n .split(/\\s+/)\n .filter(w => w.length > 3 && !isCommonWord(w));\n titleWords.forEach(w => keywords.add(w));\n }\n\n // From file paths\n for (const file of prContext.files) {\n const pathParts = file.path.split(/[\\/\\-_\\.]/);\n for (const part of pathParts) {\n if (part.length > 3 && !isCommonWord(part.toLowerCase())) {\n keywords.add(part.toLowerCase());\n }\n }\n\n // Extract from file extensions and directories\n if (file.path.includes('test')) keywords.add('testing');\n if (file.path.includes('api')) keywords.add('api');\n if (file.path.includes('auth')) keywords.add('authentication');\n if (file.path.includes('db') || file.path.includes('database')) keywords.add('database');\n if (file.path.includes('security')) keywords.add('security');\n if (file.path.includes('schema')) keywords.add('schema');\n if (file.path.includes('config')) keywords.add('configuration');\n if (file.path.includes('migration')) keywords.add('migration');\n }\n\n // From diff content (look for imports, function names, etc.)\n if (prContext.diff) {\n // Extract import statements\n const importMatches = prContext.diff.matchAll(/import\\s+.*?\\s+from\\s+['\"]([^'\"]+)['\"]/g);\n for (const match of importMatches) {\n const importPath = match[1];\n const parts = importPath.split(/[\\/\\-_]/);\n for (const part of parts) {\n if (part.length > 3 && !isCommonWord(part)) {\n keywords.add(part);\n }\n }\n }\n\n // Extract class and function names\n const classMatches = prContext.diff.matchAll(/class\\s+(\\w+)/g);\n for (const match of classMatches) {\n keywords.add(match[1].toLowerCase());\n }\n\n const functionMatches = prContext.diff.matchAll(/function\\s+(\\w+)/g);\n for (const match of functionMatches) {\n if (match[1].length > 3) {\n keywords.add(match[1].toLowerCase());\n }\n }\n }\n\n return Array.from(keywords).slice(0, 20); // Limit to top 20 keywords\n}\n\n/**\n * Check if a word is too common to be useful\n */\nfunction isCommonWord(word: string): boolean {\n const commonWords = new Set([\n 'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'been',\n 'will', 'your', 'more', 'when', 'some', 'them', 'than', 'into', 'only',\n 'other', 'then', 'also', 'make', 'made', 'like', 'time', 'very', 'just',\n 'file', 'code', 'test', 'docs', 'info', 'data', 'type', 'name', 'index',\n ]);\n return commonWords.has(word);\n}\n\n/**\n * Build a summary of the context\n */\nfunction buildContextSummary(docs: ArchDoc[], relevantDocs: any[]): string {\n const docTitles = docs.map(d => d.title).join(', ');\n const relevantCount = relevantDocs.length;\n \n let summary = `Architecture Documentation Context:\\n`;\n summary += `- Total documents: ${docs.length}\\n`;\n summary += `- Available: ${docTitles}\\n`;\n summary += `- Relevant sections retrieved: ${relevantCount}\\n\\n`;\n \n if (relevantCount > 0) {\n summary += `Most relevant sections:\\n`;\n relevantDocs.slice(0, 5).forEach((doc, i) => {\n summary += `${i + 1}. ${doc.title} - ${doc.section} (relevance: ${doc.relevance})\\n`;\n });\n }\n\n return summary;\n}\n\n/**\n * Format arch-docs context for inclusion in prompts\n */\nexport function formatArchDocsForPrompt(context: ArchDocsContext): string {\n if (!context.available || context.relevantDocs.length === 0) {\n return '';\n }\n\n let prompt = '\\n## Repository Architecture Context\\n\\n';\n prompt += 'The following sections from the architecture documentation are relevant to this PR:\\n\\n';\n\n for (const doc of context.relevantDocs) {\n prompt += `### ${doc.title} - ${doc.section}\\n\\n`;\n prompt += doc.content + '\\n\\n';\n prompt += '---\\n\\n';\n }\n\n return prompt;\n}\n\n/**\n * Get specific context for risk analysis\n */\nexport function getSecurityContext(docs: ArchDoc[]): string {\n const securityDoc = docs.find(d => d.filename === 'security');\n if (securityDoc) {\n return securityDoc.content;\n }\n return '';\n}\n\n/**\n * Get specific context for architecture understanding\n */\nexport function getArchitectureContext(docs: ArchDoc[]): string {\n const archDoc = docs.find(d => d.filename === 'architecture');\n if (archDoc) {\n return archDoc.content;\n }\n return '';\n}\n\n/**\n * Get specific context for patterns\n */\nexport function getPatternsContext(docs: ArchDoc[]): string {\n const patternsDoc = docs.find(d => d.filename === 'patterns');\n if (patternsDoc) {\n return patternsDoc.content;\n }\n return '';\n}\n\n","/**\n * Base PR Agent Workflow using LangGraph\n * Follows architecture-doc-generator patterns with self-refinement\n */\n\nimport { StateGraph, Annotation, END } from '@langchain/langgraph';\nimport { MemorySaver } from '@langchain/langgraph';\nimport { BaseChatModel } from '@langchain/core/language_models/chat_models';\nimport { AgentContext, AgentResult, FileAnalysis, AgentExecutionOptions } from '../types/agent.types.js';\nimport {\n parseDiff,\n createFileAnalyzerTool,\n createRiskDetectorTool,\n createComplexityScorerTool,\n createSummaryGeneratorTool,\n} from '../tools/pr-analysis-tools.js';\nimport { formatArchDocsForPrompt, getSecurityContext, getPatternsContext } from '../utils/arch-docs-rag.js';\nimport { parseAllArchDocs } from '../utils/arch-docs-parser.js';\n\n/**\n * Agent workflow state\n */\nexport const PRAgentState = Annotation.Root({\n // Input context\n context: Annotation({\n reducer: (_, update) => update,\n }),\n\n // Current iteration\n iteration: Annotation({\n reducer: (_, update) => update,\n default: () => 0,\n }),\n\n // File analyses\n fileAnalyses: Annotation>({\n reducer: (_, update) => update,\n default: () => new Map(),\n }),\n\n // Current analysis state\n currentSummary: Annotation({\n reducer: (_, update) => update,\n default: () => '',\n }),\n\n currentRisks: Annotation({\n reducer: (_, update) => update,\n default: () => [],\n }),\n\n currentComplexity: Annotation({\n reducer: (_, update) => update,\n default: () => 1,\n }),\n\n // Quality metrics\n clarityScore: Annotation({\n reducer: (_, update) => update,\n default: () => 0,\n }),\n\n missingInformation: Annotation({\n reducer: (_, update) => update,\n default: () => [],\n }),\n\n // Recommendations\n recommendations: Annotation({\n reducer: (_, update) => update,\n default: () => [],\n }),\n\n // Insights and reasoning\n insights: Annotation({\n reducer: (current, update) => [...current, ...update],\n default: () => [],\n }),\n\n reasoning: Annotation({\n reducer: (current, update) => [...current, ...update],\n default: () => [],\n }),\n\n // Arch-docs tracking\n archDocsInfluencedStages: Annotation({\n reducer: (current, update) => [...current, ...update],\n default: () => [],\n }),\n\n archDocsKeyInsights: Annotation({\n reducer: (current, update) => [...current, ...update],\n default: () => [],\n }),\n\n // Token tracking\n totalInputTokens: Annotation({\n reducer: (current, update) => current + update,\n default: () => 0,\n }),\n\n totalOutputTokens: Annotation({\n reducer: (current, update) => current + update,\n default: () => 0,\n }),\n});\n\n/**\n * Configuration for PR agent workflow\n */\nexport interface PRAgentWorkflowConfig {\n maxIterations: number;\n clarityThreshold: number;\n skipSelfRefinement?: boolean;\n}\n\n/**\n * Base class for PR agents with self-refinement workflow\n */\nexport abstract class BasePRAgentWorkflow {\n protected model: BaseChatModel;\n protected workflow: ReturnType;\n protected checkpointer = new MemorySaver();\n protected tools: any[];\n\n constructor(model: BaseChatModel) {\n this.model = model;\n\n // Initialize tools\n this.tools = [\n createFileAnalyzerTool(),\n createRiskDetectorTool(),\n createComplexityScorerTool(),\n createSummaryGeneratorTool(),\n ];\n\n this.workflow = this.buildWorkflow();\n }\n\n /**\n * Build the PR analysis workflow\n */\n private buildWorkflow() {\n const graph = new StateGraph(PRAgentState);\n\n // Define nodes\n graph.addNode('analyzeFiles', this.analyzeFilesNode.bind(this));\n graph.addNode('detectRisks', this.detectRisksNode.bind(this));\n graph.addNode('calculateComplexity', this.calculateComplexityNode.bind(this));\n graph.addNode('generateSummary', this.generateSummaryNode.bind(this));\n graph.addNode('evaluateQuality', this.evaluateQualityNode.bind(this));\n graph.addNode('refineAnalysis', this.refineAnalysisNode.bind(this));\n graph.addNode('finalize', this.finalizeNode.bind(this));\n\n // Set entry point\n const entryPoint = 'analyzeFiles' as '__start__';\n graph.setEntryPoint(entryPoint);\n\n // Build workflow graph\n graph.addEdge(entryPoint, 'detectRisks' as '__start__');\n graph.addEdge('detectRisks' as '__start__', 'calculateComplexity' as '__start__');\n graph.addEdge('calculateComplexity' as '__start__', 'generateSummary' as '__start__');\n graph.addEdge('generateSummary' as '__start__', 'evaluateQuality' as '__start__');\n\n // Conditional: refine or finalize\n graph.addConditionalEdges('evaluateQuality' as '__start__', this.shouldRefine.bind(this), {\n refine: 'refineAnalysis' as '__start__',\n finalize: 'finalize' as '__start__',\n });\n\n // After refinement, evaluate again\n graph.addEdge('refineAnalysis' as '__start__', 'evaluateQuality' as '__start__');\n\n // End after finalization\n graph.addEdge('finalize' as '__start__', END);\n\n return graph.compile({ checkpointer: this.checkpointer });\n }\n\n /**\n * Execute the agent workflow\n */\n async execute(context: AgentContext, options?: AgentExecutionOptions): Promise {\n const startTime = Date.now();\n\n // Fast path: skip self-refinement\n if (options?.skipSelfRefinement) {\n return this.executeFastPath(context, startTime);\n }\n\n const config: PRAgentWorkflowConfig = {\n maxIterations: 3,\n clarityThreshold: 80,\n skipSelfRefinement: false,\n };\n\n const initialState = {\n context,\n iteration: 0,\n fileAnalyses: new Map(),\n currentSummary: '',\n currentRisks: [],\n currentComplexity: 1,\n clarityScore: 0,\n missingInformation: [],\n recommendations: [],\n insights: [],\n reasoning: [],\n totalInputTokens: 0,\n totalOutputTokens: 0,\n };\n\n const workflowConfig = {\n configurable: {\n thread_id: `pr-agent-${Date.now()}`,\n maxIterations: config.maxIterations,\n clarityThreshold: config.clarityThreshold,\n },\n recursionLimit: 50,\n };\n\n let finalState = initialState;\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n\n // Execute workflow - stream returns state updates\n try {\n for await (const state of await this.workflow.stream(initialState, workflowConfig as any)) {\n // Get the last node's state\n const nodeNames = Object.keys(state);\n if (nodeNames.length > 0) {\n const lastNodeName = nodeNames[nodeNames.length - 1];\n finalState = (state as any)[lastNodeName] || finalState;\n\n // Extract token counts if present\n const stateAny = finalState as any;\n if (stateAny.totalInputTokens !== undefined) {\n totalInputTokens = stateAny.totalInputTokens;\n }\n if (stateAny.totalOutputTokens !== undefined) {\n totalOutputTokens = stateAny.totalOutputTokens;\n }\n }\n }\n } catch (error) {\n console.error('Workflow execution error:', error);\n throw error;\n }\n\n const executionTime = Date.now() - startTime;\n\n // Build arch-docs impact summary with deduplication\n const stateAny = finalState as any;\n const archDocsImpact = context.archDocs?.available ? {\n used: true,\n docsAvailable: context.archDocs.totalDocs,\n sectionsUsed: context.archDocs.relevantDocs.length,\n influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])],\n keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])],\n } : undefined;\n\n return {\n summary: finalState.currentSummary,\n fileAnalyses: finalState.fileAnalyses,\n overallComplexity: finalState.currentComplexity,\n overallRisks: finalState.currentRisks,\n recommendations: finalState.recommendations,\n insights: finalState.insights,\n reasoning: finalState.reasoning,\n provider: 'ai',\n model: (this.model as any).modelName || 'unknown',\n totalTokensUsed: totalInputTokens + totalOutputTokens,\n executionTime,\n mode: context.mode,\n archDocsImpact,\n };\n }\n\n /**\n * Fast path execution - skip refinement loop but still use LLM for detailed analysis\n */\n private async executeFastPath(context: AgentContext, startTime: number): Promise {\n // Initialize state\n const initialState = {\n context,\n iteration: 0,\n fileAnalyses: new Map(),\n currentSummary: '',\n currentRisks: [] as string[],\n currentComplexity: 1,\n clarityScore: 0,\n missingInformation: [] as string[],\n recommendations: [] as string[],\n insights: [] as string[],\n reasoning: [] as string[],\n totalInputTokens: 0,\n totalOutputTokens: 0,\n };\n\n // Execute workflow nodes sequentially (skip refinement loop)\n let state: any = initialState;\n\n try {\n // 1. Analyze files\n state = await this.analyzeFilesNode(state);\n \n // 2. Detect risks\n state = await this.detectRisksNode(state);\n \n // 3. Calculate complexity\n state = await this.calculateComplexityNode(state);\n \n // 4. Generate summary\n state = await this.generateSummaryNode(state);\n \n // 5. Generate recommendations (skip quality evaluation)\n state = await this.refineAnalysisNode(state);\n \n // 6. Finalize\n state = await this.finalizeNode(state);\n\n const executionTime = Date.now() - startTime;\n\n // Build arch-docs impact summary with deduplication\n const stateAny = state as any;\n const archDocsImpact = context.archDocs?.available ? {\n used: true,\n docsAvailable: context.archDocs.totalDocs,\n sectionsUsed: context.archDocs.relevantDocs.length,\n influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])],\n keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])],\n } : undefined;\n\n return {\n summary: state.currentSummary,\n fileAnalyses: state.fileAnalyses,\n overallComplexity: state.currentComplexity,\n overallRisks: state.currentRisks,\n recommendations: state.recommendations,\n insights: state.insights,\n reasoning: [...state.reasoning, 'Fast path: Self-refinement evaluation skipped for speed'],\n provider: 'ai',\n model: (this.model as any).modelName || 'unknown',\n totalTokensUsed: state.totalInputTokens + state.totalOutputTokens,\n executionTime,\n mode: context.mode,\n archDocsImpact,\n };\n } catch (error) {\n console.error('Fast path execution error:', error);\n throw error;\n }\n }\n\n // Workflow nodes\n\n private async analyzeFilesNode(state: typeof PRAgentState.State) {\n const { context } = state;\n const files = parseDiff(context.diff);\n \n console.log(`🔍 Analyzing ${files.length} files...`);\n \n // Show arch-docs status if available\n if (context.archDocs?.available) {\n console.log(`📚 Using architecture documentation (${context.archDocs.totalDocs} docs, ${context.archDocs.relevantDocs.length} relevant sections)`);\n }\n\n const fileAnalyses = new Map();\n\n // Build arch-docs context if available\n let archDocsContext = '';\n if (context.archDocs?.available) {\n archDocsContext = formatArchDocsForPrompt(context.archDocs);\n }\n\n // Analyze files in batches for detailed insights\n const filesToAnalyze = files.slice(0, 15); // Limit to 15 files for detailed analysis\n const importantFiles = filesToAnalyze.filter(f => \n f.additions + f.deletions > 20 || // Significant changes\n f.path.includes('config') || \n f.path.includes('schema') ||\n f.path.includes('migration') ||\n f.path.includes('test')\n ).slice(0, 5); // Top 5 important files\n\n // Get detailed analysis for important files\n if (importantFiles.length > 0) {\n try {\n\n const fileDetailsPrompt = `Analyze these files from a pull request. For EACH file, provide a detailed analysis considering the repository's architecture standards.\n${archDocsContext ? '\\n' + archDocsContext : ''}\n\nFiles to analyze:\n${importantFiles.map(f => `\nFile: ${f.path}\nStatus: ${f.status || 'modified'}\nChanges: +${f.additions} -${f.deletions}\nDiff preview:\n\\`\\`\\`\n${f.diff.substring(0, 500)}\n\\`\\`\\`\n`).join('\\n---\\n')}\n\n${archDocsContext ? `CRITICAL INSTRUCTIONS:\n- For EACH file, reference the relevant architecture documentation sections above\n- Explain how the changes align with or diverge from established patterns\n- Identify specific guidelines that apply to each file\n- Mention which parts of the architecture are affected\n- Compare changes against documented standards\n\n` : ''}\n\nRespond with a JSON object mapping file paths to analysis objects:\n{\n \"path/to/file\": {\n \"summary\": \"Description that references relevant arch-docs patterns/guidelines\",\n \"risks\": [\"risk with arch-docs context\", \"risk2\"],\n \"complexity\": 1-5,\n \"recommendations\": [\"recommendation based on arch-docs standards\"]\n }\n}\n\n${archDocsContext ? 'Each summary MUST reference the specific architecture documentation that applies to this file.' : ''}`;\n\n const response = await this.model.invoke(fileDetailsPrompt);\n const content = response.content as string;\n \n // Track tokens\n const usage = (response.response_metadata as any)?.usage;\n const inputTokens = usage?.input_tokens || 0;\n const outputTokens = usage?.output_tokens || 0;\n\n // Parse detailed file analyses\n try {\n const jsonMatch = content.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n const detailedAnalyses = JSON.parse(jsonMatch[0]);\n \n // Apply detailed analysis to file analyses\n for (const file of importantFiles) {\n const detail = detailedAnalyses[file.path];\n if (detail) {\n fileAnalyses.set(file.path, {\n path: file.path,\n summary: detail.summary || `${file.status || 'M'}: +${file.additions} -${file.deletions}`,\n risks: Array.isArray(detail.risks) ? detail.risks : [],\n complexity: detail.complexity || Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1),\n changes: {\n additions: file.additions,\n deletions: file.deletions,\n },\n recommendations: Array.isArray(detail.recommendations) ? detail.recommendations : [],\n });\n }\n }\n }\n } catch (parseError) {\n console.warn('Failed to parse file analysis JSON, using basic analysis');\n }\n\n // Update state with token tracking\n state = {\n ...state,\n totalInputTokens: (state.totalInputTokens || 0) + inputTokens,\n totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens,\n };\n } catch (error) {\n console.warn('Error in detailed file analysis, falling back to basic:', error);\n }\n }\n\n // Add basic analysis for remaining files\n for (const file of filesToAnalyze) {\n if (!fileAnalyses.has(file.path)) {\n const analysis: FileAnalysis = {\n path: file.path,\n summary: `${file.status || 'M'}: +${file.additions} -${file.deletions}`,\n risks: [],\n complexity: Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1),\n changes: {\n additions: file.additions,\n deletions: file.deletions,\n },\n recommendations: [],\n };\n\n fileAnalyses.set(file.path, analysis);\n }\n }\n\n // Track arch-docs usage\n const newInsights = [`Analyzed ${files.length} files (${importantFiles.length} in detail)`];\n const hasArchDocsContext = archDocsContext && archDocsContext.length > 0;\n const archDocsStages = hasArchDocsContext ? ['file-analysis'] : [];\n const archDocsInsights = [];\n \n if (hasArchDocsContext && context.archDocs?.available) {\n archDocsInsights.push(`Applied ${context.archDocs.relevantDocs.length} architecture documentation sections to analyze files in context of repository standards`);\n }\n\n return {\n ...state,\n fileAnalyses,\n insights: newInsights,\n archDocsInfluencedStages: archDocsStages,\n archDocsKeyInsights: archDocsInsights,\n };\n }\n\n private async detectRisksNode(state: typeof PRAgentState.State) {\n const { context, fileAnalyses } = state;\n \n console.log('⚠️ Detecting risks...');\n\n // Build context for risk analysis\n const fileList = Array.from(fileAnalyses.entries())\n .slice(0, 15)\n .map(([path, analysis]) => \n `${path} (+${analysis.changes.additions} -${analysis.changes.deletions})`\n )\n .join('\\n');\n\n // Get a sample of the diff for risk analysis (limit size)\n const diffSample = context.diff.substring(0, 8000); // First 8KB for context\n\n // Add security context from arch-docs if available\n let securityContext = '';\n let allDocs: any[] = [];\n let securityDoc: any = null;\n let patternsDoc: any = null;\n \n if (context.archDocs?.available) {\n allDocs = parseAllArchDocs();\n const secDoc = getSecurityContext(allDocs);\n if (secDoc) {\n securityContext = `\\n## Security Guidelines from Repository Documentation\\n\\n${secDoc.substring(0, 3000)}\\n`;\n securityDoc = allDocs.find(d => d.filename === 'security');\n }\n \n // Also get patterns that might indicate risks\n const patterns = getPatternsContext(allDocs);\n if (patterns) {\n securityContext += `\\n## Repository Patterns and Best Practices\\n\\n${patterns.substring(0, 2000)}\\n`;\n patternsDoc = allDocs.find(d => d.filename === 'patterns');\n }\n }\n\n const riskPrompt = `You are a security and code quality expert analyzing a pull request for potential risks.\n${securityContext}\n\nAnalyze the following changes and identify SPECIFIC risks in these categories:\n1. **Security Risks**: Exposed credentials, insecure patterns, authentication/authorization issues\n2. **Breaking Changes**: API changes, database schema changes, removed functionality\n3. **Performance Concerns**: Inefficient algorithms, memory leaks, N+1 queries\n4. **Code Quality**: Complex logic, missing error handling, lack of tests\n5. **Operational Risks**: Configuration changes, deployment concerns, dependency updates\n\nPR Title: ${context.title || 'No title provided'}\n\nFiles changed:\n${fileList}\n\nDiff sample:\n\\`\\`\\`\n${diffSample}\n\\`\\`\\`\n\n${securityContext ? `CRITICAL INSTRUCTIONS:\n- You MUST reference the repository documentation guidelines above when identifying each risk\n- For EVERY risk you identify, find the relevant guideline from the documentation\n- Explain HOW the code change violates or conflicts with the documented standards\n- Quote the specific guideline that makes this a risk\n- Be specific about why this matters based on the repository's own standards\n\nExample format for a risk with documentation:\n{\n \"description\": \"File exceeds maximum line count recommended for maintainability\",\n \"archDocsSource\": \"code-quality.md\",\n \"archDocsExcerpt\": \"Keep individual files under 500 lines to maintain testability and readability\",\n \"reason\": \"This file contains 990 lines, nearly 2x the repository standard, which increases maintenance burden and makes comprehensive testing more difficult\"\n}\n` : ''}\n\nProvide a JSON array of risk objects. Each risk MUST include:\n- description: Clear, specific description of the risk\n${securityContext ? `- archDocsSource: REQUIRED - Which documentation file from above this relates to (e.g., \"security.md\", \"patterns.md\", \"code-quality.md\")\n- archDocsExcerpt: REQUIRED - Direct quote from the repository documentation that this violates\n- reason: REQUIRED - Detailed explanation of why this is a risk based on the specific guideline quoted above\n` : ''}\n\nFormat:\n${securityContext ? `[\n {\n \"description\": \"Specific risk description\",\n \"archDocsSource\": \"documentation-file.md\",\n \"archDocsExcerpt\": \"Exact quote from the documentation\",\n \"reason\": \"Detailed explanation connecting the code change to the guideline violation\"\n }\n]\n\nDO NOT return simple string arrays. Each risk MUST be an object with archDocsSource, archDocsExcerpt, and reason fields.` : '[\"risk 1\", \"risk 2\", ...]'}\n\nOnly include risks that are actually present. If no significant risks, return an empty array [].`;\n\n try {\n const response = await this.model.invoke(riskPrompt);\n const content = response.content as string;\n \n // Track tokens\n const usage = (response.response_metadata as any)?.usage;\n const inputTokens = usage?.input_tokens || 0;\n const outputTokens = usage?.output_tokens || 0;\n\n // Parse JSON response\n let risks: any[] = [];\n let hasArchDocsEnhancement = false;\n \n try {\n // Extract JSON from markdown code blocks if present\n const jsonMatch = content.match(/\\[[\\s\\S]*\\]/);\n if (jsonMatch) {\n const parsedRisks = JSON.parse(jsonMatch[0]);\n \n // Check if risks have arch-docs references\n if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'object' && 'archDocsSource' in parsedRisks[0]) {\n // Transform to our RiskItem format\n risks = parsedRisks.map((r: any) => ({\n description: r.description,\n archDocsReference: r.archDocsSource ? {\n source: r.archDocsSource,\n excerpt: r.archDocsExcerpt || '',\n reason: r.reason || '',\n } : undefined,\n }));\n hasArchDocsEnhancement = true;\n } else if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'string') {\n // Legacy format - just strings\n risks = parsedRisks;\n } else {\n risks = parsedRisks;\n }\n }\n } catch (parseError) {\n console.warn('Failed to parse risk JSON, extracting manually');\n // Fallback: extract bullet points as strings\n const lines = content.split('\\n');\n risks = lines\n .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•'))\n .map(line => line.replace(/^[-•]\\s*/, '').trim())\n .filter(line => line.length > 0);\n }\n\n // Add basic pattern-based checks with arch-docs enhancement\n const patternRisks: any[] = [];\n if (context.diff.includes('password') || context.diff.includes('secret') || context.diff.includes('api_key')) {\n const riskDesc = 'Potential credentials or sensitive data in code changes';\n if (securityDoc) {\n // Always enhance with arch-docs if available\n patternRisks.push({\n description: riskDesc,\n archDocsReference: {\n source: 'security.md',\n excerpt: 'Never commit credentials, API keys, or secrets to the repository. Use environment variables for all sensitive configuration.',\n reason: 'Code changes contain keywords like \"password\", \"secret\", or \"api_key\" which may indicate hardcoded credentials. This violates the repository security policy requiring all secrets to be externalized via environment variables.',\n },\n });\n } else {\n patternRisks.push(riskDesc);\n }\n }\n \n if (fileAnalyses.size > 20) {\n const qualityDoc = allDocs.find(d => d.filename === 'code-quality');\n if (qualityDoc && securityContext) {\n patternRisks.push({\n description: `Large change set (${fileAnalyses.size} files) increases review complexity and error risk`,\n archDocsReference: {\n source: 'code-quality.md',\n excerpt: 'Keep pull requests focused and under 15 files when possible for thorough review',\n reason: `This PR modifies ${fileAnalyses.size} files, exceeding the recommended limit. Large PRs are harder to review thoroughly and increase the likelihood of missing critical issues.`,\n },\n });\n } else {\n patternRisks.push(`Large change set (${fileAnalyses.size} files) - may be difficult to review thoroughly`);\n }\n }\n \n if (context.diff.includes('DROP TABLE') || context.diff.includes('ALTER TABLE')) {\n if (securityContext) {\n patternRisks.push({\n description: 'Database schema changes detected - requires careful migration planning',\n archDocsReference: {\n source: 'patterns.md',\n excerpt: 'All database schema changes must be backwards-compatible and include rollback procedures',\n reason: 'The changes include database schema modifications (DROP TABLE or ALTER TABLE) which can cause data loss or application downtime if not properly planned and tested.',\n },\n });\n } else {\n patternRisks.push('Database schema changes detected - requires careful migration planning');\n }\n }\n\n // Merge risks, avoiding duplicates (for string risks)\n let allRisks: any[];\n if (hasArchDocsEnhancement) {\n // Keep structured risks\n allRisks = [...risks, ...patternRisks];\n } else {\n // Deduplicate string risks\n allRisks = [...new Set([...risks, ...patternRisks])];\n }\n\n // Track arch-docs usage in risk detection\n const archDocsStages = securityContext ? ['risk-detection'] : [];\n const archDocsInsights = [];\n \n if (securityContext && context.archDocs?.available) {\n const enhancedCount = allRisks.filter(r => typeof r === 'object' && r.archDocsReference).length;\n if (enhancedCount > 0) {\n archDocsInsights.push(`Linked ${enhancedCount} risks to specific repository security guidelines and best practices`);\n }\n }\n\n return {\n ...state,\n currentRisks: allRisks,\n insights: [`Identified ${allRisks.length} potential risks`],\n totalInputTokens: (state.totalInputTokens || 0) + inputTokens,\n totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens,\n archDocsInfluencedStages: archDocsStages,\n archDocsKeyInsights: archDocsInsights,\n };\n } catch (error) {\n console.error('Error in risk detection:', error);\n \n // Fallback to basic pattern matching\n const basicRisks: string[] = [];\n if (context.diff.includes('password') || context.diff.includes('secret')) {\n basicRisks.push('Potential credentials in diff');\n }\n if (fileAnalyses.size > 15) {\n basicRisks.push('Large change set - difficult to review');\n }\n\n return {\n ...state,\n currentRisks: basicRisks,\n insights: [`Identified ${basicRisks.length} potential risks (basic analysis)`],\n };\n }\n }\n\n private async calculateComplexityNode(state: typeof PRAgentState.State) {\n const { fileAnalyses, context } = state;\n \n console.log('📊 Calculating complexity...');\n\n const complexities = Array.from(fileAnalyses.values()).map(f => f.complexity);\n const avgComplexity = complexities.length > 0\n ? complexities.reduce((a, b) => a + b, 0) / complexities.length\n : 1;\n\n // Track arch-docs influence on complexity\n const archDocsStages = context.archDocs?.available ? ['complexity-calculation'] : [];\n const archDocsInsights = [];\n \n if (context.archDocs?.available) {\n // Check if patterns documentation helped understand complexity\n const allDocs = parseAllArchDocs();\n const patterns = getPatternsContext(allDocs);\n if (patterns) {\n archDocsInsights.push(`Evaluated complexity against repository design patterns and coding standards`);\n }\n }\n\n return {\n ...state,\n currentComplexity: Math.round(avgComplexity),\n archDocsInfluencedStages: archDocsStages,\n archDocsKeyInsights: archDocsInsights,\n };\n }\n\n private async generateSummaryNode(state: typeof PRAgentState.State) {\n const { context, fileAnalyses, currentRisks, currentComplexity } = state;\n \n console.log('📝 Generating detailed summary...');\n\n const totalFiles = fileAnalyses.size;\n const totalAdditions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.additions, 0);\n const totalDeletions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.deletions, 0);\n\n // Build file list with changes\n const fileList = Array.from(fileAnalyses.entries())\n .slice(0, 20)\n .map(([path, analysis]) => \n `- ${path}: +${analysis.changes.additions} -${analysis.changes.deletions} (complexity: ${analysis.complexity}/5)`\n )\n .join('\\n');\n\n // Add patterns context from arch-docs if available\n let patternsContext = '';\n if (context.archDocs?.available) {\n const allDocs = parseAllArchDocs();\n const patterns = getPatternsContext(allDocs);\n if (patterns) {\n patternsContext = `\\n## Design Patterns from Repository Documentation\\n\\n${patterns.substring(0, 2000)}\\n`;\n }\n }\n\n // Create comprehensive prompt for LLM\n const summaryPrompt = `You are analyzing a pull request. Provide a DETAILED and COMPREHENSIVE summary that covers:\n\n1. **Overall Purpose**: What is this PR trying to accomplish? What problem does it solve?\n2. **Key Changes**: What are the main changes being made? Group related changes together.\n3. **Impact Analysis**: What parts of the system are affected? What are the implications?\n4. **Technical Details**: Mention important technical aspects (new dependencies, API changes, data model changes, etc.)\n5. **Patterns Observed**: Any design patterns, refactoring, or architectural changes?\n${patternsContext}\n\nPR Title: ${context.title || 'No title provided'}\n\nStatistics:\n- Files changed: ${totalFiles}\n- Lines added: ${totalAdditions}\n- Lines deleted: ${totalDeletions}\n- Overall complexity: ${currentComplexity}/5\n- Risks identified: ${currentRisks.length}\n\nFiles changed:\n${fileList}\n\n${currentRisks.length > 0 ? `\\nRisks detected:\\n${currentRisks.map(r => `- ${r}`).join('\\n')}` : ''}\n\n${patternsContext ? 'Consider the design patterns and architecture from the repository documentation when analyzing the changes.\\n' : ''}\n\nProvide a detailed, well-structured summary (3-5 paragraphs) that would help a reviewer understand the scope and purpose of this PR.`;\n\n try {\n const response = await this.model.invoke(summaryPrompt);\n const detailedSummary = response.content as string;\n\n // Track token usage\n const usage = (response.response_metadata as any)?.usage;\n const inputTokens = usage?.input_tokens || 0;\n const outputTokens = usage?.output_tokens || 0;\n\n // Track arch-docs usage in summary\n const archDocsStages = patternsContext ? ['summary-generation'] : [];\n const archDocsInsights = [];\n \n if (patternsContext && context.archDocs?.available) {\n archDocsInsights.push(`Generated summary aligned with repository architecture and established patterns`);\n }\n\n return {\n ...state,\n currentSummary: detailedSummary,\n totalInputTokens: inputTokens,\n totalOutputTokens: outputTokens,\n archDocsInfluencedStages: archDocsStages,\n archDocsKeyInsights: archDocsInsights,\n };\n } catch (error) {\n console.error('Error generating summary:', error);\n // Fallback to basic summary\n const fallbackSummary = `PR Analysis Summary:\n- Files changed: ${totalFiles}\n- Additions: ${totalAdditions}\n- Deletions: ${totalDeletions}\n- Overall complexity: ${currentComplexity}/5\n- Risks identified: ${currentRisks.length}\n\n${context.title ? `Title: ${context.title}` : ''}`;\n\n return {\n ...state,\n currentSummary: fallbackSummary,\n };\n }\n }\n\n private async evaluateQualityNode(state: typeof PRAgentState.State) {\n const { iteration } = state;\n \n console.log(`🔍 Evaluating quality (iteration ${iteration + 1})...`);\n\n // Simple quality check\n const clarityScore = 85; // Placeholder\n\n return {\n ...state,\n clarityScore,\n iteration: iteration + 1,\n };\n }\n\n private async refineAnalysisNode(state: typeof PRAgentState.State) {\n const { currentSummary, currentRisks, fileAnalyses, context } = state;\n \n console.log('🔄 Refining analysis...');\n\n // Build arch-docs context for refinement\n let archDocsRefinementContext = '';\n if (context.archDocs?.available) {\n const allDocs = parseAllArchDocs();\n \n // Get recommendations from arch-docs\n const recommendationsDoc = allDocs.find(d => d.filename === 'recommendations');\n if (recommendationsDoc) {\n archDocsRefinementContext += `\\n## Repository Improvement Guidelines\\n\\n${recommendationsDoc.content.substring(0, 2000)}\\n`;\n }\n \n // Get code quality guidelines\n const qualityDoc = allDocs.find(d => d.filename === 'code-quality');\n if (qualityDoc) {\n archDocsRefinementContext += `\\n## Code Quality Standards\\n\\n${qualityDoc.content.substring(0, 2000)}\\n`;\n }\n\n // Get KPI metrics\n const kpiDoc = allDocs.find(d => d.filename === 'kpi');\n if (kpiDoc) {\n archDocsRefinementContext += `\\n## Repository Health KPIs\\n\\n${kpiDoc.content.substring(0, 1500)}\\n`;\n }\n }\n\n // Generate comprehensive recommendations\n const refinementPrompt = `Based on this PR analysis, provide specific, actionable recommendations for the developer and reviewers.\n${archDocsRefinementContext}\n\nPR Summary:\n${currentSummary}\n\nRisks Identified:\n${currentRisks.map(r => `- ${r}`).join('\\n')}\n\nFiles Changed: ${fileAnalyses.size}\n\nConsider:\n1. Code organization and structure improvements\n2. Testing recommendations\n3. Documentation needs\n4. Performance optimizations\n5. Security enhancements\n6. Review process suggestions\n${archDocsRefinementContext ? '7. Alignment with repository standards and KPIs from arch-docs\\n' : ''}\n\n${archDocsRefinementContext ? 'Use the repository guidelines and standards above to ensure recommendations align with established practices.\\n' : ''}\n\nProvide a JSON array of 3-5 specific, actionable recommendations:\n[\"recommendation 1\", \"recommendation 2\", ...]`;\n\n try {\n const response = await this.model.invoke(refinementPrompt);\n const content = response.content as string;\n \n // Track tokens\n const usage = (response.response_metadata as any)?.usage;\n const inputTokens = usage?.input_tokens || 0;\n const outputTokens = usage?.output_tokens || 0;\n\n // Parse recommendations\n let recommendations: string[] = [];\n try {\n const jsonMatch = content.match(/\\[[\\s\\S]*\\]/);\n if (jsonMatch) {\n recommendations = JSON.parse(jsonMatch[0]);\n }\n } catch (parseError) {\n // Fallback: extract bullet points\n const lines = content.split('\\n');\n recommendations = lines\n .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•') || /^\\d+\\./.test(line.trim()))\n .map(line => line.replace(/^[-•]\\s*/, '').replace(/^\\d+\\.\\s*/, '').trim())\n .filter(line => line.length > 0)\n .slice(0, 5);\n }\n\n // Add default recommendations if none found\n if (recommendations.length === 0) {\n recommendations = [\n 'Ensure comprehensive test coverage for new functionality',\n 'Update relevant documentation',\n 'Consider performance implications of changes',\n ];\n }\n\n // Track arch-docs usage in refinement\n const archDocsStages = archDocsRefinementContext ? ['refinement'] : [];\n const archDocsInsights = [];\n \n if (archDocsRefinementContext && context.archDocs?.available) {\n archDocsInsights.push(`Generated ${recommendations.length} recommendations based on repository quality standards and KPIs`);\n }\n\n return {\n ...state,\n recommendations,\n totalInputTokens: (state.totalInputTokens || 0) + inputTokens,\n totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens,\n archDocsInfluencedStages: archDocsStages,\n archDocsKeyInsights: archDocsInsights,\n };\n } catch (error) {\n console.error('Error refining analysis:', error);\n return {\n ...state,\n recommendations: [\n 'Review changes carefully for potential side effects',\n 'Ensure test coverage is adequate',\n 'Update documentation as needed',\n ],\n };\n }\n }\n\n private async finalizeNode(state: typeof PRAgentState.State) {\n console.log('✨ Finalizing analysis...');\n \n return state;\n }\n\n private shouldRefine(state: typeof PRAgentState.State): string {\n // Use defaults if config not accessible\n const maxIterations = 3;\n const clarityThreshold = 80;\n\n if (state.iteration >= maxIterations) {\n console.log(`⏹️ Stopping: Max iterations (${maxIterations}) reached`);\n return 'finalize';\n }\n\n if (state.clarityScore >= clarityThreshold) {\n console.log(`✅ Stopping: Clarity threshold (${clarityThreshold}) achieved`);\n return 'finalize';\n }\n\n console.log(`🔄 Continuing: Iteration ${state.iteration}, clarity ${state.clarityScore}`);\n return 'refine';\n }\n}\n\n","import { interopSafeParseAsync } from \"@langchain/core/utils/types\";\nimport { BaseLLMOutputParser, OutputParserException } from \"@langchain/core/output_parsers\";\n\n//#region src/output_parsers.ts\nvar AnthropicToolsOutputParser = class extends BaseLLMOutputParser {\n\tstatic lc_name() {\n\t\treturn \"AnthropicToolsOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"anthropic\",\n\t\t\"output_parsers\"\n\t];\n\treturnId = false;\n\t/** The type of tool calls to return. */\n\tkeyName;\n\t/** Whether to return only the first tool call. */\n\treturnSingle = false;\n\tzodSchema;\n\tconstructor(params) {\n\t\tsuper(params);\n\t\tthis.keyName = params.keyName;\n\t\tthis.returnSingle = params.returnSingle ?? this.returnSingle;\n\t\tthis.zodSchema = params.zodSchema;\n\t}\n\tasync _validateResult(result) {\n\t\tlet parsedResult = result;\n\t\tif (typeof result === \"string\") try {\n\t\t\tparsedResult = JSON.parse(result);\n\t\t} catch (e) {\n\t\t\tthrow new OutputParserException(`Failed to parse. Text: \"${JSON.stringify(result, null, 2)}\". Error: ${JSON.stringify(e.message)}`, result);\n\t\t}\n\t\telse parsedResult = result;\n\t\tif (this.zodSchema === void 0) return parsedResult;\n\t\tconst zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult);\n\t\tif (zodParsedResult.success) return zodParsedResult.data;\n\t\telse throw new OutputParserException(`Failed to parse. Text: \"${JSON.stringify(result, null, 2)}\". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2));\n\t}\n\tasync parseResult(generations) {\n\t\tconst tools = generations.flatMap((generation) => {\n\t\t\tconst { message } = generation;\n\t\t\tif (!Array.isArray(message.content)) return [];\n\t\t\tconst tool$1 = extractToolCalls(message.content)[0];\n\t\t\treturn tool$1;\n\t\t});\n\t\tif (tools[0] === void 0) throw new Error(\"No parseable tool calls provided to AnthropicToolsOutputParser.\");\n\t\tconst [tool] = tools;\n\t\tconst validatedResult = await this._validateResult(tool.args);\n\t\treturn validatedResult;\n\t}\n};\nfunction extractToolCalls(content) {\n\tconst toolCalls = [];\n\tfor (const block of content) if (block.type === \"tool_use\") toolCalls.push({\n\t\tname: block.name,\n\t\targs: block.input,\n\t\tid: block.id,\n\t\ttype: \"tool_call\"\n\t});\n\treturn toolCalls;\n}\n\n//#endregion\nexport { AnthropicToolsOutputParser, extractToolCalls };\n//# sourceMappingURL=output_parsers.js.map","//#region src/utils/tools.ts\nfunction handleToolChoice(toolChoice) {\n\tif (!toolChoice) return void 0;\n\telse if (toolChoice === \"any\") return { type: \"any\" };\n\telse if (toolChoice === \"auto\") return { type: \"auto\" };\n\telse if (toolChoice === \"none\") return { type: \"none\" };\n\telse if (typeof toolChoice === \"string\") return {\n\t\ttype: \"tool\",\n\t\tname: toolChoice\n\t};\n\telse return toolChoice;\n}\n\n//#endregion\nexport { handleToolChoice };\n//# sourceMappingURL=tools.js.map","import { parseBase64DataUrl } from \"@langchain/core/messages\";\n\n//#region src/utils/content.ts\nfunction _isAnthropicThinkingBlock(block) {\n\treturn typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"thinking\";\n}\nfunction _isAnthropicRedactedThinkingBlock(block) {\n\treturn typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"redacted_thinking\";\n}\nfunction _isAnthropicSearchResultBlock(block) {\n\treturn typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"search_result\";\n}\nfunction _isAnthropicImageBlockParam(block) {\n\tif (typeof block !== \"object\" || block == null) return false;\n\tif (!(\"type\" in block) || block.type !== \"image\") return false;\n\tif (!(\"source\" in block) || typeof block.source !== \"object\" || block.source == null) return false;\n\tif (!(\"type\" in block.source)) return false;\n\tif (block.source.type === \"base64\") {\n\t\tif (!(\"media_type\" in block.source)) return false;\n\t\tif (typeof block.source.media_type !== \"string\") return false;\n\t\tif (!(\"data\" in block.source)) return false;\n\t\tif (typeof block.source.data !== \"string\") return false;\n\t\treturn true;\n\t}\n\tif (block.source.type === \"url\") {\n\t\tif (!(\"url\" in block.source)) return false;\n\t\tif (typeof block.source.url !== \"string\") return false;\n\t\treturn true;\n\t}\n\treturn false;\n}\nconst standardContentBlockConverter = {\n\tproviderName: \"anthropic\",\n\tfromStandardTextBlock(block) {\n\t\treturn {\n\t\t\ttype: \"text\",\n\t\t\ttext: block.text,\n\t\t\t...\"citations\" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},\n\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}\n\t\t};\n\t},\n\tfromStandardImageBlock(block) {\n\t\tif (block.source_type === \"url\") {\n\t\t\tconst data = parseBase64DataUrl({\n\t\t\t\tdataUrl: block.url,\n\t\t\t\tasTypedArray: false\n\t\t\t});\n\t\t\tif (data) return {\n\t\t\t\ttype: \"image\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\tdata: data.data,\n\t\t\t\t\tmedia_type: data.mime_type\n\t\t\t\t},\n\t\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}\n\t\t\t};\n\t\t\telse return {\n\t\t\t\ttype: \"image\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"url\",\n\t\t\t\t\turl: block.url\n\t\t\t\t},\n\t\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}\n\t\t\t};\n\t\t} else if (block.source_type === \"base64\") return {\n\t\t\ttype: \"image\",\n\t\t\tsource: {\n\t\t\t\ttype: \"base64\",\n\t\t\t\tdata: block.data,\n\t\t\t\tmedia_type: block.mime_type ?? \"\"\n\t\t\t},\n\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}\n\t\t};\n\t\telse throw new Error(`Unsupported image source type: ${block.source_type}`);\n\t},\n\tfromStandardFileBlock(block) {\n\t\tconst mime_type = (block.mime_type ?? \"\").split(\";\")[0];\n\t\tif (block.source_type === \"url\") {\n\t\t\tif (mime_type === \"application/pdf\" || mime_type === \"\") return {\n\t\t\t\ttype: \"document\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"url\",\n\t\t\t\t\turl: block.url\n\t\t\t\t},\n\t\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},\n\t\t\t\t...\"citations\" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},\n\t\t\t\t...\"context\" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},\n\t\t\t\t...\"title\" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}\n\t\t\t};\n\t\t\tthrow new Error(`Unsupported file mime type for file url source: ${block.mime_type}`);\n\t\t} else if (block.source_type === \"text\") if (mime_type === \"text/plain\" || mime_type === \"\") return {\n\t\t\ttype: \"document\",\n\t\t\tsource: {\n\t\t\t\ttype: \"text\",\n\t\t\t\tdata: block.text,\n\t\t\t\tmedia_type: block.mime_type ?? \"\"\n\t\t\t},\n\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},\n\t\t\t...\"citations\" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},\n\t\t\t...\"context\" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},\n\t\t\t...\"title\" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}\n\t\t};\n\t\telse throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`);\n\t\telse if (block.source_type === \"base64\") if (mime_type === \"application/pdf\" || mime_type === \"\") return {\n\t\t\ttype: \"document\",\n\t\t\tsource: {\n\t\t\t\ttype: \"base64\",\n\t\t\t\tdata: block.data,\n\t\t\t\tmedia_type: \"application/pdf\"\n\t\t\t},\n\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},\n\t\t\t...\"citations\" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},\n\t\t\t...\"context\" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},\n\t\t\t...\"title\" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}\n\t\t};\n\t\telse if ([\n\t\t\t\"image/jpeg\",\n\t\t\t\"image/png\",\n\t\t\t\"image/gif\",\n\t\t\t\"image/webp\"\n\t\t].includes(mime_type)) return {\n\t\t\ttype: \"document\",\n\t\t\tsource: {\n\t\t\t\ttype: \"content\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\tdata: block.data,\n\t\t\t\t\t\tmedia_type: mime_type\n\t\t\t\t\t}\n\t\t\t\t}]\n\t\t\t},\n\t\t\t...\"cache_control\" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},\n\t\t\t...\"citations\" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},\n\t\t\t...\"context\" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},\n\t\t\t...\"title\" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}\n\t\t};\n\t\telse throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`);\n\t\telse throw new Error(`Unsupported file source type: ${block.source_type}`);\n\t}\n};\n\n//#endregion\nexport { _isAnthropicImageBlockParam, _isAnthropicRedactedThinkingBlock, _isAnthropicSearchResultBlock, _isAnthropicThinkingBlock, standardContentBlockConverter };\n//# sourceMappingURL=content.js.map","//#region src/utils/index.ts\nconst iife = (fn) => fn();\n\n//#endregion\nexport { iife };\n//# sourceMappingURL=index.js.map","import { iife } from \"./index.js\";\n\n//#region src/utils/standard.ts\nfunction _isStandardAnnotation(annotation) {\n\treturn typeof annotation === \"object\" && annotation !== null && \"type\" in annotation && annotation.type === \"citation\";\n}\nfunction _formatStandardCitations(annotations) {\n\tfunction* iterateAnnotations() {\n\t\tfor (const annotation of annotations) if (_isStandardAnnotation(annotation)) {\n\t\t\tif (annotation.source === \"char\") yield {\n\t\t\t\ttype: \"char_location\",\n\t\t\t\tfile_id: annotation.url ?? \"\",\n\t\t\t\tstart_char_index: annotation.startIndex ?? 0,\n\t\t\t\tend_char_index: annotation.endIndex ?? 0,\n\t\t\t\tdocument_title: annotation.title ?? null,\n\t\t\t\tdocument_index: 0,\n\t\t\t\tcited_text: annotation.citedText ?? \"\"\n\t\t\t};\n\t\t\telse if (annotation.source === \"page\") yield {\n\t\t\t\ttype: \"page_location\",\n\t\t\t\tfile_id: annotation.url ?? \"\",\n\t\t\t\tstart_page_number: annotation.startIndex ?? 0,\n\t\t\t\tend_page_number: annotation.endIndex ?? 0,\n\t\t\t\tdocument_title: annotation.title ?? null,\n\t\t\t\tdocument_index: 0,\n\t\t\t\tcited_text: annotation.citedText ?? \"\"\n\t\t\t};\n\t\t\telse if (annotation.source === \"block\") yield {\n\t\t\t\ttype: \"content_block_location\",\n\t\t\t\tfile_id: annotation.url ?? \"\",\n\t\t\t\tstart_block_index: annotation.startIndex ?? 0,\n\t\t\t\tend_block_index: annotation.endIndex ?? 0,\n\t\t\t\tdocument_title: annotation.title ?? null,\n\t\t\t\tdocument_index: 0,\n\t\t\t\tcited_text: annotation.citedText ?? \"\"\n\t\t\t};\n\t\t\telse if (annotation.source === \"url\") yield {\n\t\t\t\ttype: \"web_search_result_location\",\n\t\t\t\turl: annotation.url ?? \"\",\n\t\t\t\ttitle: annotation.title ?? null,\n\t\t\t\tencrypted_index: String(annotation.startIndex ?? 0),\n\t\t\t\tcited_text: annotation.citedText ?? \"\"\n\t\t\t};\n\t\t\telse if (annotation.source === \"search\") yield {\n\t\t\t\ttype: \"search_result_location\",\n\t\t\t\ttitle: annotation.title ?? null,\n\t\t\t\tstart_block_index: annotation.startIndex ?? 0,\n\t\t\t\tend_block_index: annotation.endIndex ?? 0,\n\t\t\t\tsearch_result_index: 0,\n\t\t\t\tsource: annotation.source ?? \"\",\n\t\t\t\tcited_text: annotation.citedText ?? \"\"\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateAnnotations());\n}\nfunction _formatBase64Data(data) {\n\tif (typeof data === \"string\") return data;\n\telse return _encodeUint8Array(data);\n}\nfunction _encodeUint8Array(data) {\n\tconst output = [];\n\tfor (let i = 0, { length } = data; i < length; i++) output.push(String.fromCharCode(data[i]));\n\treturn btoa(output.join(\"\"));\n}\nfunction _normalizeMimeType(mimeType) {\n\treturn (mimeType ?? \"\").split(\";\")[0].toLowerCase();\n}\nfunction _extractMetadataValue(metadata, key) {\n\tif (metadata !== void 0 && metadata !== null && typeof metadata === \"object\" && key in metadata) return metadata[key];\n\treturn void 0;\n}\nfunction _applyDocumentMetadata(block, metadata) {\n\tconst cacheControl = _extractMetadataValue(metadata, \"cache_control\");\n\tif (cacheControl !== void 0) block.cache_control = cacheControl;\n\tconst citations = _extractMetadataValue(metadata, \"citations\");\n\tif (citations !== void 0) block.citations = citations;\n\tconst context = _extractMetadataValue(metadata, \"context\");\n\tif (context !== void 0) block.context = context;\n\tconst title = _extractMetadataValue(metadata, \"title\");\n\tif (title !== void 0) block.title = title;\n\treturn block;\n}\nfunction _applyImageMetadata(block, metadata) {\n\tconst cacheControl = _extractMetadataValue(metadata, \"cache_control\");\n\tif (cacheControl !== void 0) block.cache_control = cacheControl;\n\treturn block;\n}\nfunction _hasAllowedImageMimeType(mimeType) {\n\tconst ALLOWED_IMAGE_MIME_TYPES = new Set([\n\t\t\"image/jpeg\",\n\t\t\"image/png\",\n\t\t\"image/gif\",\n\t\t\"image/webp\"\n\t]);\n\treturn ALLOWED_IMAGE_MIME_TYPES.has(mimeType);\n}\nfunction _formatStandardContent(message) {\n\tconst result = [];\n\tconst responseMetadata = message.response_metadata;\n\tconst isAnthropicMessage = \"model_provider\" in responseMetadata && responseMetadata?.model_provider === \"anthropic\";\n\tfor (const block of message.contentBlocks) if (block.type === \"text\") if (block.annotations) result.push({\n\t\ttype: \"text\",\n\t\ttext: block.text,\n\t\tcitations: _formatStandardCitations(block.annotations)\n\t});\n\telse result.push({\n\t\ttype: \"text\",\n\t\ttext: block.text\n\t});\n\telse if (block.type === \"tool_call\") result.push({\n\t\ttype: \"tool_use\",\n\t\tid: block.id ?? \"\",\n\t\tname: block.name,\n\t\tinput: block.args\n\t});\n\telse if (block.type === \"tool_call_chunk\") {\n\t\tconst input = iife(() => {\n\t\t\tif (typeof block.args !== \"string\") return block.args;\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(block.args);\n\t\t\t} catch {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t});\n\t\tresult.push({\n\t\t\ttype: \"tool_use\",\n\t\t\tid: block.id ?? \"\",\n\t\t\tname: block.name ?? \"\",\n\t\t\tinput\n\t\t});\n\t} else if (block.type === \"reasoning\" && isAnthropicMessage) result.push({\n\t\ttype: \"thinking\",\n\t\tthinking: block.reasoning,\n\t\tsignature: String(block.signature)\n\t});\n\telse if (block.type === \"server_tool_call\" && isAnthropicMessage) {\n\t\tif (block.name === \"web_search\") result.push({\n\t\t\ttype: \"server_tool_use\",\n\t\t\tname: block.name,\n\t\t\tid: block.id ?? \"\",\n\t\t\tinput: block.args\n\t\t});\n\t\telse if (block.name === \"code_execution\") result.push({\n\t\t\ttype: \"server_tool_use\",\n\t\t\tname: block.name,\n\t\t\tid: block.id ?? \"\",\n\t\t\tinput: block.args\n\t\t});\n\t} else if (block.type === \"server_tool_call_result\" && isAnthropicMessage) {\n\t\tif (block.name === \"web_search\" && Array.isArray(block.output.urls)) {\n\t\t\tconst content = block.output.urls.map((url) => ({\n\t\t\t\ttype: \"web_search_result\",\n\t\t\t\ttitle: \"\",\n\t\t\t\tencrypted_content: \"\",\n\t\t\t\turl\n\t\t\t}));\n\t\t\tresult.push({\n\t\t\t\ttype: \"web_search_tool_result\",\n\t\t\t\ttool_use_id: block.toolCallId ?? \"\",\n\t\t\t\tcontent\n\t\t\t});\n\t\t} else if (block.name === \"code_execution\") result.push({\n\t\t\ttype: \"code_execution_tool_result\",\n\t\t\ttool_use_id: block.toolCallId ?? \"\",\n\t\t\tcontent: block.output\n\t\t});\n\t\telse if (block.name === \"mcp_tool_result\") result.push({\n\t\t\ttype: \"mcp_tool_result\",\n\t\t\ttool_use_id: block.toolCallId ?? \"\",\n\t\t\tcontent: block.output\n\t\t});\n\t} else if (block.type === \"audio\") throw new Error(\"Anthropic does not support audio content blocks.\");\n\telse if (block.type === \"file\") {\n\t\tconst metadata = block.metadata;\n\t\tif (block.fileId) {\n\t\t\tresult.push(_applyDocumentMetadata({\n\t\t\t\ttype: \"document\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tfile_id: block.fileId\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.url) {\n\t\t\tconst mimeType = _normalizeMimeType(block.mimeType);\n\t\t\tif (mimeType === \"application/pdf\" || mimeType === \"\") {\n\t\t\t\tresult.push(_applyDocumentMetadata({\n\t\t\t\t\ttype: \"document\",\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: \"url\",\n\t\t\t\t\t\turl: block.url\n\t\t\t\t\t}\n\t\t\t\t}, metadata));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (block.data) {\n\t\t\tconst mimeType = _normalizeMimeType(block.mimeType);\n\t\t\tif (mimeType === \"\" || mimeType === \"application/pdf\") result.push(_applyDocumentMetadata({\n\t\t\t\ttype: \"document\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\tdata: _formatBase64Data(block.data),\n\t\t\t\t\tmedia_type: \"application/pdf\"\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\telse if (mimeType === \"text/plain\") result.push(_applyDocumentMetadata({\n\t\t\t\ttype: \"document\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\tdata: _formatBase64Data(block.data),\n\t\t\t\t\tmedia_type: \"text/plain\"\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\telse if (_hasAllowedImageMimeType(mimeType)) result.push(_applyDocumentMetadata({\n\t\t\t\ttype: \"document\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"content\",\n\t\t\t\t\tcontent: [{\n\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\t\t\tdata: _formatBase64Data(block.data),\n\t\t\t\t\t\t\tmedia_type: mimeType\n\t\t\t\t\t\t}\n\t\t\t\t\t}]\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\telse throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new Error(\"File content block must include a fileId, url, or data property.\");\n\t} else if (block.type === \"image\") {\n\t\tconst metadata = block.metadata;\n\t\tif (block.fileId) {\n\t\t\tresult.push(_applyImageMetadata({\n\t\t\t\ttype: \"image\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tfile_id: block.fileId\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.url) {\n\t\t\tresult.push(_applyImageMetadata({\n\t\t\t\ttype: \"image\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"url\",\n\t\t\t\t\turl: block.url\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.data) {\n\t\t\tconst mimeType = _normalizeMimeType(block.mimeType) || \"image/png\";\n\t\t\tif (_hasAllowedImageMimeType(mimeType)) result.push(_applyImageMetadata({\n\t\t\t\ttype: \"image\",\n\t\t\t\tsource: {\n\t\t\t\t\ttype: \"base64\",\n\t\t\t\t\tdata: _formatBase64Data(block.data),\n\t\t\t\t\tmedia_type: mimeType\n\t\t\t\t}\n\t\t\t}, metadata));\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new Error(\"Image content block must include a fileId, url, or data property.\");\n\t} else if (block.type === \"video\") {} else if (block.type === \"text-plain\") {\n\t\tif (block.data) result.push(_applyDocumentMetadata({\n\t\t\ttype: \"document\",\n\t\t\tsource: {\n\t\t\t\ttype: \"text\",\n\t\t\t\tdata: _formatBase64Data(block.data),\n\t\t\t\tmedia_type: \"text/plain\"\n\t\t\t}\n\t\t}, block.metadata));\n\t} else if (block.type === \"non_standard\" && isAnthropicMessage) result.push(block.value);\n\treturn result;\n}\n\n//#endregion\nexport { _formatStandardContent };\n//# sourceMappingURL=standard.js.map","import { _isAnthropicImageBlockParam, _isAnthropicRedactedThinkingBlock, _isAnthropicSearchResultBlock, _isAnthropicThinkingBlock, standardContentBlockConverter } from \"./content.js\";\nimport { _formatStandardContent } from \"./standard.js\";\nimport { HumanMessage, convertToProviderContentBlock, isAIMessage, isDataContentBlock, parseBase64DataUrl } from \"@langchain/core/messages\";\n\n//#region src/utils/message_inputs.ts\nfunction _formatImage(imageUrl) {\n\tconst parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n\tif (parsed) return {\n\t\ttype: \"base64\",\n\t\tmedia_type: parsed.mime_type,\n\t\tdata: parsed.data\n\t};\n\tlet parsedUrl;\n\ttry {\n\t\tparsedUrl = new URL(imageUrl);\n\t} catch {\n\t\tthrow new Error([\n\t\t\t`Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n\t\t\t\"Example: data:image/png;base64,/9j/4AAQSk...\",\n\t\t\t\"Example: https://example.com/image.jpg\"\n\t\t].join(\"\\n\\n\"));\n\t}\n\tif (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") return {\n\t\ttype: \"url\",\n\t\turl: imageUrl\n\t};\n\tthrow new Error([\n\t\t`Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n\t\t\"Example: data:image/png;base64,/9j/4AAQSk...\",\n\t\t\"Example: https://example.com/image.jpg\"\n\t].join(\"\\n\\n\"));\n}\nfunction _ensureMessageContents(messages) {\n\tconst updatedMsgs = [];\n\tfor (const message of messages) if (message._getType() === \"tool\") if (typeof message.content === \"string\") {\n\t\tconst previousMessage = updatedMsgs[updatedMsgs.length - 1];\n\t\tif (previousMessage?._getType() === \"human\" && Array.isArray(previousMessage.content) && \"type\" in previousMessage.content[0] && previousMessage.content[0].type === \"tool_result\") previousMessage.content.push({\n\t\t\ttype: \"tool_result\",\n\t\t\tcontent: message.content,\n\t\t\ttool_use_id: message.tool_call_id\n\t\t});\n\t\telse updatedMsgs.push(new HumanMessage({ content: [{\n\t\t\ttype: \"tool_result\",\n\t\t\tcontent: message.content,\n\t\t\ttool_use_id: message.tool_call_id\n\t\t}] }));\n\t} else updatedMsgs.push(new HumanMessage({ content: [{\n\t\ttype: \"tool_result\",\n\t\t...message.content != null ? { content: _formatContent(message) } : {},\n\t\ttool_use_id: message.tool_call_id\n\t}] }));\n\telse updatedMsgs.push(message);\n\treturn updatedMsgs;\n}\nfunction _convertLangChainToolCallToAnthropic(toolCall) {\n\tif (toolCall.id === void 0) throw new Error(`Anthropic requires all tool calls to have an \"id\".`);\n\treturn {\n\t\ttype: \"tool_use\",\n\t\tid: toolCall.id,\n\t\tname: toolCall.name,\n\t\tinput: toolCall.args\n\t};\n}\nfunction* _formatContentBlocks(content) {\n\tconst toolTypes = [\n\t\t\"bash_code_execution_tool_result\",\n\t\t\"input_json_delta\",\n\t\t\"server_tool_use\",\n\t\t\"text_editor_code_execution_tool_result\",\n\t\t\"tool_result\",\n\t\t\"tool_use\",\n\t\t\"web_search_result\",\n\t\t\"web_search_tool_result\"\n\t];\n\tconst textTypes = [\"text\", \"text_delta\"];\n\tfor (const contentPart of content) {\n\t\tif (isDataContentBlock(contentPart)) yield convertToProviderContentBlock(contentPart, standardContentBlockConverter);\n\t\tconst cacheControl = \"cache_control\" in contentPart ? contentPart.cache_control : void 0;\n\t\tif (contentPart.type === \"image_url\") {\n\t\t\tlet source;\n\t\t\tif (typeof contentPart.image_url === \"string\") source = _formatImage(contentPart.image_url);\n\t\t\telse if (typeof contentPart.image_url === \"object\" && contentPart.image_url !== null && \"url\" in contentPart.image_url && typeof contentPart.image_url.url === \"string\") source = _formatImage(contentPart.image_url.url);\n\t\t\tif (source) yield {\n\t\t\t\ttype: \"image\",\n\t\t\t\tsource,\n\t\t\t\t...cacheControl ? { cache_control: cacheControl } : {}\n\t\t\t};\n\t\t} else if (_isAnthropicImageBlockParam(contentPart)) return contentPart;\n\t\telse if (contentPart.type === \"document\") yield {\n\t\t\t...contentPart,\n\t\t\t...cacheControl ? { cache_control: cacheControl } : {}\n\t\t};\n\t\telse if (_isAnthropicThinkingBlock(contentPart)) {\n\t\t\tconst block = {\n\t\t\t\ttype: \"thinking\",\n\t\t\t\tthinking: contentPart.thinking,\n\t\t\t\tsignature: contentPart.signature,\n\t\t\t\t...cacheControl ? { cache_control: cacheControl } : {}\n\t\t\t};\n\t\t\tyield block;\n\t\t} else if (_isAnthropicRedactedThinkingBlock(contentPart)) {\n\t\t\tconst block = {\n\t\t\t\ttype: \"redacted_thinking\",\n\t\t\t\tdata: contentPart.data,\n\t\t\t\t...cacheControl ? { cache_control: cacheControl } : {}\n\t\t\t};\n\t\t\tyield block;\n\t\t} else if (_isAnthropicSearchResultBlock(contentPart)) {\n\t\t\tconst block = {\n\t\t\t\ttype: \"search_result\",\n\t\t\t\ttitle: contentPart.title,\n\t\t\t\tsource: contentPart.source,\n\t\t\t\t...\"cache_control\" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {},\n\t\t\t\t...\"citations\" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {},\n\t\t\t\tcontent: contentPart.content\n\t\t\t};\n\t\t\tyield block;\n\t\t} else if (textTypes.find((t) => t === contentPart.type) && \"text\" in contentPart) yield {\n\t\t\ttype: \"text\",\n\t\t\ttext: contentPart.text,\n\t\t\t...cacheControl ? { cache_control: cacheControl } : {},\n\t\t\t...\"citations\" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}\n\t\t};\n\t\telse if (toolTypes.find((t) => t === contentPart.type)) {\n\t\t\tconst contentPartCopy = { ...contentPart };\n\t\t\tif (\"index\" in contentPartCopy) delete contentPartCopy.index;\n\t\t\tif (contentPartCopy.type === \"input_json_delta\") contentPartCopy.type = \"tool_use\";\n\t\t\tif (\"input\" in contentPartCopy) {\n\t\t\t\tif (typeof contentPartCopy.input === \"string\") try {\n\t\t\t\t\tcontentPartCopy.input = JSON.parse(contentPartCopy.input);\n\t\t\t\t} catch {\n\t\t\t\t\tcontentPartCopy.input = {};\n\t\t\t\t}\n\t\t\t}\n\t\t\tyield {\n\t\t\t\t...contentPartCopy,\n\t\t\t\t...cacheControl ? { cache_control: cacheControl } : {}\n\t\t\t};\n\t\t} else if (contentPart.type === \"container_upload\") yield {\n\t\t\t...contentPart,\n\t\t\t...cacheControl ? { cache_control: cacheControl } : {}\n\t\t};\n\t}\n}\nfunction _formatContent(message) {\n\tconst { content } = message;\n\tif (typeof content === \"string\") return content;\n\telse return Array.from(_formatContentBlocks(content));\n}\n/**\n* Formats messages as a prompt for the model.\n* Used in LangSmith, export is important here.\n* @param messages The base messages to format as a prompt.\n* @returns The formatted prompt.\n*/\nfunction _convertMessagesToAnthropicPayload(messages) {\n\tconst mergedMessages = _ensureMessageContents(messages);\n\tlet system;\n\tif (mergedMessages.length > 0 && mergedMessages[0]._getType() === \"system\") system = messages[0].content;\n\tconst conversationMessages = system !== void 0 ? mergedMessages.slice(1) : mergedMessages;\n\tconst formattedMessages = conversationMessages.map((message) => {\n\t\tlet role;\n\t\tif (message._getType() === \"human\") role = \"user\";\n\t\telse if (message._getType() === \"ai\") role = \"assistant\";\n\t\telse if (message._getType() === \"tool\") role = \"user\";\n\t\telse if (message._getType() === \"system\") throw new Error(\"System messages are only permitted as the first passed message.\");\n\t\telse throw new Error(`Message type \"${message.type}\" is not supported.`);\n\t\tif (isAIMessage(message) && message.response_metadata?.output_version === \"v1\") return {\n\t\t\trole,\n\t\t\tcontent: _formatStandardContent(message)\n\t\t};\n\t\tif (isAIMessage(message) && !!message.tool_calls?.length) if (typeof message.content === \"string\") if (message.content === \"\") return {\n\t\t\trole,\n\t\t\tcontent: message.tool_calls.map(_convertLangChainToolCallToAnthropic)\n\t\t};\n\t\telse return {\n\t\t\trole,\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: message.content\n\t\t\t}, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)]\n\t\t};\n\t\telse {\n\t\t\tconst { content } = message;\n\t\t\tconst hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find((contentPart) => (contentPart.type === \"tool_use\" || contentPart.type === \"input_json_delta\" || contentPart.type === \"server_tool_use\") && contentPart.id === toolCall.id));\n\t\t\tif (hasMismatchedToolCalls) console.warn(`The \"tool_calls\" field on a message is only respected if content is a string.`);\n\t\t\treturn {\n\t\t\t\trole,\n\t\t\t\tcontent: _formatContent(message)\n\t\t\t};\n\t\t}\n\t\telse return {\n\t\t\trole,\n\t\t\tcontent: _formatContent(message)\n\t\t};\n\t});\n\treturn {\n\t\tmessages: mergeMessages(formattedMessages),\n\t\tsystem\n\t};\n}\nfunction mergeMessages(messages) {\n\tif (!messages || messages.length <= 1) return messages;\n\tconst result = [];\n\tlet currentMessage = messages[0];\n\tconst normalizeContent = (content) => {\n\t\tif (typeof content === \"string\") return [{\n\t\t\ttype: \"text\",\n\t\t\ttext: content\n\t\t}];\n\t\treturn content;\n\t};\n\tconst isToolResultMessage = (msg) => {\n\t\tif (msg.role !== \"user\") return false;\n\t\tif (typeof msg.content === \"string\") return false;\n\t\treturn Array.isArray(msg.content) && msg.content.every((item) => item.type === \"tool_result\");\n\t};\n\tfor (let i = 1; i < messages.length; i += 1) {\n\t\tconst nextMessage = messages[i];\n\t\tif (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) currentMessage = {\n\t\t\t...currentMessage,\n\t\t\tcontent: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)]\n\t\t};\n\t\telse {\n\t\t\tresult.push(currentMessage);\n\t\t\tcurrentMessage = nextMessage;\n\t\t}\n\t}\n\tresult.push(currentMessage);\n\treturn result;\n}\n\n//#endregion\nexport { _convertMessagesToAnthropicPayload };\n//# sourceMappingURL=message_inputs.js.map","import { extractToolCalls } from \"../output_parsers.js\";\nimport { AIMessage, AIMessageChunk } from \"@langchain/core/messages\";\n\n//#region src/utils/message_outputs.ts\nfunction _makeMessageChunkFromAnthropicEvent(data, fields) {\n\tconst response_metadata = { model_provider: \"anthropic\" };\n\tif (data.type === \"message_start\") {\n\t\tconst { content, usage,...additionalKwargs } = data.message;\n\t\tconst filteredAdditionalKwargs = {};\n\t\tfor (const [key, value] of Object.entries(additionalKwargs)) if (value !== void 0 && value !== null) filteredAdditionalKwargs[key] = value;\n\t\tconst { input_tokens, output_tokens,...rest } = usage ?? {};\n\t\tconst usageMetadata = {\n\t\t\tinput_tokens,\n\t\t\toutput_tokens,\n\t\t\ttotal_tokens: input_tokens + output_tokens,\n\t\t\tinput_token_details: {\n\t\t\t\tcache_creation: rest.cache_creation_input_tokens,\n\t\t\t\tcache_read: rest.cache_read_input_tokens\n\t\t\t}\n\t\t};\n\t\treturn { chunk: new AIMessageChunk({\n\t\t\tcontent: fields.coerceContentToString ? \"\" : [],\n\t\t\tadditional_kwargs: filteredAdditionalKwargs,\n\t\t\tusage_metadata: fields.streamUsage ? usageMetadata : void 0,\n\t\t\tresponse_metadata: {\n\t\t\t\t...response_metadata,\n\t\t\t\tusage: { ...rest }\n\t\t\t},\n\t\t\tid: data.message.id\n\t\t}) };\n\t} else if (data.type === \"message_delta\") {\n\t\tconst usageMetadata = {\n\t\t\tinput_tokens: 0,\n\t\t\toutput_tokens: data.usage.output_tokens,\n\t\t\ttotal_tokens: data.usage.output_tokens,\n\t\t\tinput_token_details: {\n\t\t\t\tcache_creation: data.usage.cache_creation_input_tokens,\n\t\t\t\tcache_read: data.usage.cache_read_input_tokens\n\t\t\t}\n\t\t};\n\t\tconst responseMetadata = \"context_management\" in data.delta ? { context_management: data.delta.context_management } : void 0;\n\t\treturn { chunk: new AIMessageChunk({\n\t\t\tcontent: fields.coerceContentToString ? \"\" : [],\n\t\t\tresponse_metadata: responseMetadata,\n\t\t\tadditional_kwargs: { ...data.delta },\n\t\t\tusage_metadata: fields.streamUsage ? usageMetadata : void 0\n\t\t}) };\n\t} else if (data.type === \"content_block_start\" && [\n\t\t\"tool_use\",\n\t\t\"document\",\n\t\t\"server_tool_use\",\n\t\t\"web_search_tool_result\"\n\t].includes(data.content_block.type)) {\n\t\tconst contentBlock = data.content_block;\n\t\tlet toolCallChunks;\n\t\tif (contentBlock.type === \"tool_use\") toolCallChunks = [{\n\t\t\tid: contentBlock.id,\n\t\t\tindex: data.index,\n\t\t\tname: contentBlock.name,\n\t\t\targs: \"\"\n\t\t}];\n\t\telse toolCallChunks = [];\n\t\treturn { chunk: new AIMessageChunk({\n\t\t\tcontent: fields.coerceContentToString ? \"\" : [{\n\t\t\t\tindex: data.index,\n\t\t\t\t...data.content_block,\n\t\t\t\tinput: contentBlock.type === \"server_tool_use\" || contentBlock.type === \"tool_use\" ? \"\" : void 0\n\t\t\t}],\n\t\t\tresponse_metadata,\n\t\t\tadditional_kwargs: {},\n\t\t\ttool_call_chunks: toolCallChunks\n\t\t}) };\n\t} else if (data.type === \"content_block_delta\" && [\n\t\t\"text_delta\",\n\t\t\"citations_delta\",\n\t\t\"thinking_delta\",\n\t\t\"signature_delta\"\n\t].includes(data.delta.type)) if (fields.coerceContentToString && \"text\" in data.delta) return { chunk: new AIMessageChunk({ content: data.delta.text }) };\n\telse {\n\t\tconst contentBlock = data.delta;\n\t\tif (\"citation\" in contentBlock) {\n\t\t\tcontentBlock.citations = [contentBlock.citation];\n\t\t\tdelete contentBlock.citation;\n\t\t}\n\t\tif (contentBlock.type === \"thinking_delta\" || contentBlock.type === \"signature_delta\") return { chunk: new AIMessageChunk({\n\t\t\tcontent: [{\n\t\t\t\tindex: data.index,\n\t\t\t\t...contentBlock,\n\t\t\t\ttype: \"thinking\"\n\t\t\t}],\n\t\t\tresponse_metadata\n\t\t}) };\n\t\treturn { chunk: new AIMessageChunk({\n\t\t\tcontent: [{\n\t\t\t\tindex: data.index,\n\t\t\t\t...contentBlock,\n\t\t\t\ttype: \"text\"\n\t\t\t}],\n\t\t\tresponse_metadata\n\t\t}) };\n\t}\n\telse if (data.type === \"content_block_delta\" && data.delta.type === \"input_json_delta\") return { chunk: new AIMessageChunk({\n\t\tcontent: fields.coerceContentToString ? \"\" : [{\n\t\t\tindex: data.index,\n\t\t\tinput: data.delta.partial_json,\n\t\t\ttype: data.delta.type\n\t\t}],\n\t\tresponse_metadata,\n\t\tadditional_kwargs: {},\n\t\ttool_call_chunks: [{\n\t\t\tindex: data.index,\n\t\t\targs: data.delta.partial_json\n\t\t}]\n\t}) };\n\telse if (data.type === \"content_block_start\" && data.content_block.type === \"text\") {\n\t\tconst content = data.content_block?.text;\n\t\tif (content !== void 0) return { chunk: new AIMessageChunk({\n\t\t\tcontent: fields.coerceContentToString ? content : [{\n\t\t\t\tindex: data.index,\n\t\t\t\t...data.content_block\n\t\t\t}],\n\t\t\tresponse_metadata,\n\t\t\tadditional_kwargs: {}\n\t\t}) };\n\t} else if (data.type === \"content_block_start\" && data.content_block.type === \"redacted_thinking\") return { chunk: new AIMessageChunk({\n\t\tcontent: fields.coerceContentToString ? \"\" : [{\n\t\t\tindex: data.index,\n\t\t\t...data.content_block\n\t\t}],\n\t\tresponse_metadata\n\t}) };\n\telse if (data.type === \"content_block_start\" && data.content_block.type === \"thinking\") {\n\t\tconst content = data.content_block.thinking;\n\t\treturn { chunk: new AIMessageChunk({\n\t\t\tcontent: fields.coerceContentToString ? content : [{\n\t\t\t\tindex: data.index,\n\t\t\t\t...data.content_block\n\t\t\t}],\n\t\t\tresponse_metadata\n\t\t}) };\n\t}\n\treturn null;\n}\nfunction anthropicResponseToChatMessages(messages, additionalKwargs) {\n\tconst response_metadata = {\n\t\t...additionalKwargs,\n\t\tmodel_provider: \"anthropic\"\n\t};\n\tconst usage = additionalKwargs.usage;\n\tconst usageMetadata = usage != null ? {\n\t\tinput_tokens: usage.input_tokens ?? 0,\n\t\toutput_tokens: usage.output_tokens ?? 0,\n\t\ttotal_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),\n\t\tinput_token_details: {\n\t\t\tcache_creation: usage.cache_creation_input_tokens,\n\t\t\tcache_read: usage.cache_read_input_tokens\n\t\t}\n\t} : void 0;\n\tif (messages.length === 1 && messages[0].type === \"text\") return [{\n\t\ttext: messages[0].text,\n\t\tmessage: new AIMessage({\n\t\t\tcontent: messages[0].text,\n\t\t\tadditional_kwargs: additionalKwargs,\n\t\t\tusage_metadata: usageMetadata,\n\t\t\tresponse_metadata,\n\t\t\tid: additionalKwargs.id\n\t\t})\n\t}];\n\telse {\n\t\tconst toolCalls = extractToolCalls(messages);\n\t\tconst generations = [{\n\t\t\ttext: \"\",\n\t\t\tmessage: new AIMessage({\n\t\t\t\tcontent: messages,\n\t\t\t\tadditional_kwargs: additionalKwargs,\n\t\t\t\ttool_calls: toolCalls,\n\t\t\t\tusage_metadata: usageMetadata,\n\t\t\t\tresponse_metadata,\n\t\t\t\tid: additionalKwargs.id\n\t\t\t})\n\t\t}];\n\t\treturn generations;\n\t}\n}\n\n//#endregion\nexport { _makeMessageChunkFromAnthropicEvent, anthropicResponseToChatMessages };\n//# sourceMappingURL=message_outputs.js.map","//#region src/utils/errors.ts\nfunction addLangChainErrorFields(error, lc_error_code) {\n\terror.lc_error_code = lc_error_code;\n\terror.message = `${error.message}\\n\\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\\n`;\n\treturn error;\n}\nfunction wrapAnthropicClientError(e) {\n\tlet error;\n\tif (e.status === 400 && e.message.includes(\"tool\")) error = addLangChainErrorFields(e, \"INVALID_TOOL_RESULTS\");\n\telse if (e.status === 401) error = addLangChainErrorFields(e, \"MODEL_AUTHENTICATION\");\n\telse if (e.status === 404) error = addLangChainErrorFields(e, \"MODEL_NOT_FOUND\");\n\telse if (e.status === 429) error = addLangChainErrorFields(e, \"MODEL_RATE_LIMIT\");\n\telse error = e;\n\treturn error;\n}\n\n//#endregion\nexport { wrapAnthropicClientError };\n//# sourceMappingURL=errors.js.map","function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\")\n throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f)\n throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver))\n throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return kind === \"a\" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value;\n}\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f)\n throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver))\n throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\nexport { __classPrivateFieldSet, __classPrivateFieldGet };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n/**\n * https://stackoverflow.com/a/2117523\n */\nexport let uuid4 = function () {\n const { crypto } = globalThis;\n if (crypto?.randomUUID) {\n uuid4 = crypto.randomUUID.bind(crypto);\n return crypto.randomUUID();\n }\n const u8 = new Uint8Array(1);\n const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;\n return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));\n};\n//# sourceMappingURL=uuid.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport function isAbortError(err) {\n return (typeof err === 'object' &&\n err !== null &&\n // Spec-compliant fetch implementations\n (('name' in err && err.name === 'AbortError') ||\n // Expo fetch\n ('message' in err && String(err.message).includes('FetchRequestCanceledException'))));\n}\nexport const castToError = (err) => {\n if (err instanceof Error)\n return err;\n if (typeof err === 'object' && err !== null) {\n try {\n if (Object.prototype.toString.call(err) === '[object Error]') {\n // @ts-ignore - not all envs have native support for cause yet\n const error = new Error(err.message, err.cause ? { cause: err.cause } : {});\n if (err.stack)\n error.stack = err.stack;\n // @ts-ignore - not all envs have native support for cause yet\n if (err.cause && !error.cause)\n error.cause = err.cause;\n if (err.name)\n error.name = err.name;\n return error;\n }\n }\n catch { }\n try {\n return new Error(JSON.stringify(err));\n }\n catch { }\n }\n return new Error(err);\n};\n//# sourceMappingURL=errors.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { castToError } from \"../internal/errors.mjs\";\nexport class AnthropicError extends Error {\n}\nexport class APIError extends AnthropicError {\n constructor(status, error, message, headers) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.requestID = headers?.get('request-id');\n this.error = error;\n }\n static makeMessage(status, error, message) {\n const msg = error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n static generate(status, errorResponse, message, headers) {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n const error = errorResponse;\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n return new APIError(status, error, message, headers);\n }\n}\nexport class APIUserAbortError extends APIError {\n constructor({ message } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\nexport class APIConnectionError extends APIError {\n constructor({ message, cause }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause)\n this.cause = cause;\n }\n}\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\nexport class BadRequestError extends APIError {\n}\nexport class AuthenticationError extends APIError {\n}\nexport class PermissionDeniedError extends APIError {\n}\nexport class NotFoundError extends APIError {\n}\nexport class ConflictError extends APIError {\n}\nexport class UnprocessableEntityError extends APIError {\n}\nexport class RateLimitError extends APIError {\n}\nexport class InternalServerError extends APIError {\n}\n//# sourceMappingURL=error.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { AnthropicError } from \"../../core/error.mjs\";\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nexport const isAbsoluteURL = (url) => {\n return startsWithSchemeRegexp.test(url);\n};\nexport let isArray = (val) => ((isArray = Array.isArray), isArray(val));\nexport let isReadonlyArray = isArray;\n/** Returns an object if the given value isn't an object, otherwise returns as-is */\nexport function maybeObj(x) {\n if (typeof x !== 'object') {\n return {};\n }\n return x ?? {};\n}\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nexport function isObj(obj) {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\nexport const ensurePresent = (value) => {\n if (value == null) {\n throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);\n }\n return value;\n};\nexport const validatePositiveInteger = (name, n) => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new AnthropicError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new AnthropicError(`${name} must be a positive integer`);\n }\n return n;\n};\nexport const coerceInteger = (value) => {\n if (typeof value === 'number')\n return Math.round(value);\n if (typeof value === 'string')\n return parseInt(value, 10);\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceFloat = (value) => {\n if (typeof value === 'number')\n return value;\n if (typeof value === 'string')\n return parseFloat(value);\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceBoolean = (value) => {\n if (typeof value === 'boolean')\n return value;\n if (typeof value === 'string')\n return value === 'true';\n return Boolean(value);\n};\nexport const maybeCoerceInteger = (value) => {\n if (value == null) {\n return undefined;\n }\n return coerceInteger(value);\n};\nexport const maybeCoerceFloat = (value) => {\n if (value == null) {\n return undefined;\n }\n return coerceFloat(value);\n};\nexport const maybeCoerceBoolean = (value) => {\n if (value == null) {\n return undefined;\n }\n return coerceBoolean(value);\n};\nexport const safeJSON = (text) => {\n try {\n return JSON.parse(text);\n }\n catch (err) {\n return undefined;\n }\n};\n//# sourceMappingURL=values.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n//# sourceMappingURL=sleep.mjs.map","export const VERSION = '0.65.0'; // x-release-please-version\n//# sourceMappingURL=version.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { VERSION } from \"../version.mjs\";\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined');\n};\n/**\n * Note this does not detect 'browser'; for that, use getBrowserInfo().\n */\nfunction getDetectedPlatform() {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return 'deno';\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return 'edge';\n }\n if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {\n return 'node';\n }\n return 'unknown';\n}\nconst getPlatformProperties = () => {\n const detectedPlatform = getDetectedPlatform();\n if (detectedPlatform === 'deno') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': globalThis.process.version,\n };\n }\n // Check if Node.js\n if (detectedPlatform === 'node') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'),\n 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown',\n };\n }\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo() {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge', pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome', pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox', pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari', pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n return null;\n}\nconst normalizeArch = (arch) => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32')\n return 'x32';\n if (arch === 'x86_64' || arch === 'x64')\n return 'x64';\n if (arch === 'arm')\n return 'arm';\n if (arch === 'aarch64' || arch === 'arm64')\n return 'arm64';\n if (arch)\n return `other:${arch}`;\n return 'unknown';\n};\nconst normalizePlatform = (platform) => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n platform = platform.toLowerCase();\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios'))\n return 'iOS';\n if (platform === 'android')\n return 'Android';\n if (platform === 'darwin')\n return 'MacOS';\n if (platform === 'win32')\n return 'Windows';\n if (platform === 'freebsd')\n return 'FreeBSD';\n if (platform === 'openbsd')\n return 'OpenBSD';\n if (platform === 'linux')\n return 'Linux';\n if (platform)\n return `Other:${platform}`;\n return 'Unknown';\n};\nlet _platformHeaders;\nexport const getPlatformHeaders = () => {\n return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));\n};\n//# sourceMappingURL=detect-platform.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport function getDefaultFetch() {\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');\n}\nexport function makeReadableStream(...args) {\n const ReadableStream = globalThis.ReadableStream;\n if (typeof ReadableStream === 'undefined') {\n // Note: All of the platforms / runtimes we officially support already define\n // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.\n throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');\n }\n return new ReadableStream(...args);\n}\nexport function ReadableStreamFrom(iterable) {\n let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();\n return makeReadableStream({\n start() { },\n async pull(controller) {\n const { done, value } = await iter.next();\n if (done) {\n controller.close();\n }\n else {\n controller.enqueue(value);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n}\n/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable(stream) {\n if (stream[Symbol.asyncIterator])\n return stream;\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done)\n reader.releaseLock(); // release lock when stream becomes closed\n return result;\n }\n catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n/**\n * Cancels a ReadableStream we don't need to consume.\n * See https://undici.nodejs.org/#/?id=garbage-collection\n */\nexport async function CancelReadableStream(stream) {\n if (stream === null || typeof stream !== 'object')\n return;\n if (stream[Symbol.asyncIterator]) {\n await stream[Symbol.asyncIterator]().return?.();\n return;\n }\n const reader = stream.getReader();\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n}\n//# sourceMappingURL=shims.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport const FallbackEncoder = ({ headers, body }) => {\n return {\n bodyHeaders: {\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n };\n};\n//# sourceMappingURL=request-options.mjs.map","export function concatBytes(buffers) {\n let length = 0;\n for (const buffer of buffers) {\n length += buffer.length;\n }\n const output = new Uint8Array(length);\n let index = 0;\n for (const buffer of buffers) {\n output.set(buffer, index);\n index += buffer.length;\n }\n return output;\n}\nlet encodeUTF8_;\nexport function encodeUTF8(str) {\n let encoder;\n return (encodeUTF8_ ??\n ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);\n}\nlet decodeUTF8_;\nexport function decodeUTF8(bytes) {\n let decoder;\n return (decodeUTF8_ ??\n ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);\n}\n//# sourceMappingURL=bytes.mjs.map","var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../tslib.mjs\";\nimport { concatBytes, decodeUTF8, encodeUTF8 } from \"../utils/bytes.mjs\";\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n constructor() {\n _LineDecoder_buffer.set(this, void 0);\n _LineDecoder_carriageReturnIndex.set(this, void 0);\n __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), \"f\");\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n }\n decode(chunk) {\n if (chunk == null) {\n return [];\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? encodeUTF8(chunk)\n : chunk;\n __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\"), binaryChunk]), \"f\");\n const lines = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\"))) != null) {\n if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, \"f\");\n continue;\n }\n // we got double \\r or \\rtext\\n\n if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") != null &&\n (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") + 1 || patternIndex.carriage)) {\n lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") - 1)));\n __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\")), \"f\");\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n continue;\n }\n const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(0, endIndex));\n lines.push(line);\n __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(patternIndex.index), \"f\");\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n }\n return lines;\n }\n flush() {\n if (!__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap();\n// prettier-ignore\nLineDecoder.NEWLINE_CHARS = new Set(['\\n', '\\r']);\nLineDecoder.NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(buffer, startIndex) {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n return null;\n}\nexport function findDoubleNewlineIndex(buffer) {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = 0; i < buffer.length - 1; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n return -1;\n}\n//# sourceMappingURL=line.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { hasOwn } from \"./values.mjs\";\nconst levelNumbers = {\n off: 0,\n error: 200,\n warn: 300,\n info: 400,\n debug: 500,\n};\nexport const parseLogLevel = (maybeLevel, sourceName, client) => {\n if (!maybeLevel) {\n return undefined;\n }\n if (hasOwn(levelNumbers, maybeLevel)) {\n return maybeLevel;\n }\n loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);\n return undefined;\n};\nfunction noop() { }\nfunction makeLogFn(fnLevel, logger, logLevel) {\n if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {\n return noop;\n }\n else {\n // Don't wrap logger functions, we want the stacktrace intact!\n return logger[fnLevel].bind(logger);\n }\n}\nconst noopLogger = {\n error: noop,\n warn: noop,\n info: noop,\n debug: noop,\n};\nlet cachedLoggers = /* @__PURE__ */ new WeakMap();\nexport function loggerFor(client) {\n const logger = client.logger;\n const logLevel = client.logLevel ?? 'off';\n if (!logger) {\n return noopLogger;\n }\n const cachedLogger = cachedLoggers.get(logger);\n if (cachedLogger && cachedLogger[0] === logLevel) {\n return cachedLogger[1];\n }\n const levelLogger = {\n error: makeLogFn('error', logger, logLevel),\n warn: makeLogFn('warn', logger, logLevel),\n info: makeLogFn('info', logger, logLevel),\n debug: makeLogFn('debug', logger, logLevel),\n };\n cachedLoggers.set(logger, [logLevel, levelLogger]);\n return levelLogger;\n}\nexport const formatRequestDetails = (details) => {\n if (details.options) {\n details.options = { ...details.options };\n delete details.options['headers']; // redundant + leaks internals\n }\n if (details.headers) {\n details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [\n name,\n (name.toLowerCase() === 'x-api-key' ||\n name.toLowerCase() === 'authorization' ||\n name.toLowerCase() === 'cookie' ||\n name.toLowerCase() === 'set-cookie') ?\n '***'\n : value,\n ]));\n }\n if ('retryOfRequestLogID' in details) {\n if (details.retryOfRequestLogID) {\n details.retryOf = details.retryOfRequestLogID;\n }\n delete details.retryOfRequestLogID;\n }\n return details;\n};\n//# sourceMappingURL=log.mjs.map","var _Stream_client;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { AnthropicError } from \"./error.mjs\";\nimport { makeReadableStream } from \"../internal/shims.mjs\";\nimport { findDoubleNewlineIndex, LineDecoder } from \"../internal/decoders/line.mjs\";\nimport { ReadableStreamToAsyncIterable } from \"../internal/shims.mjs\";\nimport { isAbortError } from \"../internal/errors.mjs\";\nimport { safeJSON } from \"../internal/utils/values.mjs\";\nimport { encodeUTF8 } from \"../internal/utils/bytes.mjs\";\nimport { loggerFor } from \"../internal/utils/log.mjs\";\nimport { APIError } from \"./error.mjs\";\nexport class Stream {\n constructor(iterator, controller, client) {\n this.iterator = iterator;\n _Stream_client.set(this, void 0);\n this.controller = controller;\n __classPrivateFieldSet(this, _Stream_client, client, \"f\");\n }\n static fromSSEResponse(response, controller, client) {\n let consumed = false;\n const logger = client ? loggerFor(client) : console;\n async function* iterator() {\n if (consumed) {\n throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (sse.event === 'completion') {\n try {\n yield JSON.parse(sse.data);\n }\n catch (e) {\n logger.error(`Could not parse message into JSON:`, sse.data);\n logger.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n if (sse.event === 'message_start' ||\n sse.event === 'message_delta' ||\n sse.event === 'message_stop' ||\n sse.event === 'content_block_start' ||\n sse.event === 'content_block_delta' ||\n sse.event === 'content_block_stop') {\n try {\n yield JSON.parse(sse.data);\n }\n catch (e) {\n logger.error(`Could not parse message into JSON:`, sse.data);\n logger.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n if (sse.event === 'ping') {\n continue;\n }\n if (sse.event === 'error') {\n throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);\n }\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (isAbortError(e))\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller, client);\n }\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream(readableStream, controller, client) {\n let consumed = false;\n async function* iterLines() {\n const lineDecoder = new LineDecoder();\n const iter = ReadableStreamToAsyncIterable(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n async function* iterator() {\n if (consumed) {\n throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done)\n continue;\n if (line)\n yield JSON.parse(line);\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (isAbortError(e))\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller, client);\n }\n [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {\n return this.iterator();\n }\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee() {\n const left = [];\n const right = [];\n const iterator = this.iterator();\n const teeIterator = (queue) => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift();\n },\n };\n };\n return [\n new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, \"f\")),\n new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, \"f\")),\n ];\n }\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream() {\n const self = this;\n let iter;\n return makeReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl) {\n try {\n const { value, done } = await iter.next();\n if (done)\n return ctrl.close();\n const bytes = encodeUTF8(JSON.stringify(value) + '\\n');\n ctrl.enqueue(bytes);\n }\n catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\nexport async function* _iterSSEMessages(response, controller) {\n if (!response.body) {\n controller.abort();\n if (typeof globalThis.navigator !== 'undefined' &&\n globalThis.navigator.product === 'ReactNative') {\n throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);\n }\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n const iter = ReadableStreamToAsyncIterable(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n }\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n}\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator) {\n let data = new Uint8Array();\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? encodeUTF8(chunk)\n : chunk;\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n if (data.length > 0) {\n yield data;\n }\n}\nclass SSEDecoder {\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n decode(line) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length)\n return null;\n const sse = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n this.event = null;\n this.data = [];\n this.chunks = [];\n return sse;\n }\n this.chunks.push(line);\n if (line.startsWith(':')) {\n return null;\n }\n let [fieldname, _, value] = partition(line, ':');\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n if (fieldname === 'event') {\n this.event = value;\n }\n else if (fieldname === 'data') {\n this.data.push(value);\n }\n return null;\n }\n}\nfunction partition(str, delimiter) {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n return [str, '', ''];\n}\n//# sourceMappingURL=streaming.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { Stream } from \"../core/streaming.mjs\";\nimport { formatRequestDetails, loggerFor } from \"./utils/log.mjs\";\nexport async function defaultParseResponse(client, props) {\n const { response, requestLogID, retryOfRequestLogID, startTime } = props;\n const body = await (async () => {\n if (props.options.stream) {\n loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream`\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller);\n }\n return Stream.fromSSEResponse(response, props.controller);\n }\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null;\n }\n if (props.options.__binaryResponse) {\n return response;\n }\n const contentType = response.headers.get('content-type');\n const mediaType = contentType?.split(';')[0]?.trim();\n const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');\n if (isJSON) {\n const json = await response.json();\n return addRequestID(json, response);\n }\n const text = await response.text();\n return text;\n })();\n loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n body,\n durationMs: Date.now() - startTime,\n }));\n return body;\n}\nexport function addRequestID(value, response) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('request-id'),\n enumerable: false,\n });\n}\n//# sourceMappingURL=parse.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _APIPromise_client;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { defaultParseResponse, addRequestID, } from \"../internal/parse.mjs\";\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise extends Promise {\n constructor(client, responsePromise, parseResponse = defaultParseResponse) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null);\n });\n this.responsePromise = responsePromise;\n this.parseResponse = parseResponse;\n _APIPromise_client.set(this, void 0);\n __classPrivateFieldSet(this, _APIPromise_client, client, \"f\");\n }\n _thenUnwrap(transform) {\n return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, \"f\"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));\n }\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n * to your `tsconfig.json`.\n */\n asResponse() {\n return this.responsePromise.then((p) => p.response);\n }\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned via the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n * to your `tsconfig.json`.\n */\n async withResponse() {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('request-id') };\n }\n parse() {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, \"f\"), data));\n }\n return this.parsedPromise;\n }\n then(onfulfilled, onrejected) {\n return this.parse().then(onfulfilled, onrejected);\n }\n catch(onrejected) {\n return this.parse().catch(onrejected);\n }\n finally(onfinally) {\n return this.parse().finally(onfinally);\n }\n}\n_APIPromise_client = new WeakMap();\n//# sourceMappingURL=api-promise.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _AbstractPage_client;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { AnthropicError } from \"./error.mjs\";\nimport { defaultParseResponse } from \"../internal/parse.mjs\";\nimport { APIPromise } from \"./api-promise.mjs\";\nimport { maybeObj } from \"../internal/utils/values.mjs\";\nexport class AbstractPage {\n constructor(client, response, body, options) {\n _AbstractPage_client.set(this, void 0);\n __classPrivateFieldSet(this, _AbstractPage_client, client, \"f\");\n this.options = options;\n this.response = response;\n this.body = body;\n }\n hasNextPage() {\n const items = this.getPaginatedItems();\n if (!items.length)\n return false;\n return this.nextPageRequestOptions() != null;\n }\n async getNextPage() {\n const nextOptions = this.nextPageRequestOptions();\n if (!nextOptions) {\n throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');\n }\n return await __classPrivateFieldGet(this, _AbstractPage_client, \"f\").requestAPIList(this.constructor, nextOptions);\n }\n async *iterPages() {\n let page = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise extends APIPromise {\n constructor(client, request, Page) {\n super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));\n }\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator]() {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\nexport class Page extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n this.first_id = body.first_id || null;\n this.last_id = body.last_id || null;\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n hasNextPage() {\n if (this.has_more === false) {\n return false;\n }\n return super.hasNextPage();\n }\n nextPageRequestOptions() {\n if (this.options.query?.['before_id']) {\n // in reverse\n const first_id = this.first_id;\n if (!first_id) {\n return null;\n }\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n before_id: first_id,\n },\n };\n }\n const cursor = this.last_id;\n if (!cursor) {\n return null;\n }\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n after_id: cursor,\n },\n };\n }\n}\n//# sourceMappingURL=pagination.mjs.map","import { ReadableStreamFrom } from \"./shims.mjs\";\nexport const checkFileSupport = () => {\n if (typeof File === 'undefined') {\n const { process } = globalThis;\n const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20;\n throw new Error('`File` is not defined as a global, which is required for file uploads.' +\n (isOldNode ?\n \" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.\"\n : ''));\n }\n};\n/**\n * Construct a `File` instance. This is used to ensure a helpful error is thrown\n * for environments that don't define a global `File` yet.\n */\nexport function makeFile(fileBits, fileName, options) {\n checkFileSupport();\n return new File(fileBits, fileName ?? 'unknown_file', options);\n}\nexport function getName(value) {\n return (((typeof value === 'object' &&\n value !== null &&\n (('name' in value && value.name && String(value.name)) ||\n ('url' in value && value.url && String(value.url)) ||\n ('filename' in value && value.filename && String(value.filename)) ||\n ('path' in value && value.path && String(value.path)))) ||\n '')\n .split(/[\\\\/]/)\n .pop() || undefined);\n}\nexport const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async (opts, fetch) => {\n if (!hasUploadableValue(opts.body))\n return opts;\n return { ...opts, body: await createForm(opts.body, fetch) };\n};\nexport const multipartFormRequestOptions = async (opts, fetch) => {\n return { ...opts, body: await createForm(opts.body, fetch) };\n};\nconst supportsFormDataMap = /* @__PURE__ */ new WeakMap();\n/**\n * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending\n * properly-encoded form data, it just stringifies the object, resulting in a request body of \"[object FormData]\".\n * This function detects if the fetch function provided supports the global FormData object to avoid\n * confusing error messages later on.\n */\nfunction supportsFormData(fetchObject) {\n const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch;\n const cached = supportsFormDataMap.get(fetch);\n if (cached)\n return cached;\n const promise = (async () => {\n try {\n const FetchResponse = ('Response' in fetch ?\n fetch.Response\n : (await fetch('data:,')).constructor);\n const data = new FormData();\n if (data.toString() === (await new FetchResponse(data).text())) {\n return false;\n }\n return true;\n }\n catch {\n // avoid false negatives\n return true;\n }\n })();\n supportsFormDataMap.set(fetch, promise);\n return promise;\n}\nexport const createForm = async (body, fetch) => {\n if (!(await supportsFormData(fetch))) {\n throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.');\n }\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\n// We check for Blob not File because Bun.File doesn't inherit from File,\n// but they both inherit from Blob and have a `name` property at runtime.\nconst isNamedBlob = (value) => value instanceof Blob && 'name' in value;\nconst isUploadable = (value) => typeof value === 'object' &&\n value !== null &&\n (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value));\nconst hasUploadableValue = (value) => {\n if (isUploadable(value))\n return true;\n if (Array.isArray(value))\n return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue(value[k]))\n return true;\n }\n }\n return false;\n};\nconst addFormValue = async (form, key, value) => {\n if (value === undefined)\n return;\n if (value == null) {\n throw new TypeError(`Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`);\n }\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n }\n else if (value instanceof Response) {\n let options = {};\n const contentType = value.headers.get('Content-Type');\n if (contentType) {\n options = { type: contentType };\n }\n form.append(key, makeFile([await value.blob()], getName(value), options));\n }\n else if (isAsyncIterable(value)) {\n form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value)));\n }\n else if (isNamedBlob(value)) {\n form.append(key, makeFile([value], getName(value), { type: value.type }));\n }\n else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n }\n else if (typeof value === 'object') {\n await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));\n }\n else {\n throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);\n }\n};\n//# sourceMappingURL=uploads.mjs.map","import { getName, makeFile, isAsyncIterable } from \"./uploads.mjs\";\nimport { checkFileSupport } from \"./uploads.mjs\";\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isBlobLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isFileLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\nconst isResponseLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(value, name, options) {\n checkFileSupport();\n // If it's a promise, resolve it.\n value = await value;\n name || (name = getName(value));\n // If we've been given a `File` we don't need to do anything if the name / options\n // have not been customised.\n if (isFileLike(value)) {\n if (value instanceof File && name == null && options == null) {\n return value;\n }\n return makeFile([await value.arrayBuffer()], name ?? value.name, {\n type: value.type,\n lastModified: value.lastModified,\n ...options,\n });\n }\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name || (name = new URL(value.url).pathname.split(/[\\\\/]/).pop());\n return makeFile(await getBytes(blob), name, options);\n }\n const parts = await getBytes(value);\n if (!options?.type) {\n const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n return makeFile(parts, name, options);\n}\nasync function getBytes(value) {\n let parts = [];\n if (typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer) {\n parts.push(value);\n }\n else if (isBlobLike(value)) {\n parts.push(value instanceof Blob ? value : await value.arrayBuffer());\n }\n else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(...(await getBytes(chunk))); // TODO, consider validating?\n }\n }\n else {\n const constructor = value?.constructor?.name;\n throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);\n }\n return parts;\n}\nfunction propsForError(value) {\n if (typeof value !== 'object' || value === null)\n return '';\n const props = Object.getOwnPropertyNames(value);\n return `; props: [${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n//# sourceMappingURL=to-file.mjs.map","export { toFile } from \"../internal/to-file.mjs\";\n//# sourceMappingURL=uploads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport class APIResource {\n constructor(client) {\n this._client = client;\n }\n}\n//# sourceMappingURL=resource.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { isReadonlyArray } from \"./utils/values.mjs\";\nconst brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders');\nfunction* iterateHeaders(headers) {\n if (!headers)\n return;\n if (brand_privateNullableHeaders in headers) {\n const { values, nulls } = headers;\n yield* values.entries();\n for (const name of nulls) {\n yield [name, null];\n }\n return;\n }\n let shouldClear = false;\n let iter;\n if (headers instanceof Headers) {\n iter = headers.entries();\n }\n else if (isReadonlyArray(headers)) {\n iter = headers;\n }\n else {\n shouldClear = true;\n iter = Object.entries(headers ?? {});\n }\n for (let row of iter) {\n const name = row[0];\n if (typeof name !== 'string')\n throw new TypeError('expected header name to be a string');\n const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];\n let didClear = false;\n for (const value of values) {\n if (value === undefined)\n continue;\n // Objects keys always overwrite older headers, they never append.\n // Yield a null to clear the header before adding the new values.\n if (shouldClear && !didClear) {\n didClear = true;\n yield [name, null];\n }\n yield [name, value];\n }\n }\n}\nexport const buildHeaders = (newHeaders) => {\n const targetHeaders = new Headers();\n const nullHeaders = new Set();\n for (const headers of newHeaders) {\n const seenHeaders = new Set();\n for (const [name, value] of iterateHeaders(headers)) {\n const lowerName = name.toLowerCase();\n if (!seenHeaders.has(lowerName)) {\n targetHeaders.delete(name);\n seenHeaders.add(lowerName);\n }\n if (value === null) {\n targetHeaders.delete(name);\n nullHeaders.add(lowerName);\n }\n else {\n targetHeaders.append(name, value);\n nullHeaders.delete(lowerName);\n }\n }\n }\n return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };\n};\nexport const isEmptyHeaders = (headers) => {\n for (const _ of iterateHeaders(headers))\n return false;\n return true;\n};\n//# sourceMappingURL=headers.mjs.map","import { AnthropicError } from \"../../core/error.mjs\";\n/**\n * Percent-encode everything that isn't safe to have in a path without encoding safe chars.\n *\n * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:\n * > unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n * > sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\" / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n * > pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n */\nexport function encodeURIPath(str) {\n return str.replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);\n}\nconst EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));\nexport const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) {\n // If there are no params, no processing is needed.\n if (statics.length === 1)\n return statics[0];\n let postPath = false;\n const invalidSegments = [];\n const path = statics.reduce((previousValue, currentValue, index) => {\n if (/[?#]/.test(currentValue)) {\n postPath = true;\n }\n const value = params[index];\n let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);\n if (index !== params.length &&\n (value == null ||\n (typeof value === 'object' &&\n // handle values from other realms\n value.toString ===\n Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)\n ?.toString))) {\n encoded = value + '';\n invalidSegments.push({\n start: previousValue.length + currentValue.length,\n length: encoded.length,\n error: `Value of type ${Object.prototype.toString\n .call(value)\n .slice(8, -1)} is not a valid path parameter`,\n });\n }\n return previousValue + currentValue + (index === params.length ? '' : encoded);\n }, '');\n const pathOnly = path.split(/[?#]/, 1)[0];\n const invalidSegmentPattern = /(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;\n let match;\n // Find all invalid segments\n while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {\n invalidSegments.push({\n start: match.index,\n length: match[0].length,\n error: `Value \"${match[0]}\" can\\'t be safely passed as a path parameter`,\n });\n }\n invalidSegments.sort((a, b) => a.start - b.start);\n if (invalidSegments.length > 0) {\n let lastEnd = 0;\n const underline = invalidSegments.reduce((acc, segment) => {\n const spaces = ' '.repeat(segment.start - lastEnd);\n const arrows = '^'.repeat(segment.length);\n lastEnd = segment.start + segment.length;\n return acc + spaces + arrows;\n }, '');\n throw new AnthropicError(`Path parameters result in path with invalid segments:\\n${invalidSegments\n .map((e) => e.error)\n .join('\\n')}\\n${path}\\n${underline}`);\n }\n return path;\n};\n/**\n * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.\n */\nexport const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);\n//# sourceMappingURL=path.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { Page } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { multipartFormRequestOptions } from \"../../internal/uploads.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Files extends APIResource {\n /**\n * List Files\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fileMetadata of client.beta.files.list()) {\n * // ...\n * }\n * ```\n */\n list(params = {}, options) {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/files', (Page), {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * Delete File\n *\n * @example\n * ```ts\n * const deletedFile = await client.beta.files.delete(\n * 'file_id',\n * );\n * ```\n */\n delete(fileID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.delete(path `/v1/files/${fileID}`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * Download File\n *\n * @example\n * ```ts\n * const response = await client.beta.files.download(\n * 'file_id',\n * );\n *\n * const content = await response.blob();\n * console.log(content);\n * ```\n */\n download(fileID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.get(path `/v1/files/${fileID}/content`, {\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(),\n Accept: 'application/binary',\n },\n options?.headers,\n ]),\n __binaryResponse: true,\n });\n }\n /**\n * Get File Metadata\n *\n * @example\n * ```ts\n * const fileMetadata =\n * await client.beta.files.retrieveMetadata('file_id');\n * ```\n */\n retrieveMetadata(fileID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.get(path `/v1/files/${fileID}`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * Upload File\n *\n * @example\n * ```ts\n * const fileMetadata = await client.beta.files.upload({\n * file: fs.createReadStream('path/to/file'),\n * });\n * ```\n */\n upload(params, options) {\n const { betas, ...body } = params;\n return this._client.post('/v1/files', multipartFormRequestOptions({\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n }, this._client));\n }\n}\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { Page } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n *\n * @example\n * ```ts\n * const betaModelInfo = await client.beta.models.retrieve(\n * 'model_id',\n * );\n * ```\n */\n retrieve(modelID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.get(path `/v1/models/${modelID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaModelInfo of client.beta.models.list()) {\n * // ...\n * }\n * ```\n */\n list(params = {}, options) {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/models?beta=true', (Page), {\n query,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n}\n//# sourceMappingURL=models.mjs.map","import { AnthropicError } from \"../../core/error.mjs\";\nimport { ReadableStreamToAsyncIterable } from \"../shims.mjs\";\nimport { LineDecoder } from \"./line.mjs\";\nexport class JSONLDecoder {\n constructor(iterator, controller) {\n this.iterator = iterator;\n this.controller = controller;\n }\n async *decoder() {\n const lineDecoder = new LineDecoder();\n for await (const chunk of this.iterator) {\n for (const line of lineDecoder.decode(chunk)) {\n yield JSON.parse(line);\n }\n }\n for (const line of lineDecoder.flush()) {\n yield JSON.parse(line);\n }\n }\n [Symbol.asyncIterator]() {\n return this.decoder();\n }\n static fromResponse(response, controller) {\n if (!response.body) {\n controller.abort();\n if (typeof globalThis.navigator !== 'undefined' &&\n globalThis.navigator.product === 'ReactNative') {\n throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);\n }\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);\n }\n}\n//# sourceMappingURL=jsonl.mjs.map","export * from \"./core/error.mjs\";\n//# sourceMappingURL=error.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { Page } from \"../../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { JSONLDecoder } from \"../../../internal/decoders/jsonl.mjs\";\nimport { AnthropicError } from \"../../../error.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatch =\n * await client.beta.messages.batches.create({\n * requests: [\n * {\n * custom_id: 'my-custom-id-1',\n * params: {\n * max_tokens: 1024,\n * messages: [\n * { content: 'Hello, world', role: 'user' },\n * ],\n * model: 'claude-sonnet-4-5-20250929',\n * },\n * },\n * ],\n * });\n * ```\n */\n create(params, options) {\n const { betas, ...body } = params;\n return this._client.post('/v1/messages/batches?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatch =\n * await client.beta.messages.batches.retrieve(\n * 'message_batch_id',\n * );\n * ```\n */\n retrieve(messageBatchID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaMessageBatch of client.beta.messages.batches.list()) {\n * // ...\n * }\n * ```\n */\n list(params = {}, options) {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaDeletedMessageBatch =\n * await client.beta.messages.batches.delete(\n * 'message_batch_id',\n * );\n * ```\n */\n delete(messageBatchID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatch =\n * await client.beta.messages.batches.cancel(\n * 'message_batch_id',\n * );\n * ```\n */\n cancel(messageBatchID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatchIndividualResponse =\n * await client.beta.messages.batches.results(\n * 'message_batch_id',\n * );\n * ```\n */\n async results(messageBatchID, params = {}, options) {\n const batch = await this.retrieve(messageBatchID);\n if (!batch.results_url) {\n throw new AnthropicError(`No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);\n }\n const { betas } = params ?? {};\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n Accept: 'application/binary',\n },\n options?.headers,\n ]),\n stream: true,\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));\n }\n}\n//# sourceMappingURL=batches.mjs.map","export * from \"./core/streaming.mjs\";\n//# sourceMappingURL=streaming.mjs.map","const tokenize = (input) => {\n let current = 0;\n let tokens = [];\n while (current < input.length) {\n let char = input[current];\n if (char === '\\\\') {\n current++;\n continue;\n }\n if (char === '{') {\n tokens.push({\n type: 'brace',\n value: '{',\n });\n current++;\n continue;\n }\n if (char === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n current++;\n continue;\n }\n if (char === '[') {\n tokens.push({\n type: 'paren',\n value: '[',\n });\n current++;\n continue;\n }\n if (char === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n current++;\n continue;\n }\n if (char === ':') {\n tokens.push({\n type: 'separator',\n value: ':',\n });\n current++;\n continue;\n }\n if (char === ',') {\n tokens.push({\n type: 'delimiter',\n value: ',',\n });\n current++;\n continue;\n }\n if (char === '\"') {\n let value = '';\n let danglingQuote = false;\n char = input[++current];\n while (char !== '\"') {\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n if (char === '\\\\') {\n current++;\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n value += char + input[current];\n char = input[++current];\n }\n else {\n value += char;\n char = input[++current];\n }\n }\n char = input[++current];\n if (!danglingQuote) {\n tokens.push({\n type: 'string',\n value,\n });\n }\n continue;\n }\n let WHITESPACE = /\\s/;\n if (char && WHITESPACE.test(char)) {\n current++;\n continue;\n }\n let NUMBERS = /[0-9]/;\n if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {\n let value = '';\n if (char === '-') {\n value += char;\n char = input[++current];\n }\n while ((char && NUMBERS.test(char)) || char === '.') {\n value += char;\n char = input[++current];\n }\n tokens.push({\n type: 'number',\n value,\n });\n continue;\n }\n let LETTERS = /[a-z]/i;\n if (char && LETTERS.test(char)) {\n let value = '';\n while (char && LETTERS.test(char)) {\n if (current === input.length) {\n break;\n }\n value += char;\n char = input[++current];\n }\n if (value == 'true' || value == 'false' || value === 'null') {\n tokens.push({\n type: 'name',\n value,\n });\n }\n else {\n // unknown token, e.g. `nul` which isn't quite `null`\n current++;\n continue;\n }\n continue;\n }\n current++;\n }\n return tokens;\n}, strip = (tokens) => {\n if (tokens.length === 0) {\n return tokens;\n }\n let lastToken = tokens[tokens.length - 1];\n switch (lastToken.type) {\n case 'separator':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n case 'number':\n let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];\n if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n case 'string':\n let tokenBeforeTheLastToken = tokens[tokens.length - 2];\n if (tokenBeforeTheLastToken?.type === 'delimiter') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n break;\n case 'delimiter':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n }\n return tokens;\n}, unstrip = (tokens) => {\n let tail = [];\n tokens.map((token) => {\n if (token.type === 'brace') {\n if (token.value === '{') {\n tail.push('}');\n }\n else {\n tail.splice(tail.lastIndexOf('}'), 1);\n }\n }\n if (token.type === 'paren') {\n if (token.value === '[') {\n tail.push(']');\n }\n else {\n tail.splice(tail.lastIndexOf(']'), 1);\n }\n }\n });\n if (tail.length > 0) {\n tail.reverse().map((item) => {\n if (item === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n }\n else if (item === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n }\n });\n }\n return tokens;\n}, generate = (tokens) => {\n let output = '';\n tokens.map((token) => {\n switch (token.type) {\n case 'string':\n output += '\"' + token.value + '\"';\n break;\n default:\n output += token.value;\n break;\n }\n });\n return output;\n}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));\nexport { partialParse };\n//# sourceMappingURL=parser.mjs.map","var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { isAbortError } from \"../internal/errors.mjs\";\nimport { AnthropicError, APIUserAbortError } from \"../error.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.mjs\";\nconst JSON_BUF_PROPERTY = '__json_buf';\nfunction tracksToolInput(content) {\n return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use';\n}\nexport class BetaMessageStream {\n constructor() {\n _BetaMessageStream_instances.add(this);\n this.messages = [];\n this.receivedMessages = [];\n _BetaMessageStream_currentMessageSnapshot.set(this, void 0);\n this.controller = new AbortController();\n _BetaMessageStream_connectedPromise.set(this, void 0);\n _BetaMessageStream_resolveConnectedPromise.set(this, () => { });\n _BetaMessageStream_rejectConnectedPromise.set(this, () => { });\n _BetaMessageStream_endPromise.set(this, void 0);\n _BetaMessageStream_resolveEndPromise.set(this, () => { });\n _BetaMessageStream_rejectEndPromise.set(this, () => { });\n _BetaMessageStream_listeners.set(this, {});\n _BetaMessageStream_ended.set(this, false);\n _BetaMessageStream_errored.set(this, false);\n _BetaMessageStream_aborted.set(this, false);\n _BetaMessageStream_catchingPromiseCreated.set(this, false);\n _BetaMessageStream_response.set(this, void 0);\n _BetaMessageStream_request_id.set(this, void 0);\n _BetaMessageStream_handleError.set(this, (error) => {\n __classPrivateFieldSet(this, _BetaMessageStream_errored, true, \"f\");\n if (isAbortError(error)) {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, \"f\");\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n });\n __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, \"f\");\n }), \"f\");\n __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, \"f\");\n }), \"f\");\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, \"f\").catch(() => { });\n __classPrivateFieldGet(this, _BetaMessageStream_endPromise, \"f\").catch(() => { });\n }\n get response() {\n return __classPrivateFieldGet(this, _BetaMessageStream_response, \"f\");\n }\n get request_id() {\n return __classPrivateFieldGet(this, _BetaMessageStream_request_id, \"f\");\n }\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse() {\n const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, \"f\");\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream) {\n const runner = new BetaMessageStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n static createMessage(messages, params, options) {\n const runner = new BetaMessageStream();\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));\n return runner;\n }\n _run(executor) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, \"f\"));\n }\n _addMessageParam(message) {\n this.messages.push(message);\n }\n _addMessage(message, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n async _createMessage(messages, params, options) {\n const signal = options?.signal;\n let abortHandler;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_beginRequest).call(this);\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_addStreamEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_endRequest).call(this);\n }\n finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n _connected(response) {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _BetaMessageStream_response, response, \"f\");\n __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), \"f\");\n __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, \"f\").call(this, response);\n this._emit('connect');\n }\n get ended() {\n return __classPrivateFieldGet(this, _BetaMessageStream_ended, \"f\");\n }\n get errored() {\n return __classPrivateFieldGet(this, _BetaMessageStream_errored, \"f\");\n }\n get aborted() {\n return __classPrivateFieldGet(this, _BetaMessageStream_aborted, \"f\");\n }\n abort() {\n this.controller.abort();\n }\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on(event, listener) {\n const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event] = []);\n listeners.push({ listener });\n return this;\n }\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off(event, listener) {\n const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event];\n if (!listeners)\n return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0)\n listeners.splice(index, 1);\n return this;\n }\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once(event, listener) {\n const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted(event) {\n return new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, \"f\");\n if (event !== 'error')\n this.once('error', reject);\n this.once(event, resolve);\n });\n }\n async done() {\n __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, \"f\");\n await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, \"f\");\n }\n get currentMessage() {\n return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, \"f\");\n }\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalMessage() {\n await this.done();\n return __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_getFinalMessage).call(this);\n }\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText() {\n await this.done();\n return __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_getFinalText).call(this);\n }\n _emit(event, ...args) {\n // make sure we don't emit any MessageStreamEvents after end\n if (__classPrivateFieldGet(this, _BetaMessageStream_ended, \"f\"))\n return;\n if (event === 'end') {\n __classPrivateFieldSet(this, _BetaMessageStream_ended, true, \"f\");\n __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, \"f\").call(this);\n }\n const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event];\n if (listeners) {\n __classPrivateFieldGet(this, _BetaMessageStream_listeners, \"f\")[event] = listeners.filter((l) => !l.once);\n listeners.forEach(({ listener }) => listener(...args));\n }\n if (event === 'abort') {\n const error = args[0];\n if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n return;\n }\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n const error = args[0];\n if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n }\n }\n _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_getFinalMessage).call(this));\n }\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n let abortHandler;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_beginRequest).call(this);\n this._connected(null);\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_addStreamEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_endRequest).call(this);\n }\n finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1);\n }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)\n .content.filter((block) => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, \"f\");\n }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) {\n if (this.ended)\n return;\n const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, \"m\", _BetaMessageStream_accumulateMessage).call(this, event);\n this._emit('streamEvent', event, messageSnapshot);\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1);\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (tracksToolInput(content) && content.input) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(messageSnapshot, true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1));\n break;\n }\n case 'message_start': {\n __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, \"f\");\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, \"f\");\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, \"f\");\n return snapshot;\n }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) {\n let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, \"f\");\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.container = event.delta.container;\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n snapshot.usage.output_tokens = event.usage.output_tokens;\n snapshot.context_management = event.context_management;\n if (event.usage.input_tokens != null) {\n snapshot.usage.input_tokens = event.usage.input_tokens;\n }\n if (event.usage.cache_creation_input_tokens != null) {\n snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;\n }\n if (event.usage.cache_read_input_tokens != null) {\n snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;\n }\n if (event.usage.server_tool_use != null) {\n snapshot.usage.server_tool_use = event.usage.server_tool_use;\n }\n return snapshot;\n case 'content_block_start':\n snapshot.content.push(event.content_block);\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n text: (snapshotContent.text || '') + event.delta.text,\n };\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n citations: [...(snapshotContent.citations ?? []), event.delta.citation],\n };\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent && tracksToolInput(snapshotContent)) {\n // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n const newContent = { ...snapshotContent };\n Object.defineProperty(newContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n if (jsonBuf) {\n try {\n newContent.input = partialParse(jsonBuf);\n }\n catch (err) {\n const error = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);\n __classPrivateFieldGet(this, _BetaMessageStream_handleError, \"f\").call(this, error);\n }\n }\n snapshot.content[event.index] = newContent;\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n thinking: snapshotContent.thinking + event.delta.thinking,\n };\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n signature: event.delta.signature,\n };\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\n }\n }, Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n }\n else {\n pushQueue.push(event);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x) { }\n//# sourceMappingURL=BetaMessageStream.mjs.map","// File containing shared constants\n/**\n * Model-specific timeout constraints for non-streaming requests\n */\nexport const MODEL_NONSTREAMING_TOKENS = {\n 'claude-opus-4-20250514': 8192,\n 'claude-opus-4-0': 8192,\n 'claude-4-opus-20250514': 8192,\n 'anthropic.claude-opus-4-20250514-v1:0': 8192,\n 'claude-opus-4@20250514': 8192,\n 'claude-opus-4-1-20250805': 8192,\n 'anthropic.claude-opus-4-1-20250805-v1:0': 8192,\n 'claude-opus-4-1@20250805': 8192,\n};\n//# sourceMappingURL=constants.mjs.map","var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_generateToolResponse;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../../internal/tslib.mjs\";\nimport { AnthropicError } from \"../../core/error.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\n/**\n * Just Promise.withResolvers(), which is not available in all environments.\n */\nfunction promiseWithResolvers() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve: resolve, reject: reject };\n}\n/**\n * A ToolRunner handles the automatic conversation loop between the assistant and tools.\n *\n * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects\n * depending on the streaming configuration.\n */\nexport class BetaToolRunner {\n constructor(client, params, options) {\n _BetaToolRunner_instances.add(this);\n this.client = client;\n /** Whether the async iterator has been consumed */\n _BetaToolRunner_consumed.set(this, false);\n /** Whether parameters have been mutated since the last API call */\n _BetaToolRunner_mutated.set(this, false);\n /** Current state containing the request parameters */\n _BetaToolRunner_state.set(this, void 0);\n _BetaToolRunner_options.set(this, void 0);\n /** Promise for the last message received from the assistant */\n _BetaToolRunner_message.set(this, void 0);\n /** Cached tool response to avoid redundant executions */\n _BetaToolRunner_toolResponse.set(this, void 0);\n /** Promise resolvers for waiting on completion */\n _BetaToolRunner_completion.set(this, void 0);\n /** Number of iterations (API requests) made so far */\n _BetaToolRunner_iterationCount.set(this, 0);\n __classPrivateFieldSet(this, _BetaToolRunner_state, {\n params: {\n // You can't clone the entire params since there are functions as handlers.\n // You also don't really need to clone params.messages, but it probably will prevent a foot gun\n // somewhere.\n ...params,\n messages: structuredClone(params.messages),\n },\n }, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_options, {\n ...options,\n headers: buildHeaders([{ 'x-stainless-helper': 'BetaToolRunner' }, options?.headers]),\n }, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), \"f\");\n }\n async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), Symbol.asyncIterator)]() {\n var _a;\n if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, \"f\")) {\n throw new AnthropicError('Cannot iterate over a consumed stream');\n }\n __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, \"f\");\n try {\n while (true) {\n let stream;\n try {\n if (__classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params.max_iterations &&\n __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, \"f\") >= __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params.max_iterations) {\n break;\n }\n __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, \"f\");\n __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, \"f\"), _a++, _a), \"f\");\n const { max_iterations, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params;\n if (params.stream) {\n stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, \"f\"));\n __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), \"f\");\n yield stream;\n }\n else {\n __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, \"f\")), \"f\");\n yield __classPrivateFieldGet(this, _BetaToolRunner_message, \"f\");\n }\n if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, \"f\")) {\n const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, \"f\");\n __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params.messages.push({ role, content });\n }\n const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, \"m\", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params.messages.at(-1));\n if (toolMessage) {\n __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params.messages.push(toolMessage);\n }\n if (!toolMessage && !__classPrivateFieldGet(this, _BetaToolRunner_mutated, \"f\")) {\n break;\n }\n }\n finally {\n if (stream) {\n stream.abort();\n }\n }\n }\n if (!__classPrivateFieldGet(this, _BetaToolRunner_message, \"f\")) {\n throw new AnthropicError('ToolRunner concluded without a message from the server');\n }\n __classPrivateFieldGet(this, _BetaToolRunner_completion, \"f\").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, \"f\"));\n }\n catch (error) {\n __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, \"f\");\n // Silence unhandled promise errors\n __classPrivateFieldGet(this, _BetaToolRunner_completion, \"f\").promise.catch(() => { });\n __classPrivateFieldGet(this, _BetaToolRunner_completion, \"f\").reject(error);\n __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), \"f\");\n throw error;\n }\n }\n setMessagesParams(paramsOrMutator) {\n if (typeof paramsOrMutator === 'function') {\n __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params);\n }\n else {\n __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params = paramsOrMutator;\n }\n __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, \"f\");\n // Invalidate cached tool response since parameters changed\n __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, \"f\");\n }\n /**\n * Get the tool response for the last message from the assistant.\n * Avoids redundant tool executions by caching results.\n *\n * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed\n *\n * @example\n * const toolResponse = await runner.generateToolResponse();\n * if (toolResponse) {\n * console.log('Tool results:', toolResponse.content);\n * }\n */\n async generateToolResponse() {\n const message = (await __classPrivateFieldGet(this, _BetaToolRunner_message, \"f\")) ?? this.params.messages.at(-1);\n if (!message) {\n return null;\n }\n return __classPrivateFieldGet(this, _BetaToolRunner_instances, \"m\", _BetaToolRunner_generateToolResponse).call(this, message);\n }\n /**\n * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and\n * will wait for an instance to start and go to completion.\n *\n * @returns A promise that resolves to the final BetaMessage when the iterator completes\n *\n * @example\n * // Start consuming the iterator\n * for await (const message of runner) {\n * console.log('Message:', message.content);\n * }\n *\n * // Meanwhile, wait for completion from another part of the code\n * const finalMessage = await runner.done();\n * console.log('Final response:', finalMessage.content);\n */\n done() {\n return __classPrivateFieldGet(this, _BetaToolRunner_completion, \"f\").promise;\n }\n /**\n * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:\n * * If the iterator has not been consumed, consume the entire iterator and return the final message from the\n * assistant.\n * * If the iterator has been consumed, waits for it to complete and returns the final message.\n *\n * @returns A promise that resolves to the final BetaMessage from the conversation\n * @throws {AnthropicError} If no messages were processed during the conversation\n *\n * @example\n * const finalMessage = await runner.runUntilDone();\n * console.log('Final response:', finalMessage.content);\n */\n async runUntilDone() {\n // If not yet consumed, start consuming and wait for completion\n if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, \"f\")) {\n for await (const _ of this) {\n // Iterator naturally populates this.#message\n }\n }\n // If consumed but not completed, wait for completion\n return this.done();\n }\n /**\n * Get the current parameters being used by the ToolRunner.\n *\n * @returns A readonly view of the current ToolRunnerParams\n *\n * @example\n * const currentParams = runner.params;\n * console.log('Current model:', currentParams.model);\n * console.log('Message count:', currentParams.messages.length);\n */\n get params() {\n return __classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params;\n }\n /**\n * Add one or more messages to the conversation history.\n *\n * @param messages - One or more BetaMessageParam objects to add to the conversation\n *\n * @example\n * runner.pushMessages(\n * { role: 'user', content: 'Also, what about the weather in NYC?' }\n * );\n *\n * @example\n * // Adding multiple messages\n * runner.pushMessages(\n * { role: 'user', content: 'What about NYC?' },\n * { role: 'user', content: 'And Boston?' }\n * );\n */\n pushMessages(...messages) {\n this.setMessagesParams((params) => ({\n ...params,\n messages: [...params.messages, ...messages],\n }));\n }\n /**\n * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()\n * This allows using `await runner` instead of `await runner.runUntilDone()`\n */\n then(onfulfilled, onrejected) {\n return this.runUntilDone().then(onfulfilled, onrejected);\n }\n}\n_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) {\n if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, \"f\") !== undefined) {\n return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, \"f\");\n }\n __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, \"f\").params, lastMessage), \"f\");\n return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, \"f\");\n};\nasync function generateToolResponse(params, lastMessage = params.messages.at(-1)) {\n // Only process if the last message is from the assistant and has tool use blocks\n if (!lastMessage ||\n lastMessage.role !== 'assistant' ||\n !lastMessage.content ||\n typeof lastMessage.content === 'string') {\n return null;\n }\n const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use');\n if (toolUseBlocks.length === 0) {\n return null;\n }\n const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {\n const tool = params.tools.find((t) => t.name === toolUse.name);\n if (!tool || !('run' in tool)) {\n return {\n type: 'tool_result',\n tool_use_id: toolUse.id,\n content: `Error: Tool '${toolUse.name}' not found`,\n is_error: true,\n };\n }\n try {\n let input = toolUse.input;\n if ('parse' in tool && tool.parse) {\n input = tool.parse(input);\n }\n const result = await tool.run(input);\n return {\n type: 'tool_result',\n tool_use_id: toolUse.id,\n content: result,\n };\n }\n catch (error) {\n return {\n type: 'tool_result',\n tool_use_id: toolUse.id,\n content: `Error: ${error instanceof Error ? error.message : String(error)}`,\n is_error: true,\n };\n }\n }));\n return {\n role: 'user',\n content: toolResults,\n };\n}\n//# sourceMappingURL=BetaToolRunner.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as BatchesAPI from \"./batches.mjs\";\nimport { Batches, } from \"./batches.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { BetaMessageStream } from \"../../../lib/BetaMessageStream.mjs\";\nimport { MODEL_NONSTREAMING_TOKENS } from \"../../../internal/constants.mjs\";\nimport { BetaToolRunner, } from \"../../../lib/tools/BetaToolRunner.mjs\";\nconst DEPRECATED_MODELS = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-3-opus-20240229': 'January 5th, 2026',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n 'claude-3-5-sonnet-20241022': 'October 22, 2025',\n 'claude-3-5-sonnet-20240620': 'October 22, 2025',\n};\nexport class Messages extends APIResource {\n constructor() {\n super(...arguments);\n this.batches = new BatchesAPI.Batches(this._client);\n }\n create(params, options) {\n const { betas, ...body } = params;\n if (body.model in DEPRECATED_MODELS) {\n console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);\n }\n let timeout = this._client._options.timeout;\n if (!body.stream && timeout == null) {\n const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;\n timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);\n }\n return this._client.post('/v1/messages?beta=true', {\n body,\n timeout: timeout ?? 600000,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n stream: params.stream ?? false,\n });\n }\n /**\n * Create a Message stream\n */\n stream(body, options) {\n return BetaMessageStream.createMessage(this, body, options);\n }\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](/en/docs/build-with-claude/token-counting)\n *\n * @example\n * ```ts\n * const betaMessageTokensCount =\n * await client.beta.messages.countTokens({\n * messages: [{ content: 'string', role: 'user' }],\n * model: 'claude-3-7-sonnet-latest',\n * });\n * ```\n */\n countTokens(params, options) {\n const { betas, ...body } = params;\n return this._client.post('/v1/messages/count_tokens?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },\n options?.headers,\n ]),\n });\n }\n toolRunner(body, options) {\n return new BetaToolRunner(this._client, body, options);\n }\n}\nexport { BetaToolRunner } from \"../../../lib/tools/BetaToolRunner.mjs\";\nMessages.Batches = Batches;\nMessages.BetaToolRunner = BetaToolRunner;\n//# sourceMappingURL=messages.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as FilesAPI from \"./files.mjs\";\nimport { Files, } from \"./files.mjs\";\nimport * as ModelsAPI from \"./models.mjs\";\nimport { Models } from \"./models.mjs\";\nimport * as MessagesAPI from \"./messages/messages.mjs\";\nimport { Messages, } from \"./messages/messages.mjs\";\nexport class Beta extends APIResource {\n constructor() {\n super(...arguments);\n this.models = new ModelsAPI.Models(this._client);\n this.messages = new MessagesAPI.Messages(this._client);\n this.files = new FilesAPI.Files(this._client);\n }\n}\nBeta.Models = Models;\nBeta.Messages = Messages;\nBeta.Files = Files;\n//# sourceMappingURL=beta.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { buildHeaders } from \"../internal/headers.mjs\";\nexport class Completions extends APIResource {\n create(params, options) {\n const { betas, ...body } = params;\n return this._client.post('/v1/complete', {\n body,\n timeout: this._client._options.timeout ?? 600000,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n stream: params.stream ?? false,\n });\n }\n}\n//# sourceMappingURL=completions.mjs.map","var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { isAbortError } from \"../internal/errors.mjs\";\nimport { AnthropicError, APIUserAbortError } from \"../error.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.mjs\";\nconst JSON_BUF_PROPERTY = '__json_buf';\nfunction tracksToolInput(content) {\n return content.type === 'tool_use' || content.type === 'server_tool_use';\n}\nexport class MessageStream {\n constructor() {\n _MessageStream_instances.add(this);\n this.messages = [];\n this.receivedMessages = [];\n _MessageStream_currentMessageSnapshot.set(this, void 0);\n this.controller = new AbortController();\n _MessageStream_connectedPromise.set(this, void 0);\n _MessageStream_resolveConnectedPromise.set(this, () => { });\n _MessageStream_rejectConnectedPromise.set(this, () => { });\n _MessageStream_endPromise.set(this, void 0);\n _MessageStream_resolveEndPromise.set(this, () => { });\n _MessageStream_rejectEndPromise.set(this, () => { });\n _MessageStream_listeners.set(this, {});\n _MessageStream_ended.set(this, false);\n _MessageStream_errored.set(this, false);\n _MessageStream_aborted.set(this, false);\n _MessageStream_catchingPromiseCreated.set(this, false);\n _MessageStream_response.set(this, void 0);\n _MessageStream_request_id.set(this, void 0);\n _MessageStream_handleError.set(this, (error) => {\n __classPrivateFieldSet(this, _MessageStream_errored, true, \"f\");\n if (isAbortError(error)) {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n __classPrivateFieldSet(this, _MessageStream_aborted, true, \"f\");\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n });\n __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, \"f\");\n }), \"f\");\n __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, \"f\");\n }), \"f\");\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n __classPrivateFieldGet(this, _MessageStream_connectedPromise, \"f\").catch(() => { });\n __classPrivateFieldGet(this, _MessageStream_endPromise, \"f\").catch(() => { });\n }\n get response() {\n return __classPrivateFieldGet(this, _MessageStream_response, \"f\");\n }\n get request_id() {\n return __classPrivateFieldGet(this, _MessageStream_request_id, \"f\");\n }\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse() {\n const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, \"f\");\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream) {\n const runner = new MessageStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n static createMessage(messages, params, options) {\n const runner = new MessageStream();\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));\n return runner;\n }\n _run(executor) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, __classPrivateFieldGet(this, _MessageStream_handleError, \"f\"));\n }\n _addMessageParam(message) {\n this.messages.push(message);\n }\n _addMessage(message, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n async _createMessage(messages, params, options) {\n const signal = options?.signal;\n let abortHandler;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_beginRequest).call(this);\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_addStreamEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_endRequest).call(this);\n }\n finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n _connected(response) {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _MessageStream_response, response, \"f\");\n __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), \"f\");\n __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, \"f\").call(this, response);\n this._emit('connect');\n }\n get ended() {\n return __classPrivateFieldGet(this, _MessageStream_ended, \"f\");\n }\n get errored() {\n return __classPrivateFieldGet(this, _MessageStream_errored, \"f\");\n }\n get aborted() {\n return __classPrivateFieldGet(this, _MessageStream_aborted, \"f\");\n }\n abort() {\n this.controller.abort();\n }\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on(event, listener) {\n const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event] = []);\n listeners.push({ listener });\n return this;\n }\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off(event, listener) {\n const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event];\n if (!listeners)\n return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0)\n listeners.splice(index, 1);\n return this;\n }\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once(event, listener) {\n const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted(event) {\n return new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, \"f\");\n if (event !== 'error')\n this.once('error', reject);\n this.once(event, resolve);\n });\n }\n async done() {\n __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, \"f\");\n await __classPrivateFieldGet(this, _MessageStream_endPromise, \"f\");\n }\n get currentMessage() {\n return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, \"f\");\n }\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalMessage() {\n await this.done();\n return __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_getFinalMessage).call(this);\n }\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText() {\n await this.done();\n return __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_getFinalText).call(this);\n }\n _emit(event, ...args) {\n // make sure we don't emit any MessageStreamEvents after end\n if (__classPrivateFieldGet(this, _MessageStream_ended, \"f\"))\n return;\n if (event === 'end') {\n __classPrivateFieldSet(this, _MessageStream_ended, true, \"f\");\n __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, \"f\").call(this);\n }\n const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event];\n if (listeners) {\n __classPrivateFieldGet(this, _MessageStream_listeners, \"f\")[event] = listeners.filter((l) => !l.once);\n listeners.forEach(({ listener }) => listener(...args));\n }\n if (event === 'abort') {\n const error = args[0];\n if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n return;\n }\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n const error = args[0];\n if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n }\n }\n _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_getFinalMessage).call(this));\n }\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n let abortHandler;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_beginRequest).call(this);\n this._connected(null);\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_addStreamEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_endRequest).call(this);\n }\n finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1);\n }, _MessageStream_getFinalText = function _MessageStream_getFinalText() {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)\n .content.filter((block) => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }, _MessageStream_beginRequest = function _MessageStream_beginRequest() {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, \"f\");\n }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) {\n if (this.ended)\n return;\n const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, \"m\", _MessageStream_accumulateMessage).call(this, event);\n this._emit('streamEvent', event, messageSnapshot);\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1);\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (tracksToolInput(content) && content.input) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(messageSnapshot, true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1));\n break;\n }\n case 'message_start': {\n __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, \"f\");\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }, _MessageStream_endRequest = function _MessageStream_endRequest() {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, \"f\");\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, \"f\");\n return snapshot;\n }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) {\n let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, \"f\");\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n snapshot.usage.output_tokens = event.usage.output_tokens;\n // Update other usage fields if they exist in the event\n if (event.usage.input_tokens != null) {\n snapshot.usage.input_tokens = event.usage.input_tokens;\n }\n if (event.usage.cache_creation_input_tokens != null) {\n snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;\n }\n if (event.usage.cache_read_input_tokens != null) {\n snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;\n }\n if (event.usage.server_tool_use != null) {\n snapshot.usage.server_tool_use = event.usage.server_tool_use;\n }\n return snapshot;\n case 'content_block_start':\n snapshot.content.push({ ...event.content_block });\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n text: (snapshotContent.text || '') + event.delta.text,\n };\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n citations: [...(snapshotContent.citations ?? []), event.delta.citation],\n };\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent && tracksToolInput(snapshotContent)) {\n // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n const newContent = { ...snapshotContent };\n Object.defineProperty(newContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n if (jsonBuf) {\n newContent.input = partialParse(jsonBuf);\n }\n snapshot.content[event.index] = newContent;\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n thinking: snapshotContent.thinking + event.delta.thinking,\n };\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n signature: event.delta.signature,\n };\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\n }\n }, Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n }\n else {\n pushQueue.push(event);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x) { }\n//# sourceMappingURL=MessageStream.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { Page } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { JSONLDecoder } from \"../../internal/decoders/jsonl.mjs\";\nimport { AnthropicError } from \"../../error.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatch = await client.messages.batches.create({\n * requests: [\n * {\n * custom_id: 'my-custom-id-1',\n * params: {\n * max_tokens: 1024,\n * messages: [\n * { content: 'Hello, world', role: 'user' },\n * ],\n * model: 'claude-sonnet-4-5-20250929',\n * },\n * },\n * ],\n * });\n * ```\n */\n create(body, options) {\n return this._client.post('/v1/messages/batches', { body, ...options });\n }\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatch = await client.messages.batches.retrieve(\n * 'message_batch_id',\n * );\n * ```\n */\n retrieve(messageBatchID, options) {\n return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options);\n }\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const messageBatch of client.messages.batches.list()) {\n * // ...\n * }\n * ```\n */\n list(query = {}, options) {\n return this._client.getAPIList('/v1/messages/batches', (Page), { query, ...options });\n }\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const deletedMessageBatch =\n * await client.messages.batches.delete('message_batch_id');\n * ```\n */\n delete(messageBatchID, options) {\n return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options);\n }\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatch = await client.messages.batches.cancel(\n * 'message_batch_id',\n * );\n * ```\n */\n cancel(messageBatchID, options) {\n return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options);\n }\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatchIndividualResponse =\n * await client.messages.batches.results('message_batch_id');\n * ```\n */\n async results(messageBatchID, options) {\n const batch = await this.retrieve(messageBatchID);\n if (!batch.results_url) {\n throw new AnthropicError(`No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);\n }\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]),\n stream: true,\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));\n }\n}\n//# sourceMappingURL=batches.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { MessageStream } from \"../../lib/MessageStream.mjs\";\nimport * as BatchesAPI from \"./batches.mjs\";\nimport { Batches, } from \"./batches.mjs\";\nimport { MODEL_NONSTREAMING_TOKENS } from \"../../internal/constants.mjs\";\nexport class Messages extends APIResource {\n constructor() {\n super(...arguments);\n this.batches = new BatchesAPI.Batches(this._client);\n }\n create(body, options) {\n if (body.model in DEPRECATED_MODELS) {\n console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);\n }\n let timeout = this._client._options.timeout;\n if (!body.stream && timeout == null) {\n const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;\n timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);\n }\n return this._client.post('/v1/messages', {\n body,\n timeout: timeout ?? 600000,\n ...options,\n stream: body.stream ?? false,\n });\n }\n /**\n * Create a Message stream\n */\n stream(body, options) {\n return MessageStream.createMessage(this, body, options);\n }\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](/en/docs/build-with-claude/token-counting)\n *\n * @example\n * ```ts\n * const messageTokensCount =\n * await client.messages.countTokens({\n * messages: [{ content: 'string', role: 'user' }],\n * model: 'claude-3-7-sonnet-latest',\n * });\n * ```\n */\n countTokens(body, options) {\n return this._client.post('/v1/messages/count_tokens', { body, ...options });\n }\n}\nconst DEPRECATED_MODELS = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-3-opus-20240229': 'January 5th, 2026',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n 'claude-3-5-sonnet-20241022': 'October 22, 2025',\n 'claude-3-5-sonnet-20240620': 'October 22, 2025',\n};\nMessages.Batches = Batches;\n//# sourceMappingURL=messages.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { Page } from \"../core/pagination.mjs\";\nimport { buildHeaders } from \"../internal/headers.mjs\";\nimport { path } from \"../internal/utils/path.mjs\";\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n */\n retrieve(modelID, params = {}, options) {\n const { betas } = params ?? {};\n return this._client.get(path `/v1/models/${modelID}`, {\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n */\n list(params = {}, options) {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/models', (Page), {\n query,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n}\n//# sourceMappingURL=models.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport * from \"./shared.mjs\";\nexport { Beta, } from \"./beta/beta.mjs\";\nexport { Completions, } from \"./completions.mjs\";\nexport { Messages, } from \"./messages/messages.mjs\";\nexport { Models, } from \"./models.mjs\";\n//# sourceMappingURL=index.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env) => {\n if (typeof globalThis.process !== 'undefined') {\n return globalThis.process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof globalThis.Deno !== 'undefined') {\n return globalThis.Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\n//# sourceMappingURL=env.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"./internal/tslib.mjs\";\nimport { uuid4 } from \"./internal/utils/uuid.mjs\";\nimport { validatePositiveInteger, isAbsoluteURL, safeJSON } from \"./internal/utils/values.mjs\";\nimport { sleep } from \"./internal/utils/sleep.mjs\";\nimport { castToError, isAbortError } from \"./internal/errors.mjs\";\nimport { getPlatformHeaders } from \"./internal/detect-platform.mjs\";\nimport * as Shims from \"./internal/shims.mjs\";\nimport * as Opts from \"./internal/request-options.mjs\";\nimport { VERSION } from \"./version.mjs\";\nimport * as Errors from \"./core/error.mjs\";\nimport * as Pagination from \"./core/pagination.mjs\";\nimport * as Uploads from \"./core/uploads.mjs\";\nimport * as API from \"./resources/index.mjs\";\nimport { APIPromise } from \"./core/api-promise.mjs\";\nimport { Completions, } from \"./resources/completions.mjs\";\nimport { Models } from \"./resources/models.mjs\";\nimport { Beta, } from \"./resources/beta/beta.mjs\";\nimport { Messages, } from \"./resources/messages/messages.mjs\";\nimport { isRunningInBrowser } from \"./internal/detect-platform.mjs\";\nimport { buildHeaders } from \"./internal/headers.mjs\";\nimport { readEnv } from \"./internal/utils/env.mjs\";\nimport { formatRequestDetails, loggerFor, parseLogLevel, } from \"./internal/utils/log.mjs\";\nimport { isEmptyObj } from \"./internal/utils/values.mjs\";\nexport const HUMAN_PROMPT = '\\\\n\\\\nHuman:';\nexport const AI_PROMPT = '\\\\n\\\\nAssistant:';\n/**\n * Base class for Anthropic API clients.\n */\nexport class BaseAnthropic {\n /**\n * API Client for interfacing with the Anthropic API.\n *\n * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]\n * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]\n * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.\n * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {\n _BaseAnthropic_instances.add(this);\n _BaseAnthropic_encoder.set(this, void 0);\n const options = {\n apiKey,\n authToken,\n ...opts,\n baseURL: baseURL || `https://api.anthropic.com`,\n };\n if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {\n throw new Errors.AnthropicError(\"It looks like you're running in a browser-like environment.\\n\\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\\nIf you understand the risks and have appropriate mitigations in place,\\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\\n\\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\\n\");\n }\n this.baseURL = options.baseURL;\n this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;\n this.logger = options.logger ?? console;\n const defaultLogLevel = 'warn';\n // Set default logLevel early so that we can log a warning in parseLogLevel.\n this.logLevel = defaultLogLevel;\n this.logLevel =\n parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??\n parseLogLevel(readEnv('ANTHROPIC_LOG'), \"process.env['ANTHROPIC_LOG']\", this) ??\n defaultLogLevel;\n this.fetchOptions = options.fetchOptions;\n this.maxRetries = options.maxRetries ?? 2;\n this.fetch = options.fetch ?? Shims.getDefaultFetch();\n __classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, \"f\");\n this._options = options;\n this.apiKey = apiKey;\n this.authToken = authToken;\n }\n /**\n * Create a new client instance re-using the same options given to the current client with optional overriding.\n */\n withOptions(options) {\n const client = new this.constructor({\n ...this._options,\n baseURL: this.baseURL,\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n logger: this.logger,\n logLevel: this.logLevel,\n fetch: this.fetch,\n fetchOptions: this.fetchOptions,\n apiKey: this.apiKey,\n authToken: this.authToken,\n ...options,\n });\n return client;\n }\n defaultQuery() {\n return this._options.defaultQuery;\n }\n validateHeaders({ values, nulls }) {\n if (this.apiKey && values.get('x-api-key')) {\n return;\n }\n if (nulls.has('x-api-key')) {\n return;\n }\n if (this.authToken && values.get('authorization')) {\n return;\n }\n if (nulls.has('authorization')) {\n return;\n }\n throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the \"X-Api-Key\" or \"Authorization\" headers to be explicitly omitted');\n }\n async authHeaders(opts) {\n return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);\n }\n async apiKeyAuth(opts) {\n if (this.apiKey == null) {\n return undefined;\n }\n return buildHeaders([{ 'X-Api-Key': this.apiKey }]);\n }\n async bearerAuth(opts) {\n if (this.authToken == null) {\n return undefined;\n }\n return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);\n }\n /**\n * Basic re-implementation of `qs.stringify` for primitive types.\n */\n stringifyQuery(query) {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new Errors.AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);\n })\n .join('&');\n }\n getUserAgent() {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n defaultIdempotencyKey() {\n return `stainless-node-retry-${uuid4()}`;\n }\n makeStatusError(status, error, message, headers) {\n return Errors.APIError.generate(status, error, message, headers);\n }\n buildURL(path, query, defaultBaseURL) {\n const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, \"m\", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;\n const url = isAbsoluteURL(path) ?\n new URL(path)\n : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query };\n }\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query);\n }\n return url.toString();\n }\n _calculateNonstreamingTimeout(maxTokens) {\n const defaultTimeout = 10 * 60;\n const expectedTimeout = (60 * 60 * maxTokens) / 128000;\n if (expectedTimeout > defaultTimeout) {\n throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +\n 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');\n }\n return defaultTimeout * 1000;\n }\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n async prepareOptions(options) { }\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n async prepareRequest(request, { url, options }) { }\n get(path, opts) {\n return this.methodRequest('get', path, opts);\n }\n post(path, opts) {\n return this.methodRequest('post', path, opts);\n }\n patch(path, opts) {\n return this.methodRequest('patch', path, opts);\n }\n put(path, opts) {\n return this.methodRequest('put', path, opts);\n }\n delete(path, opts) {\n return this.methodRequest('delete', path, opts);\n }\n methodRequest(method, path, opts) {\n return this.request(Promise.resolve(opts).then((opts) => {\n return { method, path, ...opts };\n }));\n }\n request(options, remainingRetries = null) {\n return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));\n }\n async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n await this.prepareOptions(options);\n const { req, url, timeout } = await this.buildRequest(options, {\n retryCount: maxRetries - retriesRemaining,\n });\n await this.prepareRequest(req, { url, options });\n /** Not an API request ID, just for correlating local log entries. */\n const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');\n const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;\n const startTime = Date.now();\n loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({\n retryOfRequestLogID,\n method: options.method,\n url,\n options,\n headers: req.headers,\n }));\n if (options.signal?.aborted) {\n throw new Errors.APIUserAbortError();\n }\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n const headersTime = Date.now();\n if (response instanceof globalThis.Error) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n if (options.signal?.aborted) {\n throw new Errors.APIUserAbortError();\n }\n // detect native connection timeout errors\n // deno throws \"TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)\"\n // undici throws \"TypeError: fetch failed\" with cause \"ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)\"\n // others do not provide enough information to distinguish timeouts from other connection errors\n const isTimeout = isAbortError(response) ||\n /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));\n if (retriesRemaining) {\n loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);\n loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }));\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);\n }\n loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);\n loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }));\n if (isTimeout) {\n throw new Errors.APIConnectionTimeoutError();\n }\n throw new Errors.APIConnectionError({ cause: response });\n }\n const specialHeaders = [...response.headers.entries()]\n .filter(([name]) => name === 'request-id')\n .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))\n .join('');\n const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;\n if (!response.ok) {\n const shouldRetry = await this.shouldRetry(response);\n if (retriesRemaining && shouldRetry) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n // We don't need the body of this response.\n await Shims.CancelReadableStream(response.body);\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n durationMs: headersTime - startTime,\n }));\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);\n }\n const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n const errText = await response.text().catch((err) => castToError(err).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n message: errMessage,\n durationMs: Date.now() - startTime,\n }));\n const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);\n throw err;\n }\n loggerFor(this).info(responseInfo);\n loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n durationMs: headersTime - startTime,\n }));\n return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };\n }\n getAPIList(path, Page, opts) {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n requestAPIList(Page, options) {\n const request = this.makeRequest(options, null, undefined);\n return new Pagination.PagePromise(this, request, Page);\n }\n async fetchWithTimeout(url, init, ms, controller) {\n const { signal, method, ...options } = init || {};\n if (signal)\n signal.addEventListener('abort', () => controller.abort());\n const timeout = setTimeout(() => controller.abort(), ms);\n const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||\n (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);\n const fetchOptions = {\n signal: controller.signal,\n ...(isReadableBody ? { duplex: 'half' } : {}),\n method: 'GET',\n ...options,\n };\n if (method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = method.toUpperCase();\n }\n try {\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n return await this.fetch.call(undefined, url, fetchOptions);\n }\n finally {\n clearTimeout(timeout);\n }\n }\n async shouldRetry(response) {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true')\n return true;\n if (shouldRetryHeader === 'false')\n return false;\n // Retry on request timeouts.\n if (response.status === 408)\n return true;\n // Retry on lock timeouts.\n if (response.status === 409)\n return true;\n // Retry on rate limits.\n if (response.status === 429)\n return true;\n // Retry internal errors.\n if (response.status >= 500)\n return true;\n return false;\n }\n async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {\n let timeoutMillis;\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.get('retry-after');\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n }\n else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n return this.makeRequest(options, retriesRemaining - 1, requestLogID);\n }\n calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n const numRetries = maxRetries - retriesRemaining;\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n return sleepSeconds * jitter * 1000;\n }\n calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {\n const maxTime = 60 * 60 * 1000; // 60 minutes\n const defaultTime = 60 * 10 * 1000; // 10 minutes\n const expectedTime = (maxTime * maxTokens) / 128000;\n if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {\n throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details');\n }\n return defaultTime;\n }\n async buildRequest(inputOptions, { retryCount = 0 } = {}) {\n const options = { ...inputOptions };\n const { method, path, query, defaultBaseURL } = options;\n const url = this.buildURL(path, query, defaultBaseURL);\n if ('timeout' in options)\n validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const { bodyHeaders, body } = this.buildBody({ options });\n const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });\n const req = {\n method,\n headers: reqHeaders,\n ...(options.signal && { signal: options.signal }),\n ...(globalThis.ReadableStream &&\n body instanceof globalThis.ReadableStream && { duplex: 'half' }),\n ...(body && { body }),\n ...(this.fetchOptions ?? {}),\n ...(options.fetchOptions ?? {}),\n };\n return { req, url, timeout: options.timeout };\n }\n async buildHeaders({ options, method, bodyHeaders, retryCount, }) {\n let idempotencyHeaders = {};\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey)\n options.idempotencyKey = this.defaultIdempotencyKey();\n idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;\n }\n const headers = buildHeaders([\n idempotencyHeaders,\n {\n Accept: 'application/json',\n 'User-Agent': this.getUserAgent(),\n 'X-Stainless-Retry-Count': String(retryCount),\n ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),\n ...getPlatformHeaders(),\n ...(this._options.dangerouslyAllowBrowser ?\n { 'anthropic-dangerous-direct-browser-access': 'true' }\n : undefined),\n 'anthropic-version': '2023-06-01',\n },\n await this.authHeaders(options),\n this._options.defaultHeaders,\n bodyHeaders,\n options.headers,\n ]);\n this.validateHeaders(headers);\n return headers.values;\n }\n buildBody({ options: { body, headers: rawHeaders } }) {\n if (!body) {\n return { bodyHeaders: undefined, body: undefined };\n }\n const headers = buildHeaders([rawHeaders]);\n if (\n // Pass raw type verbatim\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof DataView ||\n (typeof body === 'string' &&\n // Preserve legacy string encoding behavior for now\n headers.values.has('content-type')) ||\n // `Blob` is superset of `File`\n (globalThis.Blob && body instanceof globalThis.Blob) ||\n // `FormData` -> `multipart/form-data`\n body instanceof FormData ||\n // `URLSearchParams` -> `application/x-www-form-urlencoded`\n body instanceof URLSearchParams ||\n // Send chunked stream (each chunk has own `length`)\n (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {\n return { bodyHeaders: undefined, body: body };\n }\n else if (typeof body === 'object' &&\n (Symbol.asyncIterator in body ||\n (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {\n return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };\n }\n else {\n return __classPrivateFieldGet(this, _BaseAnthropic_encoder, \"f\").call(this, { body, headers });\n }\n }\n}\n_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {\n return this.baseURL !== 'https://api.anthropic.com';\n};\nBaseAnthropic.Anthropic = _a;\nBaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT;\nBaseAnthropic.AI_PROMPT = AI_PROMPT;\nBaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes\nBaseAnthropic.AnthropicError = Errors.AnthropicError;\nBaseAnthropic.APIError = Errors.APIError;\nBaseAnthropic.APIConnectionError = Errors.APIConnectionError;\nBaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\nBaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;\nBaseAnthropic.NotFoundError = Errors.NotFoundError;\nBaseAnthropic.ConflictError = Errors.ConflictError;\nBaseAnthropic.RateLimitError = Errors.RateLimitError;\nBaseAnthropic.BadRequestError = Errors.BadRequestError;\nBaseAnthropic.AuthenticationError = Errors.AuthenticationError;\nBaseAnthropic.InternalServerError = Errors.InternalServerError;\nBaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;\nBaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;\nBaseAnthropic.toFile = Uploads.toFile;\n/**\n * API Client for interfacing with the Anthropic API.\n */\nexport class Anthropic extends BaseAnthropic {\n constructor() {\n super(...arguments);\n this.completions = new API.Completions(this);\n this.messages = new API.Messages(this);\n this.models = new API.Models(this);\n this.beta = new API.Beta(this);\n }\n}\nAnthropic.Completions = Completions;\nAnthropic.Messages = Messages;\nAnthropic.Models = Models;\nAnthropic.Beta = Beta;\n//# sourceMappingURL=client.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport { Anthropic as default } from \"./client.mjs\";\nexport { toFile } from \"./core/uploads.mjs\";\nexport { APIPromise } from \"./core/api-promise.mjs\";\nexport { BaseAnthropic, Anthropic, HUMAN_PROMPT, AI_PROMPT } from \"./client.mjs\";\nexport { PagePromise } from \"./core/pagination.mjs\";\nexport { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from \"./core/error.mjs\";\n//# sourceMappingURL=index.mjs.map","import { AnthropicToolsOutputParser } from \"./output_parsers.js\";\nimport { handleToolChoice } from \"./utils/tools.js\";\nimport { _convertMessagesToAnthropicPayload } from \"./utils/message_inputs.js\";\nimport { _makeMessageChunkFromAnthropicEvent, anthropicResponseToChatMessages } from \"./utils/message_outputs.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\nimport { Anthropic as Anthropic$1 } from \"@anthropic-ai/sdk\";\nimport { AIMessageChunk } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport { RunnablePassthrough, RunnableSequence } from \"@langchain/core/runnables\";\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\n\n//#region src/chat_models.ts\nconst MODEL_DEFAULT_MAX_OUTPUT_TOKENS = {\n\t\"claude-opus-4-1\": 8192,\n\t\"claude-opus-4\": 8192,\n\t\"claude-sonnet-4\": 8192,\n\t\"claude-sonnet-3-7-sonnet\": 8192,\n\t\"claude-3-5-sonnet\": 4096,\n\t\"claude-3-5-haiku\": 4096,\n\t\"claude-3-haiku\": 2048\n};\nconst FALLBACK_MAX_OUTPUT_TOKENS = 2048;\nfunction defaultMaxOutputTokensForModel(model) {\n\tif (!model) return FALLBACK_MAX_OUTPUT_TOKENS;\n\tconst maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1];\n\treturn maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS;\n}\nfunction _toolsInParams(params) {\n\treturn !!(params.tools && params.tools.length > 0);\n}\nfunction _documentsInParams(params) {\n\tfor (const message of params.messages ?? []) {\n\t\tif (typeof message.content === \"string\") continue;\n\t\tfor (const block of message.content ?? []) if (typeof block === \"object\" && block != null && block.type === \"document\" && typeof block.citations === \"object\" && block.citations?.enabled) return true;\n\t}\n\treturn false;\n}\nfunction _thinkingInParams(params) {\n\treturn !!(params.thinking && params.thinking.type === \"enabled\");\n}\nfunction isAnthropicTool(tool) {\n\treturn \"input_schema\" in tool;\n}\nfunction isBuiltinTool(tool) {\n\tconst builtInToolPrefixes = [\n\t\t\"text_editor_\",\n\t\t\"computer_\",\n\t\t\"bash_\",\n\t\t\"web_search_\",\n\t\t\"web_fetch_\",\n\t\t\"str_replace_editor_\",\n\t\t\"str_replace_based_edit_tool_\",\n\t\t\"code_execution_\",\n\t\t\"memory_\"\n\t];\n\treturn typeof tool === \"object\" && tool !== null && \"type\" in tool && \"name\" in tool && typeof tool.type === \"string\" && builtInToolPrefixes.some((prefix) => typeof tool.type === \"string\" && tool.type.startsWith(prefix));\n}\nfunction extractToken(chunk) {\n\tif (typeof chunk.content === \"string\") return chunk.content;\n\telse if (Array.isArray(chunk.content) && chunk.content.length >= 1 && \"input\" in chunk.content[0]) return typeof chunk.content[0].input === \"string\" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input);\n\telse if (Array.isArray(chunk.content) && chunk.content.length >= 1 && \"text\" in chunk.content[0] && typeof chunk.content[0].text === \"string\") return chunk.content[0].text;\n\treturn void 0;\n}\n/**\n* Anthropic chat model integration.\n*\n* Setup:\n* Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.\n*\n* ```bash\n* npm install @langchain/anthropic\n* export ANTHROPIC_API_KEY=\"your-api-key\"\n* ```\n*\n* ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)\n*\n* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)\n*\n* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:\n*\n* ```typescript\n* // When calling `.bind`, call options should be passed via the first argument\n* const llmWithArgsBound = llm.bindTools([...]).withConfig({\n* stop: [\"\\n\"],\n* });\n*\n* // When calling `.bindTools`, call options should be passed via the second argument\n* const llmWithTools = llm.bindTools(\n* [...],\n* {\n* tool_choice: \"auto\",\n* }\n* );\n* ```\n*\n* ## Examples\n*\n*
\n* Instantiate\n*\n* ```typescript\n* import { ChatAnthropic } from '@langchain/anthropic';\n*\n* const llm = new ChatAnthropic({\n* model: \"claude-sonnet-4-5-20250929\",\n* temperature: 0,\n* maxTokens: undefined,\n* maxRetries: 2,\n* // apiKey: \"...\",\n* // baseUrl: \"...\",\n* // other params...\n* });\n* ```\n*
\n*\n*
\n*\n*
\n* Invoking\n*\n* ```typescript\n* const input = `Translate \"I love programming\" into French.`;\n*\n* // Models also accept a list of chat messages or a formatted prompt\n* const result = await llm.invoke(input);\n* console.log(result);\n* ```\n*\n* ```txt\n* AIMessage {\n* \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n* \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n* \"response_metadata\": {\n* \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n* \"model\": \"claude-sonnet-4-5-20250929\",\n* \"stop_reason\": \"end_turn\",\n* \"stop_sequence\": null,\n* \"usage\": {\n* \"input_tokens\": 25,\n* \"output_tokens\": 19\n* },\n* \"type\": \"message\",\n* \"role\": \"assistant\"\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 25,\n* \"output_tokens\": 19,\n* \"total_tokens\": 44\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Streaming Chunks\n*\n* ```typescript\n* for await (const chunk of await llm.stream(input)) {\n* console.log(chunk);\n* }\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n* \"content\": \"\",\n* \"additional_kwargs\": {\n* \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n* \"type\": \"message\",\n* \"role\": \"assistant\",\n* \"model\": \"claude-sonnet-4-5-20250929\"\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 25,\n* \"output_tokens\": 1,\n* \"total_tokens\": 26\n* }\n* }\n* AIMessageChunk {\n* \"content\": \"\",\n* }\n* AIMessageChunk {\n* \"content\": \"Here\",\n* }\n* AIMessageChunk {\n* \"content\": \"'s\",\n* }\n* AIMessageChunk {\n* \"content\": \" the translation to\",\n* }\n* AIMessageChunk {\n* \"content\": \" French:\\n\\nJ\",\n* }\n* AIMessageChunk {\n* \"content\": \"'adore la programmation\",\n* }\n* AIMessageChunk {\n* \"content\": \".\",\n* }\n* AIMessageChunk {\n* \"content\": \"\",\n* \"additional_kwargs\": {\n* \"stop_reason\": \"end_turn\",\n* \"stop_sequence\": null\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 0,\n* \"output_tokens\": 19,\n* \"total_tokens\": 19\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Aggregate Streamed Chunks\n*\n* ```typescript\n* import { AIMessageChunk } from '@langchain/core/messages';\n* import { concat } from '@langchain/core/utils/stream';\n*\n* const stream = await llm.stream(input);\n* let full: AIMessageChunk | undefined;\n* for await (const chunk of stream) {\n* full = !full ? chunk : concat(full, chunk);\n* }\n* console.log(full);\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n* \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n* \"additional_kwargs\": {\n* \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n* \"type\": \"message\",\n* \"role\": \"assistant\",\n* \"model\": \"claude-sonnet-4-5-20250929\",\n* \"stop_reason\": \"end_turn\",\n* \"stop_sequence\": null\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 25,\n* \"output_tokens\": 20,\n* \"total_tokens\": 45\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Bind tools\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const GetWeather = {\n* name: \"GetWeather\",\n* description: \"Get the current weather in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const GetPopulation = {\n* name: \"GetPopulation\",\n* description: \"Get the current population in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n* const aiMsg = await llmWithTools.invoke(\n* \"Which city is hotter today and which is bigger: LA or NY?\"\n* );\n* console.log(aiMsg.tool_calls);\n* ```\n*\n* ```txt\n* [\n* {\n* name: 'GetWeather',\n* args: { location: 'Los Angeles, CA' },\n* id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',\n* type: 'tool_call'\n* },\n* {\n* name: 'GetWeather',\n* args: { location: 'New York, NY' },\n* id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',\n* type: 'tool_call'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'Los Angeles, CA' },\n* id: 'toolu_0165qYWBA2VFyUst5RA18zew',\n* type: 'tool_call'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'New York, NY' },\n* id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',\n* type: 'tool_call'\n* }\n* ]\n* ```\n*
\n*\n*
\n*\n*
\n* Structured Output\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const Joke = z.object({\n* setup: z.string().describe(\"The setup of the joke\"),\n* punchline: z.string().describe(\"The punchline to the joke\"),\n* rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n* }).describe('Joke to tell user.');\n*\n* const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n* const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n* console.log(jokeResult);\n* ```\n*\n* ```txt\n* {\n* setup: \"Why don't cats play poker in the jungle?\",\n* punchline: 'Too many cheetahs!',\n* rating: 7\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Multimodal\n*\n* ```typescript\n* import { HumanMessage } from '@langchain/core/messages';\n*\n* const imageUrl = \"https://example.com/image.jpg\";\n* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n* const base64Image = Buffer.from(imageData).toString('base64');\n*\n* const message = new HumanMessage({\n* content: [\n* { type: \"text\", text: \"describe the weather in this image\" },\n* {\n* type: \"image_url\",\n* image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n* },\n* ]\n* });\n*\n* const imageDescriptionAiMsg = await llm.invoke([message]);\n* console.log(imageDescriptionAiMsg.content);\n* ```\n*\n* ```txt\n* The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth.\n* ```\n*
\n*\n*
\n*\n*
\n* Usage Metadata\n*\n* ```typescript\n* const aiMsgForMetadata = await llm.invoke(input);\n* console.log(aiMsgForMetadata.usage_metadata);\n* ```\n*\n* ```txt\n* { input_tokens: 25, output_tokens: 19, total_tokens: 44 }\n* ```\n*
\n*\n*
\n*\n*
\n* Stream Usage Metadata\n*\n* ```typescript\n* const streamForMetadata = await llm.stream(\n* input,\n* {\n* streamUsage: true\n* }\n* );\n* let fullForMetadata: AIMessageChunk | undefined;\n* for await (const chunk of streamForMetadata) {\n* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n* }\n* console.log(fullForMetadata?.usage_metadata);\n* ```\n*\n* ```txt\n* { input_tokens: 25, output_tokens: 20, total_tokens: 45 }\n* ```\n*
\n*\n*
\n*\n*
\n* Response Metadata\n*\n* ```typescript\n* const aiMsgForResponseMetadata = await llm.invoke(input);\n* console.log(aiMsgForResponseMetadata.response_metadata);\n* ```\n*\n* ```txt\n* {\n* id: 'msg_01STxeQxJmp4sCSpioD6vK3L',\n* model: 'claude-sonnet-4-5-20250929',\n* stop_reason: 'end_turn',\n* stop_sequence: null,\n* usage: { input_tokens: 25, output_tokens: 19 },\n* type: 'message',\n* role: 'assistant'\n* }\n* ```\n*
\n*\n*
\n*/\nvar ChatAnthropicMessages = class extends BaseChatModel {\n\tstatic lc_name() {\n\t\treturn \"ChatAnthropic\";\n\t}\n\tget lc_secrets() {\n\t\treturn {\n\t\t\tanthropicApiKey: \"ANTHROPIC_API_KEY\",\n\t\t\tapiKey: \"ANTHROPIC_API_KEY\"\n\t\t};\n\t}\n\tget lc_aliases() {\n\t\treturn { modelName: \"model\" };\n\t}\n\tlc_serializable = true;\n\tanthropicApiKey;\n\tapiKey;\n\tapiUrl;\n\ttemperature;\n\ttopK;\n\ttopP;\n\tmaxTokens;\n\tmodelName = \"claude-3-5-sonnet-latest\";\n\tmodel = \"claude-3-5-sonnet-latest\";\n\tinvocationKwargs;\n\tstopSequences;\n\tstreaming = false;\n\tclientOptions;\n\tthinking = { type: \"disabled\" };\n\tcontextManagement;\n\tbatchClient;\n\tstreamingClient;\n\tstreamUsage = true;\n\t/**\n\t* Optional method that returns an initialized underlying Anthropic client.\n\t* Useful for accessing Anthropic models hosted on other cloud services\n\t* such as Google Vertex.\n\t*/\n\tcreateClient;\n\tconstructor(fields) {\n\t\tsuper(fields ?? {});\n\t\tthis.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable(\"ANTHROPIC_API_KEY\");\n\t\tif (!this.anthropicApiKey && !fields?.createClient) throw new Error(\"Anthropic API key not found\");\n\t\tthis.clientOptions = fields?.clientOptions ?? {};\n\t\t/** Keep anthropicApiKey for backwards compatibility */\n\t\tthis.apiKey = this.anthropicApiKey;\n\t\tthis.apiUrl = fields?.anthropicApiUrl;\n\t\t/** Keep modelName for backwards compatibility */\n\t\tthis.modelName = fields?.model ?? fields?.modelName ?? this.model;\n\t\tthis.model = this.modelName;\n\t\tthis.invocationKwargs = fields?.invocationKwargs ?? {};\n\t\tthis.topP = fields?.topP ?? this.topP;\n\t\tthis.temperature = fields?.temperature ?? this.temperature;\n\t\tthis.topK = fields?.topK ?? this.topK;\n\t\tthis.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model);\n\t\tthis.stopSequences = fields?.stopSequences ?? this.stopSequences;\n\t\tthis.streaming = fields?.streaming ?? false;\n\t\tthis.streamUsage = fields?.streamUsage ?? this.streamUsage;\n\t\tthis.thinking = fields?.thinking ?? this.thinking;\n\t\tthis.contextManagement = fields?.contextManagement ?? this.contextManagement;\n\t\tthis.createClient = fields?.createClient ?? ((options) => new Anthropic$1(options));\n\t}\n\tgetLsParams(options) {\n\t\tconst params = this.invocationParams(options);\n\t\treturn {\n\t\t\tls_provider: \"anthropic\",\n\t\t\tls_model_name: this.model,\n\t\t\tls_model_type: \"chat\",\n\t\t\tls_temperature: params.temperature ?? void 0,\n\t\t\tls_max_tokens: params.max_tokens ?? void 0,\n\t\t\tls_stop: options.stop\n\t\t};\n\t}\n\t/**\n\t* Formats LangChain StructuredTools to AnthropicTools.\n\t*\n\t* @param {ChatAnthropicCallOptions[\"tools\"]} tools The tools to format\n\t* @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.\n\t*/\n\tformatStructuredToolToAnthropic(tools) {\n\t\tif (!tools || !tools.length) return void 0;\n\t\treturn tools.map((tool) => {\n\t\t\tif (isBuiltinTool(tool)) return tool;\n\t\t\tif (isAnthropicTool(tool)) return tool;\n\t\t\tif (isOpenAITool(tool)) return {\n\t\t\t\tname: tool.function.name,\n\t\t\t\tdescription: tool.function.description,\n\t\t\t\tinput_schema: tool.function.parameters\n\t\t\t};\n\t\t\tif (isLangChainTool(tool)) return {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tinput_schema: isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema\n\t\t\t};\n\t\t\tthrow new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`);\n\t\t});\n\t}\n\tbindTools(tools, kwargs) {\n\t\treturn this.withConfig({\n\t\t\ttools: this.formatStructuredToolToAnthropic(tools),\n\t\t\t...kwargs\n\t\t});\n\t}\n\t/**\n\t* Get the parameters used to invoke the model\n\t*/\n\tinvocationParams(options) {\n\t\tconst tool_choice = handleToolChoice(options?.tool_choice);\n\t\tif (this.thinking.type === \"enabled\") {\n\t\t\tif (this.topP !== void 0 && this.topK !== -1) throw new Error(\"topK is not supported when thinking is enabled\");\n\t\t\tif (this.temperature !== void 0 && this.temperature !== 1) throw new Error(\"temperature is not supported when thinking is enabled\");\n\t\t\treturn {\n\t\t\t\tmodel: this.model,\n\t\t\t\tstop_sequences: options?.stop ?? this.stopSequences,\n\t\t\t\tstream: this.streaming,\n\t\t\t\tmax_tokens: this.maxTokens,\n\t\t\t\ttools: this.formatStructuredToolToAnthropic(options?.tools),\n\t\t\t\ttool_choice,\n\t\t\t\tthinking: this.thinking,\n\t\t\t\tcontext_management: this.contextManagement,\n\t\t\t\t...this.invocationKwargs,\n\t\t\t\tcontainer: options?.container\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmodel: this.model,\n\t\t\ttemperature: this.temperature,\n\t\t\ttop_k: this.topK,\n\t\t\ttop_p: this.topP,\n\t\t\tstop_sequences: options?.stop ?? this.stopSequences,\n\t\t\tstream: this.streaming,\n\t\t\tmax_tokens: this.maxTokens,\n\t\t\ttools: this.formatStructuredToolToAnthropic(options?.tools),\n\t\t\ttool_choice,\n\t\t\tthinking: this.thinking,\n\t\t\tcontext_management: this.contextManagement,\n\t\t\t...this.invocationKwargs,\n\t\t\tcontainer: options?.container\n\t\t};\n\t}\n\t/** @ignore */\n\t_identifyingParams() {\n\t\treturn {\n\t\t\tmodel_name: this.model,\n\t\t\t...this.invocationParams()\n\t\t};\n\t}\n\t/**\n\t* Get the identifying parameters for the model\n\t*/\n\tidentifyingParams() {\n\t\treturn {\n\t\t\tmodel_name: this.model,\n\t\t\t...this.invocationParams()\n\t\t};\n\t}\n\tasync *_streamResponseChunks(messages, options, runManager) {\n\t\tconst params = this.invocationParams(options);\n\t\tconst formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\t\tconst payload = {\n\t\t\t...params,\n\t\t\t...formattedMessages,\n\t\t\tstream: true\n\t\t};\n\t\tconst coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload);\n\t\tconst stream = await this.createStreamWithRetry(payload, { headers: options.headers });\n\t\tfor await (const data of stream) {\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tstream.controller.abort();\n\t\t\t\tthrow new Error(\"AbortError: User aborted the request.\");\n\t\t\t}\n\t\t\tconst shouldStreamUsage = this.streamUsage ?? options.streamUsage;\n\t\t\tconst result = _makeMessageChunkFromAnthropicEvent(data, {\n\t\t\t\tstreamUsage: shouldStreamUsage,\n\t\t\t\tcoerceContentToString\n\t\t\t});\n\t\t\tif (!result) continue;\n\t\t\tconst { chunk } = result;\n\t\t\tconst token = extractToken(chunk);\n\t\t\tconst generationChunk = new ChatGenerationChunk({\n\t\t\t\tmessage: new AIMessageChunk({\n\t\t\t\t\tcontent: chunk.content,\n\t\t\t\t\tadditional_kwargs: chunk.additional_kwargs,\n\t\t\t\t\ttool_call_chunks: chunk.tool_call_chunks,\n\t\t\t\t\tusage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0,\n\t\t\t\t\tresponse_metadata: chunk.response_metadata,\n\t\t\t\t\tid: chunk.id\n\t\t\t\t}),\n\t\t\t\ttext: token ?? \"\"\n\t\t\t});\n\t\t\tyield generationChunk;\n\t\t\tawait runManager?.handleLLMNewToken(token ?? \"\", void 0, void 0, void 0, void 0, { chunk: generationChunk });\n\t\t}\n\t}\n\t/** @ignore */\n\tasync _generateNonStreaming(messages, params, requestOptions) {\n\t\tconst response = await this.completionWithRetry({\n\t\t\t...params,\n\t\t\tstream: false,\n\t\t\t..._convertMessagesToAnthropicPayload(messages)\n\t\t}, requestOptions);\n\t\tconst { content,...additionalKwargs } = response;\n\t\tconst generations = anthropicResponseToChatMessages(content, additionalKwargs);\n\t\tconst { role: _role, type: _type,...rest } = additionalKwargs;\n\t\treturn {\n\t\t\tgenerations,\n\t\t\tllmOutput: rest\n\t\t};\n\t}\n\t/** @ignore */\n\tasync _generate(messages, options, runManager) {\n\t\tif (this.stopSequences && options.stop) throw new Error(`\"stopSequence\" parameter found in input and default params`);\n\t\tconst params = this.invocationParams(options);\n\t\tif (params.stream) {\n\t\t\tlet finalChunk;\n\t\t\tconst stream = this._streamResponseChunks(messages, options, runManager);\n\t\t\tfor await (const chunk of stream) if (finalChunk === void 0) finalChunk = chunk;\n\t\t\telse finalChunk = finalChunk.concat(chunk);\n\t\t\tif (finalChunk === void 0) throw new Error(\"No chunks returned from Anthropic API.\");\n\t\t\treturn { generations: [{\n\t\t\t\ttext: finalChunk.text,\n\t\t\t\tmessage: finalChunk.message\n\t\t\t}] };\n\t\t} else return this._generateNonStreaming(messages, params, {\n\t\t\tsignal: options.signal,\n\t\t\theaders: options.headers\n\t\t});\n\t}\n\t/**\n\t* Creates a streaming request with retry.\n\t* @param request The parameters for creating a completion.\n\t* @param options\n\t* @returns A streaming request.\n\t*/\n\tasync createStreamWithRetry(request, options) {\n\t\tif (!this.streamingClient) {\n\t\t\tconst options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0;\n\t\t\tthis.streamingClient = this.createClient({\n\t\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t\t...this.clientOptions,\n\t\t\t\t...options_,\n\t\t\t\tapiKey: this.apiKey,\n\t\t\t\tmaxRetries: 0\n\t\t\t});\n\t\t}\n\t\tconst makeCompletionRequest = async () => {\n\t\t\ttry {\n\t\t\t\treturn await this.streamingClient.messages.create({\n\t\t\t\t\t...request,\n\t\t\t\t\t...this.invocationKwargs,\n\t\t\t\t\tstream: true\n\t\t\t\t}, options);\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapAnthropicClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\t\treturn this.caller.call(makeCompletionRequest);\n\t}\n\t/** @ignore */\n\tasync completionWithRetry(request, options) {\n\t\tif (!this.batchClient) {\n\t\t\tconst options$1 = this.apiUrl ? { baseURL: this.apiUrl } : void 0;\n\t\t\tthis.batchClient = this.createClient({\n\t\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t\t...this.clientOptions,\n\t\t\t\t...options$1,\n\t\t\t\tapiKey: this.apiKey,\n\t\t\t\tmaxRetries: 0\n\t\t\t});\n\t\t}\n\t\tconst makeCompletionRequest = async () => {\n\t\t\ttry {\n\t\t\t\treturn await this.batchClient.messages.create({\n\t\t\t\t\t...request,\n\t\t\t\t\t...this.invocationKwargs\n\t\t\t\t}, options);\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapAnthropicClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\t\treturn this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest);\n\t}\n\t_llmType() {\n\t\treturn \"anthropic\";\n\t}\n\twithStructuredOutput(outputSchema, config) {\n\t\tconst schema = outputSchema;\n\t\tconst name = config?.name;\n\t\tconst method = config?.method;\n\t\tconst includeRaw = config?.includeRaw;\n\t\tif (method === \"jsonMode\") throw new Error(`Anthropic only supports \"functionCalling\" as a method.`);\n\t\tlet functionName = name ?? \"extract\";\n\t\tlet outputParser;\n\t\tlet tools;\n\t\tif (isInteropZodSchema(schema)) {\n\t\t\tconst jsonSchema = toJsonSchema(schema);\n\t\t\ttools = [{\n\t\t\t\tname: functionName,\n\t\t\t\tdescription: jsonSchema.description ?? \"A function available to call.\",\n\t\t\t\tinput_schema: jsonSchema\n\t\t\t}];\n\t\t\toutputParser = new AnthropicToolsOutputParser({\n\t\t\t\treturnSingle: true,\n\t\t\t\tkeyName: functionName,\n\t\t\t\tzodSchema: schema\n\t\t\t});\n\t\t} else {\n\t\t\tlet anthropicTools;\n\t\t\tif (typeof schema.name === \"string\" && typeof schema.description === \"string\" && typeof schema.input_schema === \"object\" && schema.input_schema != null) {\n\t\t\t\tanthropicTools = schema;\n\t\t\t\tfunctionName = schema.name;\n\t\t\t} else anthropicTools = {\n\t\t\t\tname: functionName,\n\t\t\t\tdescription: schema.description ?? \"\",\n\t\t\t\tinput_schema: schema\n\t\t\t};\n\t\t\ttools = [anthropicTools];\n\t\t\toutputParser = new AnthropicToolsOutputParser({\n\t\t\t\treturnSingle: true,\n\t\t\t\tkeyName: functionName\n\t\t\t});\n\t\t}\n\t\tlet llm;\n\t\tif (this.thinking?.type === \"enabled\") {\n\t\t\tconst thinkingAdmonition = \"Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.\";\n\t\t\tconsole.warn(thinkingAdmonition);\n\t\t\tllm = this.withConfig({\n\t\t\t\toutputVersion: \"v0\",\n\t\t\t\ttools,\n\t\t\t\tls_structured_output_format: {\n\t\t\t\t\tkwargs: { method: \"functionCalling\" },\n\t\t\t\t\tschema: toJsonSchema(schema)\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst raiseIfNoToolCalls = (message) => {\n\t\t\t\tif (!message.tool_calls || message.tool_calls.length === 0) throw new Error(thinkingAdmonition);\n\t\t\t\treturn message;\n\t\t\t};\n\t\t\tllm = llm.pipe(raiseIfNoToolCalls);\n\t\t} else llm = this.withConfig({\n\t\t\toutputVersion: \"v0\",\n\t\t\ttools,\n\t\t\ttool_choice: {\n\t\t\t\ttype: \"tool\",\n\t\t\t\tname: functionName\n\t\t\t},\n\t\t\tls_structured_output_format: {\n\t\t\t\tkwargs: { method: \"functionCalling\" },\n\t\t\t\tschema: toJsonSchema(schema)\n\t\t\t}\n\t\t});\n\t\tif (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: \"ChatAnthropicStructuredOutput\" });\n\t\tconst parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });\n\t\tconst parserNone = RunnablePassthrough.assign({ parsed: () => null });\n\t\tconst parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });\n\t\treturn RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: \"StructuredOutputRunnable\" });\n\t}\n};\nvar ChatAnthropic = class extends ChatAnthropicMessages {};\n\n//#endregion\nexport { ChatAnthropic, ChatAnthropicMessages };\n//# sourceMappingURL=chat_models.js.map","import { _convertMessagesToAnthropicPayload } from \"./message_inputs.js\";\n\n//#region src/utils/prompts.ts\n/**\n* Convert a formatted LangChain prompt (e.g. pulled from the hub) into\n* a format expected by Anthropic's JS SDK.\n*\n* Requires the \"@langchain/anthropic\" package to be installed in addition\n* to the Anthropic SDK.\n*\n* @example\n* ```ts\n* import { convertPromptToAnthropic } from \"langsmith/utils/hub/anthropic\";\n* import { pull } from \"langchain/hub\";\n*\n* import Anthropic from '@anthropic-ai/sdk';\n*\n* const prompt = await pull(\"jacob/joke-generator\");\n* const formattedPrompt = await prompt.invoke({\n* topic: \"cats\",\n* });\n*\n* const { system, messages } = convertPromptToAnthropic(formattedPrompt);\n*\n* const anthropicClient = new Anthropic({\n* apiKey: 'your_api_key',\n* });\n*\n* const anthropicResponse = await anthropicClient.messages.create({\n* model: \"claude-sonnet-4-5-20250929\",\n* max_tokens: 1024,\n* stream: false,\n* system,\n* messages,\n* });\n* ```\n* @param formattedPrompt\n* @returns A partial Anthropic payload.\n*/\nfunction convertPromptToAnthropic(formattedPrompt) {\n\tconst messages = formattedPrompt.toChatMessages();\n\tconst anthropicBody = _convertMessagesToAnthropicPayload(messages);\n\tif (anthropicBody.messages === void 0) anthropicBody.messages = [];\n\treturn anthropicBody;\n}\n\n//#endregion\nexport { convertPromptToAnthropic };\n//# sourceMappingURL=prompts.js.map","import { ChatAnthropic, ChatAnthropicMessages } from \"./chat_models.js\";\nimport { convertPromptToAnthropic } from \"./utils/prompts.js\";\n\nexport { ChatAnthropic, ChatAnthropicMessages, convertPromptToAnthropic };","import { ChatAnthropic } from '@langchain/anthropic';\nimport { BaseChatModel } from '@langchain/core/language_models/chat_models';\nimport { ILLMProvider, ProviderConfig } from './provider.interface.js';\n\n/**\n * Anthropic Claude provider implementation\n */\nexport class AnthropicProvider implements ILLMProvider {\n public readonly name = 'anthropic';\n private readonly apiKey: string;\n\n constructor(apiKey?: string) {\n this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || '';\n }\n\n public isConfigured(): boolean {\n return !!this.apiKey;\n }\n\n public getDefaultModel(): string {\n return 'claude-sonnet-4-5-20250929';\n }\n\n public getChatModel(config: ProviderConfig = {}): BaseChatModel {\n if (!this.isConfigured()) {\n throw new Error('Anthropic API key is not configured');\n }\n\n return new ChatAnthropic({\n apiKey: this.apiKey,\n modelName: config.model || this.getDefaultModel(),\n temperature: config.temperature ?? 0.2,\n maxTokens: config.maxTokens ?? 4000,\n });\n }\n}\n\n","import { ChatMessage } from \"@langchain/core/messages\";\n\n//#region src/utils/misc.ts\nconst iife = (fn) => fn();\nfunction isReasoningModel(model) {\n\tif (!model) return false;\n\tif (/^o\\d/.test(model ?? \"\")) return true;\n\tif (model.startsWith(\"gpt-5\") && !model.startsWith(\"gpt-5-chat\")) return true;\n\treturn false;\n}\nfunction extractGenericMessageCustomRole(message) {\n\tif (message.role !== \"system\" && message.role !== \"developer\" && message.role !== \"assistant\" && message.role !== \"user\" && message.role !== \"function\" && message.role !== \"tool\") console.warn(`Unknown message role: ${message.role}`);\n\treturn message.role;\n}\nfunction messageToOpenAIRole(message) {\n\tconst type = message._getType();\n\tswitch (type) {\n\t\tcase \"system\": return \"system\";\n\t\tcase \"ai\": return \"assistant\";\n\t\tcase \"human\": return \"user\";\n\t\tcase \"function\": return \"function\";\n\t\tcase \"tool\": return \"tool\";\n\t\tcase \"generic\":\n\t\t\tif (!ChatMessage.isInstance(message)) throw new Error(\"Invalid generic chat message\");\n\t\t\treturn extractGenericMessageCustomRole(message);\n\t\tdefault: throw new Error(`Unknown message type: ${type}`);\n\t}\n}\n\n//#endregion\nexport { iife, isReasoningModel, messageToOpenAIRole };\n//# sourceMappingURL=misc.js.map","import { iife } from \"./misc.js\";\n\n//#region src/utils/azure.ts\n/**\n* This function generates an endpoint URL for (Azure) OpenAI\n* based on the configuration parameters provided.\n*\n* @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint.\n*\n* @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI.\n* @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`.\n* @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI.\n* @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`.\n* @property {string} config.baseURL - Some other custom base path URL.\n* @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`.\n*\n* The function operates as follows:\n* - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`).\n* - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`).\n* - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters.\n* - If none of the above conditions are met, return any custom `baseURL`.\n* - The function returns the generated URL as a string, or undefined if no custom paths are specified.\n*\n* @throws Will throw an error if the necessary parameters for generating the URL are missing.\n*\n* @returns {string | undefined} The generated (Azure) OpenAI endpoint URL.\n*/\nfunction getEndpoint(config) {\n\tconst { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, azureADTokenProvider, azureOpenAIEndpoint } = config;\n\tif ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`;\n\tif ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIEndpoint && azureOpenAIApiDeploymentName) return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`;\n\tif (azureOpenAIApiKey || azureADTokenProvider) {\n\t\tif (!azureOpenAIApiInstanceName) throw new Error(\"azureOpenAIApiInstanceName is required when using azureOpenAIApiKey\");\n\t\tif (!azureOpenAIApiDeploymentName) throw new Error(\"azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey\");\n\t\treturn `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`;\n\t}\n\treturn baseURL;\n}\nfunction isHeaders(headers) {\n\treturn typeof Headers !== \"undefined\" && headers !== null && typeof headers === \"object\" && Object.prototype.toString.call(headers) === \"[object Headers]\";\n}\n/**\n* Normalizes various header formats into a consistent Record format.\n*\n* This function accepts headers in multiple formats and converts them to a\n* Record for consistent handling.\n*\n* @param headers - The headers to normalize. Can be:\n* - A Headers instance\n* - An array of [key, value] pairs\n* - A plain object with string keys\n* - A NullableHeaders-like object with a 'values' property containing Headers\n* - null or undefined\n* @returns A normalized Record containing the header key-value pairs\n*\n* @example\n* ```ts\n* // With Headers instance\n* const headers1 = new Headers([['content-type', 'application/json']]);\n* const normalized1 = normalizeHeaders(headers1);\n*\n* // With plain object\n* const headers2 = { 'content-type': 'application/json' };\n* const normalized2 = normalizeHeaders(headers2);\n*\n* // With array of pairs\n* const headers3 = [['content-type', 'application/json']];\n* const normalized3 = normalizeHeaders(headers3);\n* ```\n*/\nfunction normalizeHeaders(headers) {\n\tconst output = iife(() => {\n\t\tif (isHeaders(headers)) return headers;\n\t\telse if (Array.isArray(headers)) return new Headers(headers);\n\t\telse if (typeof headers === \"object\" && headers !== null && \"values\" in headers && isHeaders(headers.values)) return headers.values;\n\t\telse if (typeof headers === \"object\" && headers !== null) {\n\t\t\tconst entries = Object.entries(headers).filter(([, v]) => typeof v === \"string\").map(([k, v]) => [k, v]);\n\t\t\treturn new Headers(entries);\n\t\t}\n\t\treturn new Headers();\n\t});\n\treturn Object.fromEntries(output.entries());\n}\n\n//#endregion\nexport { getEndpoint, isHeaders, normalizeHeaders };\n//# sourceMappingURL=azure.js.map","import { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport { convertToOpenAITool, isLangChainTool } from \"@langchain/core/utils/function_calling\";\n\n//#region src/utils/tools.ts\n/**\n* Formats a tool in either OpenAI format, or LangChain structured tool format\n* into an OpenAI tool format. If the tool is already in OpenAI format, return without\n* any changes. If it is in LangChain structured tool format, convert it to OpenAI tool format\n* using OpenAI's `zodFunction` util, falling back to `convertToOpenAIFunction` if the parameters\n* returned from the `zodFunction` util are not defined.\n*\n* @param {BindToolsInput} tool The tool to convert to an OpenAI tool.\n* @param {Object} [fields] Additional fields to add to the OpenAI tool.\n* @returns {ToolDefinition} The inputted tool in OpenAI tool format.\n*/\nfunction _convertToOpenAITool(tool, fields) {\n\tlet toolDef;\n\tif (isLangChainTool(tool)) toolDef = convertToOpenAITool(tool);\n\telse toolDef = tool;\n\tif (fields?.strict !== void 0) toolDef.function.strict = fields.strict;\n\treturn toolDef;\n}\nfunction isAnyOfProp(prop) {\n\treturn prop.anyOf !== void 0 && Array.isArray(prop.anyOf);\n}\nfunction formatFunctionDefinitions(functions) {\n\tconst lines = [\"namespace functions {\", \"\"];\n\tfor (const f of functions) {\n\t\tif (f.description) lines.push(`// ${f.description}`);\n\t\tif (Object.keys(f.parameters.properties ?? {}).length > 0) {\n\t\t\tlines.push(`type ${f.name} = (_: {`);\n\t\t\tlines.push(formatObjectProperties(f.parameters, 0));\n\t\t\tlines.push(\"}) => any;\");\n\t\t} else lines.push(`type ${f.name} = () => any;`);\n\t\tlines.push(\"\");\n\t}\n\tlines.push(\"} // namespace functions\");\n\treturn lines.join(\"\\n\");\n}\nfunction formatObjectProperties(obj, indent) {\n\tconst lines = [];\n\tfor (const [name, param] of Object.entries(obj.properties ?? {})) {\n\t\tif (param.description && indent < 2) lines.push(`// ${param.description}`);\n\t\tif (obj.required?.includes(name)) lines.push(`${name}: ${formatType(param, indent)},`);\n\t\telse lines.push(`${name}?: ${formatType(param, indent)},`);\n\t}\n\treturn lines.map((line) => \" \".repeat(indent) + line).join(\"\\n\");\n}\nfunction formatType(param, indent) {\n\tif (isAnyOfProp(param)) return param.anyOf.map((v) => formatType(v, indent)).join(\" | \");\n\tswitch (param.type) {\n\t\tcase \"string\":\n\t\t\tif (param.enum) return param.enum.map((v) => `\"${v}\"`).join(\" | \");\n\t\t\treturn \"string\";\n\t\tcase \"number\":\n\t\t\tif (param.enum) return param.enum.map((v) => `${v}`).join(\" | \");\n\t\t\treturn \"number\";\n\t\tcase \"integer\":\n\t\t\tif (param.enum) return param.enum.map((v) => `${v}`).join(\" | \");\n\t\t\treturn \"number\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"null\": return \"null\";\n\t\tcase \"object\": return [\n\t\t\t\"{\",\n\t\t\tformatObjectProperties(param, indent + 2),\n\t\t\t\"}\"\n\t\t].join(\"\\n\");\n\t\tcase \"array\":\n\t\t\tif (param.items) return `${formatType(param.items, indent)}[]`;\n\t\t\treturn \"any[]\";\n\t\tdefault: return \"\";\n\t}\n}\nfunction formatToOpenAIToolChoice(toolChoice) {\n\tif (!toolChoice) return void 0;\n\telse if (toolChoice === \"any\" || toolChoice === \"required\") return \"required\";\n\telse if (toolChoice === \"auto\") return \"auto\";\n\telse if (toolChoice === \"none\") return \"none\";\n\telse if (typeof toolChoice === \"string\") return {\n\t\ttype: \"function\",\n\t\tfunction: { name: toolChoice }\n\t};\n\telse return toolChoice;\n}\nfunction isBuiltInTool(tool) {\n\treturn \"type\" in tool && tool.type !== \"function\";\n}\nfunction isBuiltInToolChoice(tool_choice) {\n\treturn tool_choice != null && typeof tool_choice === \"object\" && \"type\" in tool_choice && tool_choice.type !== \"function\";\n}\nfunction isCustomTool(tool) {\n\treturn typeof tool === \"object\" && tool !== null && \"metadata\" in tool && typeof tool.metadata === \"object\" && tool.metadata !== null && \"customTool\" in tool.metadata && typeof tool.metadata.customTool === \"object\" && tool.metadata.customTool !== null;\n}\nfunction isOpenAICustomTool(tool) {\n\treturn \"type\" in tool && tool.type === \"custom\" && \"custom\" in tool && typeof tool.custom === \"object\" && tool.custom !== null;\n}\nfunction parseCustomToolCall(rawToolCall) {\n\tif (rawToolCall.type !== \"custom_tool_call\") return void 0;\n\treturn {\n\t\t...rawToolCall,\n\t\ttype: \"tool_call\",\n\t\tcall_id: rawToolCall.id,\n\t\tid: rawToolCall.call_id,\n\t\tname: rawToolCall.name,\n\t\tisCustomTool: true,\n\t\targs: { input: rawToolCall.input }\n\t};\n}\nfunction isCustomToolCall(toolCall) {\n\treturn toolCall.type === \"tool_call\" && \"isCustomTool\" in toolCall && toolCall.isCustomTool === true;\n}\nfunction convertCompletionsCustomTool(tool) {\n\tconst getFormat = () => {\n\t\tif (!tool.custom.format) return void 0;\n\t\tif (tool.custom.format.type === \"grammar\") return {\n\t\t\ttype: \"grammar\",\n\t\t\tdefinition: tool.custom.format.grammar.definition,\n\t\t\tsyntax: tool.custom.format.grammar.syntax\n\t\t};\n\t\tif (tool.custom.format.type === \"text\") return { type: \"text\" };\n\t\treturn void 0;\n\t};\n\treturn {\n\t\ttype: \"custom\",\n\t\tname: tool.custom.name,\n\t\tdescription: tool.custom.description,\n\t\tformat: getFormat()\n\t};\n}\nfunction convertResponsesCustomTool(tool) {\n\tconst getFormat = () => {\n\t\tif (!tool.format) return void 0;\n\t\tif (tool.format.type === \"grammar\") return {\n\t\t\ttype: \"grammar\",\n\t\t\tgrammar: {\n\t\t\t\tdefinition: tool.format.definition,\n\t\t\t\tsyntax: tool.format.syntax\n\t\t\t}\n\t\t};\n\t\tif (tool.format.type === \"text\") return { type: \"text\" };\n\t\treturn void 0;\n\t};\n\treturn {\n\t\ttype: \"custom\",\n\t\tcustom: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tformat: getFormat()\n\t\t}\n\t};\n}\n\n//#endregion\nexport { _convertToOpenAITool, convertCompletionsCustomTool, convertResponsesCustomTool, formatFunctionDefinitions, formatToOpenAIToolChoice, isBuiltInTool, isBuiltInToolChoice, isCustomTool, isCustomToolCall, isOpenAICustomTool, parseCustomToolCall };\n//# sourceMappingURL=tools.js.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport function isAbortError(err) {\n return (typeof err === 'object' &&\n err !== null &&\n // Spec-compliant fetch implementations\n (('name' in err && err.name === 'AbortError') ||\n // Expo fetch\n ('message' in err && String(err.message).includes('FetchRequestCanceledException'))));\n}\nexport const castToError = (err) => {\n if (err instanceof Error)\n return err;\n if (typeof err === 'object' && err !== null) {\n try {\n if (Object.prototype.toString.call(err) === '[object Error]') {\n // @ts-ignore - not all envs have native support for cause yet\n const error = new Error(err.message, err.cause ? { cause: err.cause } : {});\n if (err.stack)\n error.stack = err.stack;\n // @ts-ignore - not all envs have native support for cause yet\n if (err.cause && !error.cause)\n error.cause = err.cause;\n if (err.name)\n error.name = err.name;\n return error;\n }\n }\n catch { }\n try {\n return new Error(JSON.stringify(err));\n }\n catch { }\n }\n return new Error(err);\n};\n//# sourceMappingURL=errors.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { castToError } from \"../internal/errors.mjs\";\nexport class OpenAIError extends Error {\n}\nexport class APIError extends OpenAIError {\n constructor(status, error, message, headers) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.requestID = headers?.get('x-request-id');\n this.error = error;\n const data = error;\n this.code = data?.['code'];\n this.param = data?.['param'];\n this.type = data?.['type'];\n }\n static makeMessage(status, error, message) {\n const msg = error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n static generate(status, errorResponse, message, headers) {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n const error = errorResponse?.['error'];\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n return new APIError(status, error, message, headers);\n }\n}\nexport class APIUserAbortError extends APIError {\n constructor({ message } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\nexport class APIConnectionError extends APIError {\n constructor({ message, cause }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause)\n this.cause = cause;\n }\n}\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\nexport class BadRequestError extends APIError {\n}\nexport class AuthenticationError extends APIError {\n}\nexport class PermissionDeniedError extends APIError {\n}\nexport class NotFoundError extends APIError {\n}\nexport class ConflictError extends APIError {\n}\nexport class UnprocessableEntityError extends APIError {\n}\nexport class RateLimitError extends APIError {\n}\nexport class InternalServerError extends APIError {\n}\nexport class LengthFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the length limit was reached`);\n }\n}\nexport class ContentFilterFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the request was rejected by the content filter`);\n }\n}\nexport class InvalidWebhookSignatureError extends Error {\n constructor(message) {\n super(message);\n }\n}\n//# sourceMappingURL=error.mjs.map","export * from \"./core/error.mjs\";\n//# sourceMappingURL=error.mjs.map","import { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from \"../error.mjs\";\nexport function isChatCompletionFunctionTool(tool) {\n return tool !== undefined && 'function' in tool && tool.function !== undefined;\n}\nexport function makeParseableResponseFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function makeParseableTextFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableResponseFormat(response_format) {\n return response_format?.['$brand'] === 'auto-parseable-response-format';\n}\nexport function makeParseableTool(tool, { parser, callback, }) {\n const obj = { ...tool };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableTool(tool) {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\nexport function maybeParseChatCompletion(completion, params) {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...completion,\n choices: completion.choices.map((choice) => {\n assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls);\n return {\n ...choice,\n message: {\n ...choice.message,\n parsed: null,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls,\n }\n : undefined),\n },\n };\n }),\n };\n }\n return parseChatCompletion(completion, params);\n}\nexport function parseChatCompletion(completion, params) {\n const choices = completion.choices.map((choice) => {\n if (choice.finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (choice.finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls);\n return {\n ...choice,\n message: {\n ...choice.message,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined,\n }\n : undefined),\n parsed: choice.message.content && !choice.message.refusal ?\n parseResponseFormat(params, choice.message.content)\n : null,\n },\n };\n });\n return { ...completion, choices };\n}\nfunction parseResponseFormat(params, content) {\n if (params.response_format?.type !== 'json_schema') {\n return null;\n }\n if (params.response_format?.type === 'json_schema') {\n if ('$parseRaw' in params.response_format) {\n const response_format = params.response_format;\n return response_format.$parseRaw(content);\n }\n return JSON.parse(content);\n }\n return null;\n}\nfunction parseToolCall(params, toolCall) {\n const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); // TS doesn't narrow based on isChatCompletionTool\n return {\n ...toolCall,\n function: {\n ...toolCall.function,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)\n : null,\n },\n };\n}\nexport function shouldParseToolCall(params, toolCall) {\n if (!params || !('tools' in params) || !params.tools) {\n return false;\n }\n const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name);\n return (isChatCompletionFunctionTool(inputTool) &&\n (isAutoParsableTool(inputTool) || inputTool?.function.strict || false));\n}\nexport function hasAutoParseableInput(params) {\n if (isAutoParsableResponseFormat(params.response_format)) {\n return true;\n }\n return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);\n}\nexport function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) {\n for (const toolCall of toolCalls || []) {\n if (toolCall.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool calls are supported; Received \\`${toolCall.type}\\``);\n }\n }\n}\nexport function validateInputTools(tools) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``);\n }\n if (tool.function.strict !== true) {\n throw new OpenAIError(`The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`);\n }\n }\n}\n//# sourceMappingURL=parser.mjs.map","export const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use');\nconst defaultOptions = {\n name: undefined,\n $refStrategy: 'root',\n effectStrategy: 'input',\n pipeStrategy: 'all',\n dateStrategy: 'format:date-time',\n mapStrategy: 'entries',\n nullableStrategy: 'from-target',\n removeAdditionalStrategy: 'passthrough',\n definitionPath: 'definitions',\n target: 'jsonSchema7',\n strictUnions: false,\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: 'escape',\n applyRegexFlags: false,\n emailStrategy: 'format:email',\n base64Strategy: 'contentEncoding:base64',\n nameStrategy: 'ref',\n};\nexport const getDefaultOptions = (options) => {\n // We need to add `definitions` here as we may mutate it\n return (typeof options === 'string' ?\n {\n ...defaultOptions,\n basePath: ['#'],\n definitions: {},\n name: options,\n }\n : {\n ...defaultOptions,\n basePath: ['#'],\n definitions: {},\n ...options,\n });\n};\n//# sourceMappingURL=Options.mjs.map","export const zodDef = (zodSchema) => {\n return '_def' in zodSchema ? zodSchema._def : zodSchema;\n};\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n//# sourceMappingURL=util.mjs.map","import { getDefaultOptions } from \"./Options.mjs\";\nimport { zodDef } from \"./util.mjs\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined ?\n [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n currentPath: currentPath,\n propertyPath: undefined,\n seenRefs: new Set(),\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n zodDef(def),\n {\n def: zodDef(def),\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n//# sourceMappingURL=Refs.mjs.map","export function parseAnyDef() {\n return {};\n}\n//# sourceMappingURL=any.mjs.map","export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n//# sourceMappingURL=errorMessages.mjs.map","import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nimport { parseDef } from \"../parseDef.mjs\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: 'array',\n };\n if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n//# sourceMappingURL=array.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: 'integer',\n format: 'int64',\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n break;\n case 'max':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n break;\n case 'multipleOf':\n setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n//# sourceMappingURL=bigint.mjs.map","export function parseBooleanDef() {\n return {\n type: 'boolean',\n };\n}\n//# sourceMappingURL=boolean.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n//# sourceMappingURL=branded.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n//# sourceMappingURL=catch.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case 'string':\n case 'format:date-time':\n return {\n type: 'string',\n format: 'date-time',\n };\n case 'format:date':\n return {\n type: 'string',\n format: 'date',\n };\n case 'integer':\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: 'integer',\n format: 'unix-time',\n };\n if (refs.target === 'openApi3') {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds\n check.message, refs);\n break;\n case 'max':\n setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n//# sourceMappingURL=date.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n//# sourceMappingURL=default.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseEffectsDef(_def, refs, forceResolution) {\n return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {};\n}\n//# sourceMappingURL=effects.mjs.map","export function parseEnumDef(def) {\n return {\n type: 'string',\n enum: [...def.values],\n };\n}\n//# sourceMappingURL=enum.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nconst isJsonSchema7AllOfType = (type) => {\n if ('type' in type && type.type === 'string')\n return false;\n return 'allOf' in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '1'],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if ('additionalProperties' in schema && schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ?\n {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n//# sourceMappingURL=intersection.mjs.map","export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== 'bigint' &&\n parsedType !== 'number' &&\n parsedType !== 'boolean' &&\n parsedType !== 'string') {\n return {\n type: Array.isArray(def.value) ? 'array' : 'object',\n };\n }\n if (refs.target === 'openApi3') {\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n const: def.value,\n };\n}\n//# sourceMappingURL=literal.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nlet emojiRegex;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp('^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$', 'u');\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: 'string',\n };\n function processPattern(value) {\n return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value;\n }\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n break;\n case 'max':\n setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n break;\n case 'email':\n switch (refs.emailStrategy) {\n case 'format:email':\n addFormat(res, 'email', check.message, refs);\n break;\n case 'format:idn-email':\n addFormat(res, 'idn-email', check.message, refs);\n break;\n case 'pattern:zod':\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case 'url':\n addFormat(res, 'uri', check.message, refs);\n break;\n case 'uuid':\n addFormat(res, 'uuid', check.message, refs);\n break;\n case 'regex':\n addPattern(res, check.regex, check.message, refs);\n break;\n case 'cuid':\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case 'cuid2':\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case 'startsWith':\n addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);\n break;\n case 'endsWith':\n addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);\n break;\n case 'datetime':\n addFormat(res, 'date-time', check.message, refs);\n break;\n case 'date':\n addFormat(res, 'date', check.message, refs);\n break;\n case 'time':\n addFormat(res, 'time', check.message, refs);\n break;\n case 'duration':\n addFormat(res, 'duration', check.message, refs);\n break;\n case 'length':\n setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n break;\n case 'includes': {\n addPattern(res, RegExp(processPattern(check.value)), check.message, refs);\n break;\n }\n case 'ip': {\n if (check.version !== 'v6') {\n addFormat(res, 'ipv4', check.message, refs);\n }\n if (check.version !== 'v4') {\n addFormat(res, 'ipv6', check.message, refs);\n }\n break;\n }\n case 'emoji':\n addPattern(res, zodPatterns.emoji, check.message, refs);\n break;\n case 'ulid': {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case 'base64': {\n switch (refs.base64Strategy) {\n case 'format:binary': {\n addFormat(res, 'binary', check.message, refs);\n break;\n }\n case 'contentEncoding:base64': {\n setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs);\n break;\n }\n case 'pattern:zod': {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case 'nanoid': {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case 'toLowerCase':\n case 'toUpperCase':\n case 'trim':\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nconst escapeNonAlphaNumeric = (value) => Array.from(value)\n .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\\\${c}`))\n .join('');\nconst addFormat = (schema, value, message, refs) => {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message && refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, 'format', value, message, refs);\n }\n};\nconst addPattern = (schema, regex, message, refs) => {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: processRegExp(regex, refs),\n ...(message && refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs);\n }\n};\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nconst processRegExp = (regexOrFunction, refs) => {\n const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction;\n if (!refs.applyRegexFlags || !regex.flags)\n return regex.source;\n // Currently handled flags\n const flags = {\n i: regex.flags.includes('i'), // Case-insensitive\n m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters\n s: regex.flags.includes('s'), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = '';\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === '^') {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === '$') {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === '.') {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === '\\\\') {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === ']') {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === '[') {\n inCharGroup = true;\n }\n }\n try {\n const regexTest = new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n};\n//# sourceMappingURL=string.mjs.map","import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseDef } from \"../parseDef.mjs\";\nimport { parseStringDef } from \"./string.mjs\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: 'object',\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'properties', key],\n }) ?? {},\n }), {}),\n additionalProperties: false,\n };\n }\n const schema = {\n type: 'object',\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? {},\n };\n if (refs.target === 'openApi3') {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {\n const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {});\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n return schema;\n}\n//# sourceMappingURL=record.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nimport { parseRecordDef } from \"./record.mjs\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === 'record') {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '0'],\n }) || {};\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '1'],\n }) || {};\n return {\n type: 'array',\n maxItems: 125,\n items: {\n type: 'array',\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n//# sourceMappingURL=map.mjs.map","export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== 'number';\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1 ?\n parsedTypes[0] === 'string' ?\n 'string'\n : 'number'\n : ['string', 'number'],\n enum: actualValues,\n };\n}\n//# sourceMappingURL=nativeEnum.mjs.map","export function parseNeverDef() {\n return {\n not: {},\n };\n}\n//# sourceMappingURL=never.mjs.map","export function parseNullDef(refs) {\n return refs.target === 'openApi3' ?\n {\n enum: ['null'],\n nullable: true,\n }\n : {\n type: 'null',\n };\n}\n//# sourceMappingURL=null.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const primitiveMappings = {\n ZodString: 'string',\n ZodNumber: 'number',\n ZodBigInt: 'integer',\n ZodBoolean: 'boolean',\n ZodNull: 'null',\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === 'openApi3')\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case 'string':\n case 'number':\n case 'boolean':\n return [...acc, type];\n case 'bigint':\n return [...acc, 'integer'];\n case 'object':\n if (x._def.value === null)\n return [...acc, 'null'];\n case 'symbol':\n case 'undefined':\n case 'function':\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === 'ZodEnum')) {\n return {\n type: 'string',\n enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n }))\n .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n//# sourceMappingURL=union.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nimport { primitiveMappings } from \"./union.mjs\";\nexport function parseNullableDef(def, refs) {\n if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [primitiveMappings[def.innerType._def.typeName], 'null'],\n };\n }\n if (refs.target === 'openApi3') {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && '$ref' in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '0'],\n });\n return base && { anyOf: [base, { type: 'null' }] };\n}\n//# sourceMappingURL=nullable.mjs.map","import { addErrorMessage, setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: 'number',\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case 'int':\n res.type = 'integer';\n addErrorMessage(res, 'type', check.message, refs);\n break;\n case 'min':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n break;\n case 'max':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n break;\n case 'multipleOf':\n setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n//# sourceMappingURL=number.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nfunction decideAdditionalProperties(def, refs) {\n if (refs.removeAdditionalStrategy === 'strict') {\n return def.catchall._def.typeName === 'ZodNever' ?\n def.unknownKeys !== 'strict'\n : parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? true;\n }\n else {\n return def.catchall._def.typeName === 'ZodNever' ?\n def.unknownKeys === 'passthrough'\n : parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? true;\n }\n}\nexport function parseObjectDef(def, refs) {\n const result = {\n type: 'object',\n ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {\n if (propDef === undefined || propDef._def === undefined)\n return acc;\n const propertyPath = [...refs.currentPath, 'properties', propName];\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: propertyPath,\n propertyPath,\n });\n if (parsedDef === undefined)\n return acc;\n if (refs.openaiStrictMode &&\n propDef.isOptional() &&\n !propDef.isNullable() &&\n typeof propDef._def?.defaultValue === 'undefined') {\n throw new Error(`Zod field at \\`${propertyPath.join('/')}\\` uses \\`.optional()\\` without \\`.nullable()\\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);\n }\n return {\n properties: {\n ...acc.properties,\n [propName]: parsedDef,\n },\n required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName],\n };\n }, { properties: {}, required: [] }),\n additionalProperties: decideAdditionalProperties(def, refs),\n };\n if (!result.required.length)\n delete result.required;\n return result;\n}\n//# sourceMappingURL=object.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.propertyPath &&\n refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) {\n return parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath });\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '1'],\n });\n return innerSchema ?\n {\n anyOf: [\n {\n not: {},\n },\n innerSchema,\n ],\n }\n : {};\n};\n//# sourceMappingURL=optional.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === 'input') {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === 'output') {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n//# sourceMappingURL=pipeline.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n//# sourceMappingURL=promise.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nimport { parseDef } from \"../parseDef.mjs\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n const schema = {\n type: 'array',\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n//# sourceMappingURL=set.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: 'array',\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalItems'],\n }),\n };\n }\n else {\n return {\n type: 'array',\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n//# sourceMappingURL=tuple.mjs.map","export function parseUndefinedDef() {\n return {\n not: {},\n };\n}\n//# sourceMappingURL=undefined.mjs.map","export function parseUnknownDef() {\n return {};\n}\n//# sourceMappingURL=unknown.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n//# sourceMappingURL=readonly.mjs.map","import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseAnyDef } from \"./parsers/any.mjs\";\nimport { parseArrayDef } from \"./parsers/array.mjs\";\nimport { parseBigintDef } from \"./parsers/bigint.mjs\";\nimport { parseBooleanDef } from \"./parsers/boolean.mjs\";\nimport { parseBrandedDef } from \"./parsers/branded.mjs\";\nimport { parseCatchDef } from \"./parsers/catch.mjs\";\nimport { parseDateDef } from \"./parsers/date.mjs\";\nimport { parseDefaultDef } from \"./parsers/default.mjs\";\nimport { parseEffectsDef } from \"./parsers/effects.mjs\";\nimport { parseEnumDef } from \"./parsers/enum.mjs\";\nimport { parseIntersectionDef } from \"./parsers/intersection.mjs\";\nimport { parseLiteralDef } from \"./parsers/literal.mjs\";\nimport { parseMapDef } from \"./parsers/map.mjs\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.mjs\";\nimport { parseNeverDef } from \"./parsers/never.mjs\";\nimport { parseNullDef } from \"./parsers/null.mjs\";\nimport { parseNullableDef } from \"./parsers/nullable.mjs\";\nimport { parseNumberDef } from \"./parsers/number.mjs\";\nimport { parseObjectDef } from \"./parsers/object.mjs\";\nimport { parseOptionalDef } from \"./parsers/optional.mjs\";\nimport { parsePipelineDef } from \"./parsers/pipeline.mjs\";\nimport { parsePromiseDef } from \"./parsers/promise.mjs\";\nimport { parseRecordDef } from \"./parsers/record.mjs\";\nimport { parseSetDef } from \"./parsers/set.mjs\";\nimport { parseStringDef } from \"./parsers/string.mjs\";\nimport { parseTupleDef } from \"./parsers/tuple.mjs\";\nimport { parseUndefinedDef } from \"./parsers/undefined.mjs\";\nimport { parseUnionDef } from \"./parsers/union.mjs\";\nimport { parseUnknownDef } from \"./parsers/unknown.mjs\";\nimport { parseReadonlyDef } from \"./parsers/readonly.mjs\";\nimport { ignoreOverride } from \"./Options.mjs\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n if ('$ref' in seenSchema) {\n refs.seenRefs.add(seenSchema.$ref);\n }\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchema = selectParser(def, def.typeName, refs, forceResolution);\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case 'root':\n return { $ref: item.path.join('/') };\n // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e.\n // the top-level schema *must* be `{\"type\": \"object\", \"properties\": {...}}` but if we ever\n // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract\n // the schema to `#/definitions/` and reference that.\n //\n // e.g. if we need to reference a schema at\n // `[\"#\",\"definitions\",\"contactPerson\",\"properties\",\"person1\",\"properties\",\"name\"]`\n // then we'll extract it out to `contactPerson_properties_person1_properties_name`\n case 'extract-to-root':\n const name = item.path.slice(refs.basePath.length + 1).join('_');\n // we don't need to extract the root schema in this case, as it's already\n // been added to the definitions\n if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') {\n refs.definitions[name] = item.def;\n }\n return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') };\n case 'relative':\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case 'none':\n case 'seen': {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`);\n return {};\n }\n return refs.$refStrategy === 'seen' ? {} : undefined;\n }\n }\n};\nconst getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\nconst selectParser = (def, typeName, refs, forceResolution) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return parseDef(def.getter()._def, refs);\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs, forceResolution);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n//# sourceMappingURL=parseDef.mjs.map","import { parseDef } from \"./parseDef.mjs\";\nimport { getRefs } from \"./Refs.mjs\";\nimport { zodDef, isEmptyObj } from \"./util.mjs\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n const name = typeof options === 'string' ? options\n : options?.nameStrategy === 'title' ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined ? refs : ({\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }), false) ?? {};\n const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ?\n options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n const definitions = (() => {\n if (isEmptyObj(refs.definitions)) {\n return undefined;\n }\n const definitions = {};\n const processedDefinitions = new Set();\n // the call to `parseDef()` here might itself add more entries to `.definitions`\n // so we need to continually evaluate definitions until we've resolved all of them\n //\n // we have a generous iteration limit here to avoid blowing up the stack if there\n // are any bugs that would otherwise result in us iterating indefinitely\n for (let i = 0; i < 500; i++) {\n const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key));\n if (newDefinitions.length === 0)\n break;\n for (const [key, schema] of newDefinitions) {\n definitions[key] =\n parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {};\n processedDefinitions.add(key);\n }\n }\n return definitions;\n })();\n const combined = name === undefined ?\n definitions ?\n {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : refs.nameStrategy === 'duplicate-ref' ?\n {\n ...main,\n ...(definitions || refs.seenRefs.size ?\n {\n [refs.definitionPath]: {\n ...definitions,\n // only actually duplicate the schema definition if it was ever referenced\n // otherwise the duplication is completely pointless\n ...(refs.seenRefs.size ? { [name]: main } : undefined),\n },\n }\n : undefined),\n }\n : {\n $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === 'jsonSchema7') {\n combined.$schema = 'http://json-schema.org/draft-07/schema#';\n }\n else if (refs.target === 'jsonSchema2019-09') {\n combined.$schema = 'https://json-schema.org/draft/2019-09/schema#';\n }\n return combined;\n};\nexport { zodToJsonSchema };\n//# sourceMappingURL=zodToJsonSchema.mjs.map","export * from \"./Options.mjs\";\nexport * from \"./Refs.mjs\";\nexport * from \"./errorMessages.mjs\";\nexport * from \"./parseDef.mjs\";\nexport * from \"./parsers/any.mjs\";\nexport * from \"./parsers/array.mjs\";\nexport * from \"./parsers/bigint.mjs\";\nexport * from \"./parsers/boolean.mjs\";\nexport * from \"./parsers/branded.mjs\";\nexport * from \"./parsers/catch.mjs\";\nexport * from \"./parsers/date.mjs\";\nexport * from \"./parsers/default.mjs\";\nexport * from \"./parsers/effects.mjs\";\nexport * from \"./parsers/enum.mjs\";\nexport * from \"./parsers/intersection.mjs\";\nexport * from \"./parsers/literal.mjs\";\nexport * from \"./parsers/map.mjs\";\nexport * from \"./parsers/nativeEnum.mjs\";\nexport * from \"./parsers/never.mjs\";\nexport * from \"./parsers/null.mjs\";\nexport * from \"./parsers/nullable.mjs\";\nexport * from \"./parsers/number.mjs\";\nexport * from \"./parsers/object.mjs\";\nexport * from \"./parsers/optional.mjs\";\nexport * from \"./parsers/pipeline.mjs\";\nexport * from \"./parsers/promise.mjs\";\nexport * from \"./parsers/readonly.mjs\";\nexport * from \"./parsers/record.mjs\";\nexport * from \"./parsers/set.mjs\";\nexport * from \"./parsers/string.mjs\";\nexport * from \"./parsers/tuple.mjs\";\nexport * from \"./parsers/undefined.mjs\";\nexport * from \"./parsers/union.mjs\";\nexport * from \"./parsers/unknown.mjs\";\nexport * from \"./zodToJsonSchema.mjs\";\nimport { zodToJsonSchema } from \"./zodToJsonSchema.mjs\";\nexport default zodToJsonSchema;\n//# sourceMappingURL=index.mjs.map","import { OpenAIError } from \"../error.mjs\";\nimport { isAutoParsableResponseFormat } from \"../lib/parser.mjs\";\nexport function maybeParseResponse(response, params) {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...response,\n output_parsed: null,\n output: response.output.map((item) => {\n if (item.type === 'function_call') {\n return {\n ...item,\n parsed_arguments: null,\n };\n }\n if (item.type === 'message') {\n return {\n ...item,\n content: item.content.map((content) => ({\n ...content,\n parsed: null,\n })),\n };\n }\n else {\n return item;\n }\n }),\n };\n }\n return parseResponse(response, params);\n}\nexport function parseResponse(response, params) {\n const output = response.output.map((item) => {\n if (item.type === 'function_call') {\n return {\n ...item,\n parsed_arguments: parseToolCall(params, item),\n };\n }\n if (item.type === 'message') {\n const content = item.content.map((content) => {\n if (content.type === 'output_text') {\n return {\n ...content,\n parsed: parseTextFormat(params, content.text),\n };\n }\n return content;\n });\n return {\n ...item,\n content,\n };\n }\n return item;\n });\n const parsed = Object.assign({}, response, { output });\n if (!Object.getOwnPropertyDescriptor(response, 'output_text')) {\n addOutputText(parsed);\n }\n Object.defineProperty(parsed, 'output_parsed', {\n enumerable: true,\n get() {\n for (const output of parsed.output) {\n if (output.type !== 'message') {\n continue;\n }\n for (const content of output.content) {\n if (content.type === 'output_text' && content.parsed !== null) {\n return content.parsed;\n }\n }\n }\n return null;\n },\n });\n return parsed;\n}\nfunction parseTextFormat(params, content) {\n if (params.text?.format?.type !== 'json_schema') {\n return null;\n }\n if ('$parseRaw' in params.text?.format) {\n const text_format = params.text?.format;\n return text_format.$parseRaw(content);\n }\n return JSON.parse(content);\n}\nexport function hasAutoParseableInput(params) {\n if (isAutoParsableResponseFormat(params.text?.format)) {\n return true;\n }\n return false;\n}\nexport function makeParseableResponseTool(tool, { parser, callback, }) {\n const obj = { ...tool };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableTool(tool) {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\nfunction getInputToolByName(input_tools, name) {\n return input_tools.find((tool) => tool.type === 'function' && tool.name === name);\n}\nfunction parseToolCall(params, toolCall) {\n const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);\n return {\n ...toolCall,\n ...toolCall,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments)\n : inputTool?.strict ? JSON.parse(toolCall.arguments)\n : null,\n };\n}\nexport function shouldParseToolCall(params, toolCall) {\n if (!params) {\n return false;\n }\n const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);\n return isAutoParsableTool(inputTool) || inputTool?.strict || false;\n}\nexport function validateInputTools(tools) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``);\n }\n if (tool.function.strict !== true) {\n throw new OpenAIError(`The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`);\n }\n }\n}\nexport function addOutputText(rsp) {\n const texts = [];\n for (const output of rsp.output) {\n if (output.type !== 'message') {\n continue;\n }\n for (const content of output.content) {\n if (content.type === 'output_text') {\n texts.push(content.text);\n }\n }\n }\n rsp.output_text = texts.join('');\n}\n//# sourceMappingURL=ResponsesParser.mjs.map","export function toStrictJsonSchema(schema) {\n if (schema.type !== 'object') {\n throw new Error(`Root schema must have type: 'object' but got type: ${schema.type ? `'${schema.type}'` : 'undefined'}`);\n }\n const schemaCopy = structuredClone(schema);\n return ensureStrictJsonSchema(schemaCopy, [], schemaCopy);\n}\nfunction isNullable(schema) {\n if (typeof schema === 'boolean') {\n return false;\n }\n if (schema.type === 'null') {\n return true;\n }\n for (const oneOfVariant of schema.oneOf ?? []) {\n if (isNullable(oneOfVariant)) {\n return true;\n }\n }\n for (const allOfVariant of schema.anyOf ?? []) {\n if (isNullable(allOfVariant)) {\n return true;\n }\n }\n return false;\n}\n/**\n * Mutates the given JSON schema to ensure it conforms to the `strict` standard\n * that the API expects.\n */\nfunction ensureStrictJsonSchema(jsonSchema, path, root) {\n if (typeof jsonSchema === 'boolean') {\n throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`);\n }\n if (!isObject(jsonSchema)) {\n throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join('/')}`);\n }\n // Handle $defs (non-standard but sometimes used)\n const defs = jsonSchema.$defs;\n if (isObject(defs)) {\n for (const [defName, defSchema] of Object.entries(defs)) {\n ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root);\n }\n }\n // Handle definitions (draft-04 style, deprecated in draft-07 but still used)\n const definitions = jsonSchema.definitions;\n if (isObject(definitions)) {\n for (const [definitionName, definitionSchema] of Object.entries(definitions)) {\n ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root);\n }\n }\n // Add additionalProperties: false to object types\n const typ = jsonSchema.type;\n if (typ === 'object' && !('additionalProperties' in jsonSchema)) {\n jsonSchema.additionalProperties = false;\n }\n const required = jsonSchema.required ?? [];\n // Handle object properties\n const properties = jsonSchema.properties;\n if (isObject(properties)) {\n for (const [key, value] of Object.entries(properties)) {\n if (!isNullable(value) && !required.includes(key)) {\n throw new Error(`Zod field at \\`${[...path, 'properties', key].join('/')}\\` uses \\`.optional()\\` without \\`.nullable()\\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);\n }\n }\n jsonSchema.required = Object.keys(properties);\n jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [\n key,\n ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root),\n ]));\n }\n // Handle arrays\n const items = jsonSchema.items;\n if (isObject(items)) {\n jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root);\n }\n // Handle unions (anyOf)\n const anyOf = jsonSchema.anyOf;\n if (Array.isArray(anyOf)) {\n jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root));\n }\n // Handle intersections (allOf)\n const allOf = jsonSchema.allOf;\n if (Array.isArray(allOf)) {\n if (allOf.length === 1) {\n const resolved = ensureStrictJsonSchema(allOf[0], [...path, 'allOf', '0'], root);\n Object.assign(jsonSchema, resolved);\n delete jsonSchema.allOf;\n }\n else {\n jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root));\n }\n }\n // Strip `null` defaults as there's no meaningful distinction\n if (jsonSchema.default === null) {\n delete jsonSchema.default;\n }\n // Handle $ref with additional properties\n const ref = jsonSchema.$ref;\n if (ref && hasMoreThanNKeys(jsonSchema, 1)) {\n if (typeof ref !== 'string') {\n throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join('/')}`);\n }\n const resolved = resolveRef(root, ref);\n if (typeof resolved === 'boolean') {\n throw new Error(`Expected \\`$ref: ${ref}\\` to resolve to an object schema but got boolean`);\n }\n if (!isObject(resolved)) {\n throw new Error(`Expected \\`$ref: ${ref}\\` to resolve to an object but got ${JSON.stringify(resolved)}`);\n }\n // Properties from the json schema take priority over the ones on the `$ref`\n Object.assign(jsonSchema, { ...resolved, ...jsonSchema });\n delete jsonSchema.$ref;\n // Since the schema expanded from `$ref` might not have `additionalProperties: false` applied,\n // we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid.\n return ensureStrictJsonSchema(jsonSchema, path, root);\n }\n return jsonSchema;\n}\nfunction resolveRef(root, ref) {\n if (!ref.startsWith('#/')) {\n throw new Error(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`);\n }\n const pathParts = ref.slice(2).split('/');\n let resolved = root;\n for (const key of pathParts) {\n if (!isObject(resolved)) {\n throw new Error(`encountered non-object entry while resolving ${ref} - ${JSON.stringify(resolved)}`);\n }\n const value = resolved[key];\n if (value === undefined) {\n throw new Error(`Key ${key} not found while resolving ${ref}`);\n }\n resolved = value;\n }\n return resolved;\n}\nfunction isObject(obj) {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj);\n}\nfunction hasMoreThanNKeys(obj, n) {\n let i = 0;\n for (const _ in obj) {\n i++;\n if (i > n) {\n return true;\n }\n }\n return false;\n}\n//# sourceMappingURL=transform.mjs.map","import { z as z4 } from 'zod/v4';\nimport { makeParseableResponseFormat, makeParseableTextFormat, makeParseableTool, } from \"../lib/parser.mjs\";\nimport { zodToJsonSchema as _zodToJsonSchema } from \"../_vendor/zod-to-json-schema/index.mjs\";\nimport { makeParseableResponseTool } from \"../lib/ResponsesParser.mjs\";\nimport { toStrictJsonSchema } from \"../lib/transform.mjs\";\nfunction zodV3ToJsonSchema(schema, options) {\n return _zodToJsonSchema(schema, {\n openaiStrictMode: true,\n name: options.name,\n nameStrategy: 'duplicate-ref',\n $refStrategy: 'extract-to-root',\n nullableStrategy: 'property',\n });\n}\nfunction zodV4ToJsonSchema(schema) {\n return toStrictJsonSchema(z4.toJSONSchema(schema, {\n target: 'draft-7',\n }));\n}\nfunction isZodV4(zodObject) {\n return '_zod' in zodObject;\n}\n/**\n * Creates a chat completion `JSONSchema` response format object from\n * the given Zod schema.\n *\n * If this is passed to the `.parse()`, `.stream()` or `.runTools()`\n * chat completion methods then the response message will contain a\n * `.parsed` property that is the result of parsing the content with\n * the given Zod object.\n *\n * ```ts\n * const completion = await client.chat.completions.parse({\n * model: 'gpt-4o-2024-08-06',\n * messages: [\n * { role: 'system', content: 'You are a helpful math tutor.' },\n * { role: 'user', content: 'solve 8x + 31 = 2' },\n * ],\n * response_format: zodResponseFormat(\n * z.object({\n * steps: z.array(z.object({\n * explanation: z.string(),\n * answer: z.string(),\n * })),\n * final_answer: z.string(),\n * }),\n * 'math_answer',\n * ),\n * });\n * const message = completion.choices[0]?.message;\n * if (message?.parsed) {\n * console.log(message.parsed);\n * console.log(message.parsed.final_answer);\n * }\n * ```\n *\n * This can be passed directly to the `.create()` method but will not\n * result in any automatic parsing, you'll have to parse the response yourself.\n */\nexport function zodResponseFormat(zodObject, name, props) {\n return makeParseableResponseFormat({\n type: 'json_schema',\n json_schema: {\n ...props,\n name,\n strict: true,\n schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }),\n },\n }, (content) => zodObject.parse(JSON.parse(content)));\n}\nexport function zodTextFormat(zodObject, name, props) {\n return makeParseableTextFormat({\n type: 'json_schema',\n ...props,\n name,\n strict: true,\n schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }),\n }, (content) => zodObject.parse(JSON.parse(content)));\n}\n/**\n * Creates a chat completion `function` tool that can be invoked\n * automatically by the chat completion `.runTools()` method or automatically\n * parsed by `.parse()` / `.stream()`.\n */\nexport function zodFunction(options) {\n // @ts-expect-error TODO\n return makeParseableTool({\n type: 'function',\n function: {\n name: options.name,\n parameters: isZodV4(options.parameters) ?\n zodV4ToJsonSchema(options.parameters)\n : zodV3ToJsonSchema(options.parameters, { name: options.name }),\n strict: true,\n ...(options.description ? { description: options.description } : undefined),\n },\n }, {\n callback: options.function,\n parser: (args) => options.parameters.parse(JSON.parse(args)),\n });\n}\nexport function zodResponsesFunction(options) {\n return makeParseableResponseTool({\n type: 'function',\n name: options.name,\n parameters: isZodV4(options.parameters) ?\n zodV4ToJsonSchema(options.parameters)\n : zodV3ToJsonSchema(options.parameters, { name: options.name }),\n strict: true,\n ...(options.description ? { description: options.description } : undefined),\n }, {\n callback: options.function,\n parser: (args) => options.parameters.parse(JSON.parse(args)),\n });\n}\n//# sourceMappingURL=zod.mjs.map","import { isZodSchemaV3, isZodSchemaV4 } from \"@langchain/core/utils/types\";\nimport { parse, toJSONSchema } from \"zod/v4/core\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\n\n//#region src/utils/output.ts\nconst SUPPORTED_METHODS = [\n\t\"jsonSchema\",\n\t\"functionCalling\",\n\t\"jsonMode\"\n];\n/**\n* Get the structured output method for a given model. By default, it uses\n* `jsonSchema` if the model supports it, otherwise it uses `functionCalling`.\n*\n* @throws if the method is invalid, e.g. is not a string or invalid method is provided.\n* @param model - The model name.\n* @param config - The structured output method options.\n* @returns The structured output method.\n*/\nfunction getStructuredOutputMethod(model, method) {\n\t/**\n\t* If a method is provided, validate it.\n\t*/\n\tif (typeof method !== \"undefined\" && !SUPPORTED_METHODS.includes(method)) throw new Error(`Invalid method: ${method}. Supported methods are: ${SUPPORTED_METHODS.join(\", \")}`);\n\tconst hasSupportForJsonSchema = !model.startsWith(\"gpt-3\") && !model.startsWith(\"gpt-4-\") && model !== \"gpt-4\";\n\t/**\n\t* If the model supports JSON Schema, use it by default.\n\t*/\n\tif (hasSupportForJsonSchema && !method) return \"jsonSchema\";\n\tif (!hasSupportForJsonSchema && method === \"jsonSchema\") throw new Error(`JSON Schema is not supported for model \"${model}\". Please use a different method, e.g. \"functionCalling\" or \"jsonMode\".`);\n\t/**\n\t* If the model does not support JSON Schema, use function calling by default.\n\t*/\n\treturn method ?? \"functionCalling\";\n}\nfunction makeParseableResponseFormat(response_format, parser) {\n\tconst obj = { ...response_format };\n\tObject.defineProperties(obj, {\n\t\t$brand: {\n\t\t\tvalue: \"auto-parseable-response-format\",\n\t\t\tenumerable: false\n\t\t},\n\t\t$parseRaw: {\n\t\t\tvalue: parser,\n\t\t\tenumerable: false\n\t\t}\n\t});\n\treturn obj;\n}\nfunction interopZodResponseFormat(zodSchema, name, props) {\n\tif (isZodSchemaV3(zodSchema)) return zodResponseFormat(zodSchema, name, props);\n\tif (isZodSchemaV4(zodSchema)) return makeParseableResponseFormat({\n\t\ttype: \"json_schema\",\n\t\tjson_schema: {\n\t\t\t...props,\n\t\t\tname,\n\t\t\tstrict: true,\n\t\t\tschema: toJSONSchema(zodSchema, {\n\t\t\t\tcycles: \"ref\",\n\t\t\t\treused: \"ref\",\n\t\t\t\toverride(ctx) {\n\t\t\t\t\tctx.jsonSchema.title = name;\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}, (content) => parse(zodSchema, JSON.parse(content)));\n\tthrow new Error(\"Unsupported schema response format\");\n}\n/**\n* Handle multi modal response content.\n*\n* @param content The content of the message.\n* @param messages The messages of the response.\n* @returns The new content of the message.\n*/\nfunction handleMultiModalOutput(content, messages) {\n\t/**\n\t* Handle OpenRouter image responses\n\t* @see https://openrouter.ai/docs/features/multimodal/image-generation#api-usage\n\t*/\n\tif (messages && typeof messages === \"object\" && \"images\" in messages && Array.isArray(messages.images)) {\n\t\tconst images = messages.images.filter((image) => typeof image?.image_url?.url === \"string\").map((image) => ({\n\t\t\ttype: \"image\",\n\t\t\turl: image.image_url.url\n\t\t}));\n\t\treturn [{\n\t\t\ttype: \"text\",\n\t\t\ttext: content\n\t\t}, ...images];\n\t}\n\treturn content;\n}\nfunction _convertOpenAIResponsesUsageToLangChainUsage(usage) {\n\tconst inputTokenDetails = { ...usage?.input_tokens_details?.cached_tokens != null && { cache_read: usage?.input_tokens_details?.cached_tokens } };\n\tconst outputTokenDetails = { ...usage?.output_tokens_details?.reasoning_tokens != null && { reasoning: usage?.output_tokens_details?.reasoning_tokens } };\n\treturn {\n\t\tinput_tokens: usage?.input_tokens ?? 0,\n\t\toutput_tokens: usage?.output_tokens ?? 0,\n\t\ttotal_tokens: usage?.total_tokens ?? 0,\n\t\tinput_token_details: inputTokenDetails,\n\t\toutput_token_details: outputTokenDetails\n\t};\n}\n\n//#endregion\nexport { _convertOpenAIResponsesUsageToLangChainUsage, getStructuredOutputMethod, handleMultiModalOutput, interopZodResponseFormat };\n//# sourceMappingURL=output.js.map","function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\")\n throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f)\n throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver))\n throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return kind === \"a\" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value;\n}\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f)\n throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver))\n throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\nexport { __classPrivateFieldSet, __classPrivateFieldGet };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n/**\n * https://stackoverflow.com/a/2117523\n */\nexport let uuid4 = function () {\n const { crypto } = globalThis;\n if (crypto?.randomUUID) {\n uuid4 = crypto.randomUUID.bind(crypto);\n return crypto.randomUUID();\n }\n const u8 = new Uint8Array(1);\n const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;\n return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));\n};\n//# sourceMappingURL=uuid.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { OpenAIError } from \"../../core/error.mjs\";\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nexport const isAbsoluteURL = (url) => {\n return startsWithSchemeRegexp.test(url);\n};\nexport let isArray = (val) => ((isArray = Array.isArray), isArray(val));\nexport let isReadonlyArray = isArray;\n/** Returns an object if the given value isn't an object, otherwise returns as-is */\nexport function maybeObj(x) {\n if (typeof x !== 'object') {\n return {};\n }\n return x ?? {};\n}\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nexport function isObj(obj) {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\nexport const ensurePresent = (value) => {\n if (value == null) {\n throw new OpenAIError(`Expected a value to be given but received ${value} instead.`);\n }\n return value;\n};\nexport const validatePositiveInteger = (name, n) => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new OpenAIError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new OpenAIError(`${name} must be a positive integer`);\n }\n return n;\n};\nexport const coerceInteger = (value) => {\n if (typeof value === 'number')\n return Math.round(value);\n if (typeof value === 'string')\n return parseInt(value, 10);\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceFloat = (value) => {\n if (typeof value === 'number')\n return value;\n if (typeof value === 'string')\n return parseFloat(value);\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceBoolean = (value) => {\n if (typeof value === 'boolean')\n return value;\n if (typeof value === 'string')\n return value === 'true';\n return Boolean(value);\n};\nexport const maybeCoerceInteger = (value) => {\n if (value == null) {\n return undefined;\n }\n return coerceInteger(value);\n};\nexport const maybeCoerceFloat = (value) => {\n if (value == null) {\n return undefined;\n }\n return coerceFloat(value);\n};\nexport const maybeCoerceBoolean = (value) => {\n if (value == null) {\n return undefined;\n }\n return coerceBoolean(value);\n};\nexport const safeJSON = (text) => {\n try {\n return JSON.parse(text);\n }\n catch (err) {\n return undefined;\n }\n};\n//# sourceMappingURL=values.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n//# sourceMappingURL=sleep.mjs.map","export const VERSION = '6.8.1'; // x-release-please-version\n//# sourceMappingURL=version.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { VERSION } from \"../version.mjs\";\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined');\n};\n/**\n * Note this does not detect 'browser'; for that, use getBrowserInfo().\n */\nfunction getDetectedPlatform() {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return 'deno';\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return 'edge';\n }\n if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {\n return 'node';\n }\n return 'unknown';\n}\nconst getPlatformProperties = () => {\n const detectedPlatform = getDetectedPlatform();\n if (detectedPlatform === 'deno') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': globalThis.process.version,\n };\n }\n // Check if Node.js\n if (detectedPlatform === 'node') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'),\n 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown',\n };\n }\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo() {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge', pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome', pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox', pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari', pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n return null;\n}\nconst normalizeArch = (arch) => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32')\n return 'x32';\n if (arch === 'x86_64' || arch === 'x64')\n return 'x64';\n if (arch === 'arm')\n return 'arm';\n if (arch === 'aarch64' || arch === 'arm64')\n return 'arm64';\n if (arch)\n return `other:${arch}`;\n return 'unknown';\n};\nconst normalizePlatform = (platform) => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n platform = platform.toLowerCase();\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios'))\n return 'iOS';\n if (platform === 'android')\n return 'Android';\n if (platform === 'darwin')\n return 'MacOS';\n if (platform === 'win32')\n return 'Windows';\n if (platform === 'freebsd')\n return 'FreeBSD';\n if (platform === 'openbsd')\n return 'OpenBSD';\n if (platform === 'linux')\n return 'Linux';\n if (platform)\n return `Other:${platform}`;\n return 'Unknown';\n};\nlet _platformHeaders;\nexport const getPlatformHeaders = () => {\n return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));\n};\n//# sourceMappingURL=detect-platform.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport function getDefaultFetch() {\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');\n}\nexport function makeReadableStream(...args) {\n const ReadableStream = globalThis.ReadableStream;\n if (typeof ReadableStream === 'undefined') {\n // Note: All of the platforms / runtimes we officially support already define\n // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.\n throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');\n }\n return new ReadableStream(...args);\n}\nexport function ReadableStreamFrom(iterable) {\n let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();\n return makeReadableStream({\n start() { },\n async pull(controller) {\n const { done, value } = await iter.next();\n if (done) {\n controller.close();\n }\n else {\n controller.enqueue(value);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n}\n/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable(stream) {\n if (stream[Symbol.asyncIterator])\n return stream;\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done)\n reader.releaseLock(); // release lock when stream becomes closed\n return result;\n }\n catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n/**\n * Cancels a ReadableStream we don't need to consume.\n * See https://undici.nodejs.org/#/?id=garbage-collection\n */\nexport async function CancelReadableStream(stream) {\n if (stream === null || typeof stream !== 'object')\n return;\n if (stream[Symbol.asyncIterator]) {\n await stream[Symbol.asyncIterator]().return?.();\n return;\n }\n const reader = stream.getReader();\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n}\n//# sourceMappingURL=shims.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport const FallbackEncoder = ({ headers, body }) => {\n return {\n bodyHeaders: {\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n };\n};\n//# sourceMappingURL=request-options.mjs.map","export const default_format = 'RFC3986';\nexport const default_formatter = (v) => String(v);\nexport const formatters = {\n RFC1738: (v) => String(v).replace(/%20/g, '+'),\n RFC3986: default_formatter,\n};\nexport const RFC1738 = 'RFC1738';\nexport const RFC3986 = 'RFC3986';\n//# sourceMappingURL=formats.mjs.map","import { RFC1738 } from \"./formats.mjs\";\nimport { isArray } from \"../utils/values.mjs\";\nexport let has = (obj, key) => ((has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)),\n has(obj, key));\nconst hex_table = /* @__PURE__ */ (() => {\n const array = [];\n for (let i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n return array;\n})();\nfunction compact_queue(queue) {\n while (queue.length > 1) {\n const item = queue.pop();\n if (!item)\n continue;\n const obj = item.obj[item.prop];\n if (isArray(obj)) {\n const compacted = [];\n for (let j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n // @ts-ignore\n item.obj[item.prop] = compacted;\n }\n }\n}\nfunction array_to_object(source, options) {\n const obj = options && options.plainObjects ? Object.create(null) : {};\n for (let i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n return obj;\n}\nexport function merge(target, source, options = {}) {\n if (!source) {\n return target;\n }\n if (typeof source !== 'object') {\n if (isArray(target)) {\n target.push(source);\n }\n else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) {\n target[source] = true;\n }\n }\n else {\n return [target, source];\n }\n return target;\n }\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n let mergeTarget = target;\n if (isArray(target) && !isArray(source)) {\n // @ts-ignore\n mergeTarget = array_to_object(target, options);\n }\n if (isArray(target) && isArray(source)) {\n source.forEach(function (item, i) {\n if (has(target, i)) {\n const targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n }\n else {\n target.push(item);\n }\n }\n else {\n target[i] = item;\n }\n });\n return target;\n }\n return Object.keys(source).reduce(function (acc, key) {\n const value = source[key];\n if (has(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n }\n else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n}\nexport function assign_single_source(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n}\nexport function decode(str, _, charset) {\n const strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n }\n catch (e) {\n return strWithoutPlus;\n }\n}\nconst limit = 1024;\nexport const encode = (str, _defaultEncoder, charset, _kind, format) => {\n // This code was originally written by Brian White for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n let string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n }\n else if (typeof str !== 'string') {\n string = String(str);\n }\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n let out = '';\n for (let j = 0; j < string.length; j += limit) {\n const segment = string.length >= limit ? string.slice(j, j + limit) : string;\n const arr = [];\n for (let i = 0; i < segment.length; ++i) {\n let c = segment.charCodeAt(i);\n if (c === 0x2d || // -\n c === 0x2e || // .\n c === 0x5f || // _\n c === 0x7e || // ~\n (c >= 0x30 && c <= 0x39) || // 0-9\n (c >= 0x41 && c <= 0x5a) || // a-z\n (c >= 0x61 && c <= 0x7a) || // A-Z\n (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n arr[arr.length] = segment.charAt(i);\n continue;\n }\n if (c < 0x80) {\n arr[arr.length] = hex_table[c];\n continue;\n }\n if (c < 0x800) {\n arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n if (c < 0xd800 || c >= 0xe000) {\n arr[arr.length] =\n hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n i += 1;\n c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff));\n arr[arr.length] =\n hex_table[0xf0 | (c >> 18)] +\n hex_table[0x80 | ((c >> 12) & 0x3f)] +\n hex_table[0x80 | ((c >> 6) & 0x3f)] +\n hex_table[0x80 | (c & 0x3f)];\n }\n out += arr.join('');\n }\n return out;\n};\nexport function compact(value) {\n const queue = [{ obj: { o: value }, prop: 'o' }];\n const refs = [];\n for (let i = 0; i < queue.length; ++i) {\n const item = queue[i];\n // @ts-ignore\n const obj = item.obj[item.prop];\n const keys = Object.keys(obj);\n for (let j = 0; j < keys.length; ++j) {\n const key = keys[j];\n const val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n compact_queue(queue);\n return value;\n}\nexport function is_regexp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\nexport function is_buffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n}\nexport function combine(a, b) {\n return [].concat(a, b);\n}\nexport function maybe_map(val, fn) {\n if (isArray(val)) {\n const mapped = [];\n for (let i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]));\n }\n return mapped;\n }\n return fn(val);\n}\n//# sourceMappingURL=utils.mjs.map","import { encode, is_buffer, maybe_map, has } from \"./utils.mjs\";\nimport { default_format, default_formatter, formatters } from \"./formats.mjs\";\nimport { isArray } from \"../utils/values.mjs\";\nconst array_prefix_generators = {\n brackets(prefix) {\n return String(prefix) + '[]';\n },\n comma: 'comma',\n indices(prefix, key) {\n return String(prefix) + '[' + key + ']';\n },\n repeat(prefix) {\n return String(prefix);\n },\n};\nconst push_to_array = function (arr, value_or_array) {\n Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);\n};\nlet toISOString;\nconst defaults = {\n addQueryPrefix: false,\n allowDots: false,\n allowEmptyArrays: false,\n arrayFormat: 'indices',\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encodeDotInKeys: false,\n encoder: encode,\n encodeValuesOnly: false,\n format: default_format,\n formatter: default_formatter,\n /** @deprecated */\n indices: false,\n serializeDate(date) {\n return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date);\n },\n skipNulls: false,\n strictNullHandling: false,\n};\nfunction is_non_nullish_primitive(v) {\n return (typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'symbol' ||\n typeof v === 'bigint');\n}\nconst sentinel = {};\nfunction inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {\n let obj = object;\n let tmp_sc = sideChannel;\n let step = 0;\n let find_flag = false;\n while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {\n // Where object last appeared in the ref tree\n const pos = tmp_sc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n }\n else {\n find_flag = true; // Break while\n }\n }\n if (typeof tmp_sc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n }\n else if (obj instanceof Date) {\n obj = serializeDate?.(obj);\n }\n else if (generateArrayPrefix === 'comma' && isArray(obj)) {\n obj = maybe_map(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate?.(value);\n }\n return value;\n });\n }\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ?\n // @ts-expect-error\n encoder(prefix, defaults.encoder, charset, 'key', format)\n : prefix;\n }\n obj = '';\n }\n if (is_non_nullish_primitive(obj) || is_buffer(obj)) {\n if (encoder) {\n const key_value = encodeValuesOnly ? prefix\n // @ts-expect-error\n : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [\n formatter?.(key_value) +\n '=' +\n // @ts-expect-error\n formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)),\n ];\n }\n return [formatter?.(prefix) + '=' + formatter?.(String(obj))];\n }\n const values = [];\n if (typeof obj === 'undefined') {\n return values;\n }\n let obj_keys;\n if (generateArrayPrefix === 'comma' && isArray(obj)) {\n // we need to join elements in\n if (encodeValuesOnly && encoder) {\n // @ts-expect-error values only\n obj = maybe_map(obj, encoder);\n }\n obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n }\n else if (isArray(filter)) {\n obj_keys = filter;\n }\n else {\n const keys = Object.keys(obj);\n obj_keys = sort ? keys.sort(sort) : keys;\n }\n const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\\./g, '%2E') : String(prefix);\n const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix;\n if (allowEmptyArrays && isArray(obj) && obj.length === 0) {\n return adjusted_prefix + '[]';\n }\n for (let j = 0; j < obj_keys.length; ++j) {\n const key = obj_keys[j];\n const value = \n // @ts-ignore\n typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];\n if (skipNulls && value === null) {\n continue;\n }\n // @ts-ignore\n const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\\./g, '%2E') : key;\n const key_prefix = isArray(obj) ?\n typeof generateArrayPrefix === 'function' ?\n generateArrayPrefix(adjusted_prefix, encoded_key)\n : adjusted_prefix\n : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']');\n sideChannel.set(object, step);\n const valueSideChannel = new WeakMap();\n valueSideChannel.set(sentinel, sideChannel);\n push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, \n // @ts-ignore\n generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel));\n }\n return values;\n}\nfunction normalize_stringify_options(opts = defaults) {\n if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {\n throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');\n }\n if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {\n throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');\n }\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n const charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n let format = default_format;\n if (typeof opts.format !== 'undefined') {\n if (!has(formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n const formatter = formatters[format];\n let filter = defaults.filter;\n if (typeof opts.filter === 'function' || isArray(opts.filter)) {\n filter = opts.filter;\n }\n let arrayFormat;\n if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {\n arrayFormat = opts.arrayFormat;\n }\n else if ('indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n }\n else {\n arrayFormat = defaults.arrayFormat;\n }\n if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n const allowDots = typeof opts.allowDots === 'undefined' ?\n !!opts.encodeDotInKeys === true ?\n true\n : defaults.allowDots\n : !!opts.allowDots;\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n // @ts-ignore\n allowDots: allowDots,\n allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,\n arrayFormat: arrayFormat,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n commaRoundTrip: !!opts.commaRoundTrip,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n // @ts-ignore\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,\n };\n}\nexport function stringify(object, opts = {}) {\n let obj = object;\n const options = normalize_stringify_options(opts);\n let obj_keys;\n let filter;\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n }\n else if (isArray(options.filter)) {\n filter = options.filter;\n obj_keys = filter;\n }\n const keys = [];\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n const generateArrayPrefix = array_prefix_generators[options.arrayFormat];\n const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;\n if (!obj_keys) {\n obj_keys = Object.keys(obj);\n }\n if (options.sort) {\n obj_keys.sort(options.sort);\n }\n const sideChannel = new WeakMap();\n for (let i = 0; i < obj_keys.length; ++i) {\n const key = obj_keys[i];\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n push_to_array(keys, inner_stringify(obj[key], key, \n // @ts-expect-error\n generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel));\n }\n const joined = keys.join(options.delimiter);\n let prefix = options.addQueryPrefix === true ? '?' : '';\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n }\n else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n return joined.length > 0 ? prefix + joined : '';\n}\n//# sourceMappingURL=stringify.mjs.map","import { default_format, formatters, RFC1738, RFC3986 } from \"./formats.mjs\";\nconst formats = {\n formatters,\n RFC1738,\n RFC3986,\n default: default_format,\n};\nexport { stringify } from \"./stringify.mjs\";\nexport { formats };\n//# sourceMappingURL=index.mjs.map","export function concatBytes(buffers) {\n let length = 0;\n for (const buffer of buffers) {\n length += buffer.length;\n }\n const output = new Uint8Array(length);\n let index = 0;\n for (const buffer of buffers) {\n output.set(buffer, index);\n index += buffer.length;\n }\n return output;\n}\nlet encodeUTF8_;\nexport function encodeUTF8(str) {\n let encoder;\n return (encodeUTF8_ ??\n ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);\n}\nlet decodeUTF8_;\nexport function decodeUTF8(bytes) {\n let decoder;\n return (decodeUTF8_ ??\n ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);\n}\n//# sourceMappingURL=bytes.mjs.map","var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../tslib.mjs\";\nimport { concatBytes, decodeUTF8, encodeUTF8 } from \"../utils/bytes.mjs\";\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n constructor() {\n _LineDecoder_buffer.set(this, void 0);\n _LineDecoder_carriageReturnIndex.set(this, void 0);\n __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), \"f\");\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n }\n decode(chunk) {\n if (chunk == null) {\n return [];\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? encodeUTF8(chunk)\n : chunk;\n __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\"), binaryChunk]), \"f\");\n const lines = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\"))) != null) {\n if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, \"f\");\n continue;\n }\n // we got double \\r or \\rtext\\n\n if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") != null &&\n (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") + 1 || patternIndex.carriage)) {\n lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") - 1)));\n __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\")), \"f\");\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n continue;\n }\n const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, \"f\") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(0, endIndex));\n lines.push(line);\n __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").subarray(patternIndex.index), \"f\");\n __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, \"f\");\n }\n return lines;\n }\n flush() {\n if (!__classPrivateFieldGet(this, _LineDecoder_buffer, \"f\").length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap();\n// prettier-ignore\nLineDecoder.NEWLINE_CHARS = new Set(['\\n', '\\r']);\nLineDecoder.NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(buffer, startIndex) {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n return null;\n}\nexport function findDoubleNewlineIndex(buffer) {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = 0; i < buffer.length - 1; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n return -1;\n}\n//# sourceMappingURL=line.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { hasOwn } from \"./values.mjs\";\nconst levelNumbers = {\n off: 0,\n error: 200,\n warn: 300,\n info: 400,\n debug: 500,\n};\nexport const parseLogLevel = (maybeLevel, sourceName, client) => {\n if (!maybeLevel) {\n return undefined;\n }\n if (hasOwn(levelNumbers, maybeLevel)) {\n return maybeLevel;\n }\n loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);\n return undefined;\n};\nfunction noop() { }\nfunction makeLogFn(fnLevel, logger, logLevel) {\n if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {\n return noop;\n }\n else {\n // Don't wrap logger functions, we want the stacktrace intact!\n return logger[fnLevel].bind(logger);\n }\n}\nconst noopLogger = {\n error: noop,\n warn: noop,\n info: noop,\n debug: noop,\n};\nlet cachedLoggers = /* @__PURE__ */ new WeakMap();\nexport function loggerFor(client) {\n const logger = client.logger;\n const logLevel = client.logLevel ?? 'off';\n if (!logger) {\n return noopLogger;\n }\n const cachedLogger = cachedLoggers.get(logger);\n if (cachedLogger && cachedLogger[0] === logLevel) {\n return cachedLogger[1];\n }\n const levelLogger = {\n error: makeLogFn('error', logger, logLevel),\n warn: makeLogFn('warn', logger, logLevel),\n info: makeLogFn('info', logger, logLevel),\n debug: makeLogFn('debug', logger, logLevel),\n };\n cachedLoggers.set(logger, [logLevel, levelLogger]);\n return levelLogger;\n}\nexport const formatRequestDetails = (details) => {\n if (details.options) {\n details.options = { ...details.options };\n delete details.options['headers']; // redundant + leaks internals\n }\n if (details.headers) {\n details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [\n name,\n (name.toLowerCase() === 'authorization' ||\n name.toLowerCase() === 'cookie' ||\n name.toLowerCase() === 'set-cookie') ?\n '***'\n : value,\n ]));\n }\n if ('retryOfRequestLogID' in details) {\n if (details.retryOfRequestLogID) {\n details.retryOf = details.retryOfRequestLogID;\n }\n delete details.retryOfRequestLogID;\n }\n return details;\n};\n//# sourceMappingURL=log.mjs.map","var _Stream_client;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { OpenAIError } from \"./error.mjs\";\nimport { makeReadableStream } from \"../internal/shims.mjs\";\nimport { findDoubleNewlineIndex, LineDecoder } from \"../internal/decoders/line.mjs\";\nimport { ReadableStreamToAsyncIterable } from \"../internal/shims.mjs\";\nimport { isAbortError } from \"../internal/errors.mjs\";\nimport { encodeUTF8 } from \"../internal/utils/bytes.mjs\";\nimport { loggerFor } from \"../internal/utils/log.mjs\";\nimport { APIError } from \"./error.mjs\";\nexport class Stream {\n constructor(iterator, controller, client) {\n this.iterator = iterator;\n _Stream_client.set(this, void 0);\n this.controller = controller;\n __classPrivateFieldSet(this, _Stream_client, client, \"f\");\n }\n static fromSSEResponse(response, controller, client) {\n let consumed = false;\n const logger = client ? loggerFor(client) : console;\n async function* iterator() {\n if (consumed) {\n throw new OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (done)\n continue;\n if (sse.data.startsWith('[DONE]')) {\n done = true;\n continue;\n }\n if (sse.event === null || !sse.event.startsWith('thread.')) {\n let data;\n try {\n data = JSON.parse(sse.data);\n }\n catch (e) {\n logger.error(`Could not parse message into JSON:`, sse.data);\n logger.error(`From chunk:`, sse.raw);\n throw e;\n }\n if (data && data.error) {\n throw new APIError(undefined, data.error, undefined, response.headers);\n }\n yield data;\n }\n else {\n let data;\n try {\n data = JSON.parse(sse.data);\n }\n catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n // TODO: Is this where the error should be thrown?\n if (sse.event == 'error') {\n throw new APIError(undefined, data.error, data.message, undefined);\n }\n yield { event: sse.event, data: data };\n }\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (isAbortError(e))\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller, client);\n }\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream(readableStream, controller, client) {\n let consumed = false;\n async function* iterLines() {\n const lineDecoder = new LineDecoder();\n const iter = ReadableStreamToAsyncIterable(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n async function* iterator() {\n if (consumed) {\n throw new OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done)\n continue;\n if (line)\n yield JSON.parse(line);\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (isAbortError(e))\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller, client);\n }\n [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {\n return this.iterator();\n }\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee() {\n const left = [];\n const right = [];\n const iterator = this.iterator();\n const teeIterator = (queue) => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift();\n },\n };\n };\n return [\n new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, \"f\")),\n new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, \"f\")),\n ];\n }\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream() {\n const self = this;\n let iter;\n return makeReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl) {\n try {\n const { value, done } = await iter.next();\n if (done)\n return ctrl.close();\n const bytes = encodeUTF8(JSON.stringify(value) + '\\n');\n ctrl.enqueue(bytes);\n }\n catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\nexport async function* _iterSSEMessages(response, controller) {\n if (!response.body) {\n controller.abort();\n if (typeof globalThis.navigator !== 'undefined' &&\n globalThis.navigator.product === 'ReactNative') {\n throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);\n }\n throw new OpenAIError(`Attempted to iterate over a response with no body`);\n }\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n const iter = ReadableStreamToAsyncIterable(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n }\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n}\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator) {\n let data = new Uint8Array();\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? encodeUTF8(chunk)\n : chunk;\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n if (data.length > 0) {\n yield data;\n }\n}\nclass SSEDecoder {\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n decode(line) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length)\n return null;\n const sse = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n this.event = null;\n this.data = [];\n this.chunks = [];\n return sse;\n }\n this.chunks.push(line);\n if (line.startsWith(':')) {\n return null;\n }\n let [fieldname, _, value] = partition(line, ':');\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n if (fieldname === 'event') {\n this.event = value;\n }\n else if (fieldname === 'data') {\n this.data.push(value);\n }\n return null;\n }\n}\nfunction partition(str, delimiter) {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n return [str, '', ''];\n}\n//# sourceMappingURL=streaming.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { Stream } from \"../core/streaming.mjs\";\nimport { formatRequestDetails, loggerFor } from \"./utils/log.mjs\";\nexport async function defaultParseResponse(client, props) {\n const { response, requestLogID, retryOfRequestLogID, startTime } = props;\n const body = await (async () => {\n if (props.options.stream) {\n loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream`\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller, client);\n }\n return Stream.fromSSEResponse(response, props.controller, client);\n }\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null;\n }\n if (props.options.__binaryResponse) {\n return response;\n }\n const contentType = response.headers.get('content-type');\n const mediaType = contentType?.split(';')[0]?.trim();\n const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');\n if (isJSON) {\n const json = await response.json();\n return addRequestID(json, response);\n }\n const text = await response.text();\n return text;\n })();\n loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n body,\n durationMs: Date.now() - startTime,\n }));\n return body;\n}\nexport function addRequestID(value, response) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('x-request-id'),\n enumerable: false,\n });\n}\n//# sourceMappingURL=parse.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _APIPromise_client;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { defaultParseResponse, addRequestID, } from \"../internal/parse.mjs\";\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise extends Promise {\n constructor(client, responsePromise, parseResponse = defaultParseResponse) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null);\n });\n this.responsePromise = responsePromise;\n this.parseResponse = parseResponse;\n _APIPromise_client.set(this, void 0);\n __classPrivateFieldSet(this, _APIPromise_client, client, \"f\");\n }\n _thenUnwrap(transform) {\n return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, \"f\"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));\n }\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n * to your `tsconfig.json`.\n */\n asResponse() {\n return this.responsePromise.then((p) => p.response);\n }\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned via the X-Request-ID header which is useful for debugging requests and reporting\n * issues to OpenAI.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n * to your `tsconfig.json`.\n */\n async withResponse() {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('x-request-id') };\n }\n parse() {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, \"f\"), data));\n }\n return this.parsedPromise;\n }\n then(onfulfilled, onrejected) {\n return this.parse().then(onfulfilled, onrejected);\n }\n catch(onrejected) {\n return this.parse().catch(onrejected);\n }\n finally(onfinally) {\n return this.parse().finally(onfinally);\n }\n}\n_APIPromise_client = new WeakMap();\n//# sourceMappingURL=api-promise.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _AbstractPage_client;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { OpenAIError } from \"./error.mjs\";\nimport { defaultParseResponse } from \"../internal/parse.mjs\";\nimport { APIPromise } from \"./api-promise.mjs\";\nimport { maybeObj } from \"../internal/utils/values.mjs\";\nexport class AbstractPage {\n constructor(client, response, body, options) {\n _AbstractPage_client.set(this, void 0);\n __classPrivateFieldSet(this, _AbstractPage_client, client, \"f\");\n this.options = options;\n this.response = response;\n this.body = body;\n }\n hasNextPage() {\n const items = this.getPaginatedItems();\n if (!items.length)\n return false;\n return this.nextPageRequestOptions() != null;\n }\n async getNextPage() {\n const nextOptions = this.nextPageRequestOptions();\n if (!nextOptions) {\n throw new OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');\n }\n return await __classPrivateFieldGet(this, _AbstractPage_client, \"f\").requestAPIList(this.constructor, nextOptions);\n }\n async *iterPages() {\n let page = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise extends APIPromise {\n constructor(client, request, Page) {\n super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));\n }\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator]() {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class Page extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.object = body.object;\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n nextPageRequestOptions() {\n return null;\n }\n}\nexport class CursorPage extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n hasNextPage() {\n if (this.has_more === false) {\n return false;\n }\n return super.hasNextPage();\n }\n nextPageRequestOptions() {\n const data = this.getPaginatedItems();\n const id = data[data.length - 1]?.id;\n if (!id) {\n return null;\n }\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n after: id,\n },\n };\n }\n}\nexport class ConversationCursorPage extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n this.last_id = body.last_id || '';\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n hasNextPage() {\n if (this.has_more === false) {\n return false;\n }\n return super.hasNextPage();\n }\n nextPageRequestOptions() {\n const cursor = this.last_id;\n if (!cursor) {\n return null;\n }\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n after: cursor,\n },\n };\n }\n}\n//# sourceMappingURL=pagination.mjs.map","import { ReadableStreamFrom } from \"./shims.mjs\";\nexport const checkFileSupport = () => {\n if (typeof File === 'undefined') {\n const { process } = globalThis;\n const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20;\n throw new Error('`File` is not defined as a global, which is required for file uploads.' +\n (isOldNode ?\n \" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.\"\n : ''));\n }\n};\n/**\n * Construct a `File` instance. This is used to ensure a helpful error is thrown\n * for environments that don't define a global `File` yet.\n */\nexport function makeFile(fileBits, fileName, options) {\n checkFileSupport();\n return new File(fileBits, fileName ?? 'unknown_file', options);\n}\nexport function getName(value) {\n return (((typeof value === 'object' &&\n value !== null &&\n (('name' in value && value.name && String(value.name)) ||\n ('url' in value && value.url && String(value.url)) ||\n ('filename' in value && value.filename && String(value.filename)) ||\n ('path' in value && value.path && String(value.path)))) ||\n '')\n .split(/[\\\\/]/)\n .pop() || undefined);\n}\nexport const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async (opts, fetch) => {\n if (!hasUploadableValue(opts.body))\n return opts;\n return { ...opts, body: await createForm(opts.body, fetch) };\n};\nexport const multipartFormRequestOptions = async (opts, fetch) => {\n return { ...opts, body: await createForm(opts.body, fetch) };\n};\nconst supportsFormDataMap = /* @__PURE__ */ new WeakMap();\n/**\n * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending\n * properly-encoded form data, it just stringifies the object, resulting in a request body of \"[object FormData]\".\n * This function detects if the fetch function provided supports the global FormData object to avoid\n * confusing error messages later on.\n */\nfunction supportsFormData(fetchObject) {\n const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch;\n const cached = supportsFormDataMap.get(fetch);\n if (cached)\n return cached;\n const promise = (async () => {\n try {\n const FetchResponse = ('Response' in fetch ?\n fetch.Response\n : (await fetch('data:,')).constructor);\n const data = new FormData();\n if (data.toString() === (await new FetchResponse(data).text())) {\n return false;\n }\n return true;\n }\n catch {\n // avoid false negatives\n return true;\n }\n })();\n supportsFormDataMap.set(fetch, promise);\n return promise;\n}\nexport const createForm = async (body, fetch) => {\n if (!(await supportsFormData(fetch))) {\n throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.');\n }\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\n// We check for Blob not File because Bun.File doesn't inherit from File,\n// but they both inherit from Blob and have a `name` property at runtime.\nconst isNamedBlob = (value) => value instanceof Blob && 'name' in value;\nconst isUploadable = (value) => typeof value === 'object' &&\n value !== null &&\n (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value));\nconst hasUploadableValue = (value) => {\n if (isUploadable(value))\n return true;\n if (Array.isArray(value))\n return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue(value[k]))\n return true;\n }\n }\n return false;\n};\nconst addFormValue = async (form, key, value) => {\n if (value === undefined)\n return;\n if (value == null) {\n throw new TypeError(`Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`);\n }\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n }\n else if (value instanceof Response) {\n form.append(key, makeFile([await value.blob()], getName(value)));\n }\n else if (isAsyncIterable(value)) {\n form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value)));\n }\n else if (isNamedBlob(value)) {\n form.append(key, value, getName(value));\n }\n else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n }\n else if (typeof value === 'object') {\n await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));\n }\n else {\n throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);\n }\n};\n//# sourceMappingURL=uploads.mjs.map","import { getName, makeFile, isAsyncIterable } from \"./uploads.mjs\";\nimport { checkFileSupport } from \"./uploads.mjs\";\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isBlobLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isFileLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\nconst isResponseLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(value, name, options) {\n checkFileSupport();\n // If it's a promise, resolve it.\n value = await value;\n // If we've been given a `File` we don't need to do anything\n if (isFileLike(value)) {\n if (value instanceof File) {\n return value;\n }\n return makeFile([await value.arrayBuffer()], value.name);\n }\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name || (name = new URL(value.url).pathname.split(/[\\\\/]/).pop());\n return makeFile(await getBytes(blob), name, options);\n }\n const parts = await getBytes(value);\n name || (name = getName(value));\n if (!options?.type) {\n const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n return makeFile(parts, name, options);\n}\nasync function getBytes(value) {\n let parts = [];\n if (typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer) {\n parts.push(value);\n }\n else if (isBlobLike(value)) {\n parts.push(value instanceof Blob ? value : await value.arrayBuffer());\n }\n else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(...(await getBytes(chunk))); // TODO, consider validating?\n }\n }\n else {\n const constructor = value?.constructor?.name;\n throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);\n }\n return parts;\n}\nfunction propsForError(value) {\n if (typeof value !== 'object' || value === null)\n return '';\n const props = Object.getOwnPropertyNames(value);\n return `; props: [${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n//# sourceMappingURL=to-file.mjs.map","export { toFile } from \"../internal/to-file.mjs\";\n//# sourceMappingURL=uploads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport class APIResource {\n constructor(client) {\n this._client = client;\n }\n}\n//# sourceMappingURL=resource.mjs.map","import { OpenAIError } from \"../../core/error.mjs\";\n/**\n * Percent-encode everything that isn't safe to have in a path without encoding safe chars.\n *\n * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:\n * > unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n * > sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\" / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n * > pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n */\nexport function encodeURIPath(str) {\n return str.replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);\n}\nconst EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));\nexport const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) {\n // If there are no params, no processing is needed.\n if (statics.length === 1)\n return statics[0];\n let postPath = false;\n const invalidSegments = [];\n const path = statics.reduce((previousValue, currentValue, index) => {\n if (/[?#]/.test(currentValue)) {\n postPath = true;\n }\n const value = params[index];\n let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);\n if (index !== params.length &&\n (value == null ||\n (typeof value === 'object' &&\n // handle values from other realms\n value.toString ===\n Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)\n ?.toString))) {\n encoded = value + '';\n invalidSegments.push({\n start: previousValue.length + currentValue.length,\n length: encoded.length,\n error: `Value of type ${Object.prototype.toString\n .call(value)\n .slice(8, -1)} is not a valid path parameter`,\n });\n }\n return previousValue + currentValue + (index === params.length ? '' : encoded);\n }, '');\n const pathOnly = path.split(/[?#]/, 1)[0];\n const invalidSegmentPattern = /(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;\n let match;\n // Find all invalid segments\n while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {\n invalidSegments.push({\n start: match.index,\n length: match[0].length,\n error: `Value \"${match[0]}\" can\\'t be safely passed as a path parameter`,\n });\n }\n invalidSegments.sort((a, b) => a.start - b.start);\n if (invalidSegments.length > 0) {\n let lastEnd = 0;\n const underline = invalidSegments.reduce((acc, segment) => {\n const spaces = ' '.repeat(segment.start - lastEnd);\n const arrows = '^'.repeat(segment.length);\n lastEnd = segment.start + segment.length;\n return acc + spaces + arrows;\n }, '');\n throw new OpenAIError(`Path parameters result in path with invalid segments:\\n${invalidSegments\n .map((e) => e.error)\n .join('\\n')}\\n${path}\\n${underline}`);\n }\n return path;\n};\n/**\n * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.\n */\nexport const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);\n//# sourceMappingURL=path.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Messages extends APIResource {\n /**\n * Get the messages in a stored chat completion. Only Chat Completions that have\n * been created with the `store` parameter set to `true` will be returned.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(\n * 'completion_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(completionID, query = {}, options) {\n return this._client.getAPIList(path `/chat/completions/${completionID}/messages`, (CursorPage), { query, ...options });\n }\n}\n//# sourceMappingURL=messages.mjs.map","export const isAssistantMessage = (message) => {\n return message?.role === 'assistant';\n};\nexport const isToolMessage = (message) => {\n return message?.role === 'tool';\n};\nexport function isPresent(obj) {\n return obj != null;\n}\n//# sourceMappingURL=chatCompletionUtils.mjs.map","var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { APIUserAbortError, OpenAIError } from \"../error.mjs\";\nexport class EventStream {\n constructor() {\n _EventStream_instances.add(this);\n this.controller = new AbortController();\n _EventStream_connectedPromise.set(this, void 0);\n _EventStream_resolveConnectedPromise.set(this, () => { });\n _EventStream_rejectConnectedPromise.set(this, () => { });\n _EventStream_endPromise.set(this, void 0);\n _EventStream_resolveEndPromise.set(this, () => { });\n _EventStream_rejectEndPromise.set(this, () => { });\n _EventStream_listeners.set(this, {});\n _EventStream_ended.set(this, false);\n _EventStream_errored.set(this, false);\n _EventStream_aborted.set(this, false);\n _EventStream_catchingPromiseCreated.set(this, false);\n __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, \"f\");\n }), \"f\");\n __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, \"f\");\n }), \"f\");\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n __classPrivateFieldGet(this, _EventStream_connectedPromise, \"f\").catch(() => { });\n __classPrivateFieldGet(this, _EventStream_endPromise, \"f\").catch(() => { });\n }\n _run(executor) {\n // Unfortunately if we call `executor()` immediately we get runtime errors about\n // references to `this` before the `super()` constructor call returns.\n setTimeout(() => {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, __classPrivateFieldGet(this, _EventStream_instances, \"m\", _EventStream_handleError).bind(this));\n }, 0);\n }\n _connected() {\n if (this.ended)\n return;\n __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, \"f\").call(this);\n this._emit('connect');\n }\n get ended() {\n return __classPrivateFieldGet(this, _EventStream_ended, \"f\");\n }\n get errored() {\n return __classPrivateFieldGet(this, _EventStream_errored, \"f\");\n }\n get aborted() {\n return __classPrivateFieldGet(this, _EventStream_aborted, \"f\");\n }\n abort() {\n this.controller.abort();\n }\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n on(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = []);\n listeners.push({ listener });\n return this;\n }\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n off(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event];\n if (!listeners)\n return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0)\n listeners.splice(index, 1);\n return this;\n }\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n once(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted(event) {\n return new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, \"f\");\n if (event !== 'error')\n this.once('error', reject);\n this.once(event, resolve);\n });\n }\n async done() {\n __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, \"f\");\n await __classPrivateFieldGet(this, _EventStream_endPromise, \"f\");\n }\n _emit(event, ...args) {\n // make sure we don't emit any events after end\n if (__classPrivateFieldGet(this, _EventStream_ended, \"f\")) {\n return;\n }\n if (event === 'end') {\n __classPrivateFieldSet(this, _EventStream_ended, true, \"f\");\n __classPrivateFieldGet(this, _EventStream_resolveEndPromise, \"f\").call(this);\n }\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event];\n if (listeners) {\n __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = listeners.filter((l) => !l.once);\n listeners.forEach(({ listener }) => listener(...args));\n }\n if (event === 'abort') {\n const error = args[0];\n if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _EventStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n return;\n }\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n const error = args[0];\n if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.finalChatCompletion()\n // - etc.\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _EventStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n }\n }\n _emitFinal() { }\n}\n_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) {\n __classPrivateFieldSet(this, _EventStream_errored, true, \"f\");\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n __classPrivateFieldSet(this, _EventStream_aborted, true, \"f\");\n return this._emit('abort', error);\n }\n if (error instanceof OpenAIError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const openAIError = new OpenAIError(error.message);\n // @ts-ignore\n openAIError.cause = error;\n return this._emit('error', openAIError);\n }\n return this._emit('error', new OpenAIError(String(error)));\n};\n//# sourceMappingURL=EventStream.mjs.map","export function isRunnableFunctionWithParse(fn) {\n return typeof fn.parse === 'function';\n}\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n */\nexport class ParsingToolFunction {\n constructor(input) {\n this.type = 'function';\n this.function = input;\n }\n}\n//# sourceMappingURL=RunnableFunction.mjs.map","var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult;\nimport { __classPrivateFieldGet } from \"../internal/tslib.mjs\";\nimport { OpenAIError } from \"../error.mjs\";\nimport { isAutoParsableTool, parseChatCompletion } from \"../lib/parser.mjs\";\nimport { isAssistantMessage, isToolMessage } from \"./chatCompletionUtils.mjs\";\nimport { EventStream } from \"./EventStream.mjs\";\nimport { isRunnableFunctionWithParse, } from \"./RunnableFunction.mjs\";\nconst DEFAULT_MAX_CHAT_COMPLETIONS = 10;\nexport class AbstractChatCompletionRunner extends EventStream {\n constructor() {\n super(...arguments);\n _AbstractChatCompletionRunner_instances.add(this);\n this._chatCompletions = [];\n this.messages = [];\n }\n _addChatCompletion(chatCompletion) {\n this._chatCompletions.push(chatCompletion);\n this._emit('chatCompletion', chatCompletion);\n const message = chatCompletion.choices[0]?.message;\n if (message)\n this._addMessage(message);\n return chatCompletion;\n }\n _addMessage(message, emit = true) {\n if (!('content' in message))\n message.content = null;\n this.messages.push(message);\n if (emit) {\n this._emit('message', message);\n if (isToolMessage(message) && message.content) {\n // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function.\n this._emit('functionToolCallResult', message.content);\n }\n else if (isAssistantMessage(message) && message.tool_calls) {\n for (const tool_call of message.tool_calls) {\n if (tool_call.type === 'function') {\n this._emit('functionToolCall', tool_call.function);\n }\n }\n }\n }\n }\n /**\n * @returns a promise that resolves with the final ChatCompletion, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletion.\n */\n async finalChatCompletion() {\n await this.done();\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (!completion)\n throw new OpenAIError('stream ended without producing a ChatCompletion');\n return completion;\n }\n /**\n * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalContent() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalContent).call(this);\n }\n /**\n * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,\n * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalMessage() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this);\n }\n /**\n * @returns a promise that resolves with the content of the final FunctionCall, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalFunctionToolCall() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);\n }\n async finalFunctionToolCallResult() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);\n }\n async totalUsage() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);\n }\n allChatCompletions() {\n return [...this._chatCompletions];\n }\n _emitFinal() {\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (completion)\n this._emit('finalChatCompletion', completion);\n const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this);\n if (finalMessage)\n this._emit('finalMessage', finalMessage);\n const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalContent).call(this);\n if (finalContent)\n this._emit('finalContent', finalContent);\n const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);\n if (finalFunctionCall)\n this._emit('finalFunctionToolCall', finalFunctionCall);\n const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);\n if (finalFunctionCallResult != null)\n this._emit('finalFunctionToolCallResult', finalFunctionCallResult);\n if (this._chatCompletions.some((c) => c.usage)) {\n this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));\n }\n }\n async _createChatCompletion(client, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_validateParams).call(this, params);\n const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });\n this._connected();\n return this._addChatCompletion(parseChatCompletion(chatCompletion, params));\n }\n async _runChatCompletion(client, params, options) {\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n return await this._createChatCompletion(client, params, options);\n }\n async _runTools(client, params, options) {\n const role = 'tool';\n const { tool_choice = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n // TODO(someday): clean this logic up\n const inputTools = params.tools.map((tool) => {\n if (isAutoParsableTool(tool)) {\n if (!tool.$callback) {\n throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function');\n }\n return {\n type: 'function',\n function: {\n function: tool.$callback,\n name: tool.function.name,\n description: tool.function.description || '',\n parameters: tool.function.parameters,\n parse: tool.$parseRaw,\n strict: true,\n },\n };\n }\n return tool;\n });\n const functionsByName = {};\n for (const f of inputTools) {\n if (f.type === 'function') {\n functionsByName[f.function.name || f.function.function.name] = f.function;\n }\n }\n const tools = 'tools' in params ?\n inputTools.map((t) => t.type === 'function' ?\n {\n type: 'function',\n function: {\n name: t.function.name || t.function.function.name,\n parameters: t.function.parameters,\n description: t.function.description,\n strict: t.function.strict,\n },\n }\n : t)\n : undefined;\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion = await this._createChatCompletion(client, {\n ...restParams,\n tool_choice,\n tools,\n messages: [...this.messages],\n }, options);\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.tool_calls?.length) {\n return;\n }\n for (const tool_call of message.tool_calls) {\n if (tool_call.type !== 'function')\n continue;\n const tool_call_id = tool_call.id;\n const { name, arguments: args } = tool_call.function;\n const fn = functionsByName[name];\n if (!fn) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName)\n .map((name) => JSON.stringify(name))\n .join(', ')}. Please try again`;\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n }\n catch (error) {\n const content = error instanceof Error ? error.message : String(error);\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);\n this._addMessage({ role, tool_call_id, content });\n if (singleFunctionToCall) {\n return;\n }\n }\n }\n return;\n }\n}\n_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() {\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;\n}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() {\n let i = this.messages.length;\n while (i-- > 0) {\n const message = this.messages[i];\n if (isAssistantMessage(message)) {\n // TODO: support audio here\n const ret = {\n ...message,\n content: message.content ?? null,\n refusal: message.refusal ?? null,\n };\n return ret;\n }\n }\n throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant');\n}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isAssistantMessage(message) && message?.tool_calls?.length) {\n return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function;\n }\n }\n return;\n}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isToolMessage(message) &&\n message.content != null &&\n typeof message.content === 'string' &&\n this.messages.some((x) => x.role === 'assistant' &&\n x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) {\n return message.content;\n }\n }\n return;\n}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() {\n const total = {\n completion_tokens: 0,\n prompt_tokens: 0,\n total_tokens: 0,\n };\n for (const { usage } of this._chatCompletions) {\n if (usage) {\n total.completion_tokens += usage.completion_tokens;\n total.prompt_tokens += usage.prompt_tokens;\n total.total_tokens += usage.total_tokens;\n }\n }\n return total;\n}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) {\n if (params.n != null && params.n > 1) {\n throw new OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.');\n }\n}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) {\n return (typeof rawContent === 'string' ? rawContent\n : rawContent === undefined ? 'undefined'\n : JSON.stringify(rawContent));\n};\n//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map","import { AbstractChatCompletionRunner, } from \"./AbstractChatCompletionRunner.mjs\";\nimport { isAssistantMessage } from \"./chatCompletionUtils.mjs\";\nexport class ChatCompletionRunner extends AbstractChatCompletionRunner {\n static runTools(client, params, options) {\n const runner = new ChatCompletionRunner();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n _addMessage(message, emit = true) {\n super._addMessage(message, emit);\n if (isAssistantMessage(message) && message.content) {\n this._emit('content', message.content);\n }\n }\n}\n//# sourceMappingURL=ChatCompletionRunner.mjs.map","const STR = 0b000000001;\nconst NUM = 0b000000010;\nconst ARR = 0b000000100;\nconst OBJ = 0b000001000;\nconst NULL = 0b000010000;\nconst BOOL = 0b000100000;\nconst NAN = 0b001000000;\nconst INFINITY = 0b010000000;\nconst MINUS_INFINITY = 0b100000000;\nconst INF = INFINITY | MINUS_INFINITY;\nconst SPECIAL = NULL | BOOL | INF | NAN;\nconst ATOM = STR | NUM | SPECIAL;\nconst COLLECTION = ARR | OBJ;\nconst ALL = ATOM | COLLECTION;\nconst Allow = {\n STR,\n NUM,\n ARR,\n OBJ,\n NULL,\n BOOL,\n NAN,\n INFINITY,\n MINUS_INFINITY,\n INF,\n SPECIAL,\n ATOM,\n COLLECTION,\n ALL,\n};\n// The JSON string segment was unable to be parsed completely\nclass PartialJSON extends Error {\n}\nclass MalformedJSON extends Error {\n}\n/**\n * Parse incomplete JSON\n * @param {string} jsonString Partial JSON to be parsed\n * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details\n * @returns The parsed JSON\n * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)\n * @throws {MalformedJSON} If the JSON is malformed\n */\nfunction parseJSON(jsonString, allowPartial = Allow.ALL) {\n if (typeof jsonString !== 'string') {\n throw new TypeError(`expecting str, got ${typeof jsonString}`);\n }\n if (!jsonString.trim()) {\n throw new Error(`${jsonString} is empty`);\n }\n return _parseJSON(jsonString.trim(), allowPartial);\n}\nconst _parseJSON = (jsonString, allow) => {\n const length = jsonString.length;\n let index = 0;\n const markPartialJSON = (msg) => {\n throw new PartialJSON(`${msg} at position ${index}`);\n };\n const throwMalformedError = (msg) => {\n throw new MalformedJSON(`${msg} at position ${index}`);\n };\n const parseAny = () => {\n skipBlank();\n if (index >= length)\n markPartialJSON('Unexpected end of input');\n if (jsonString[index] === '\"')\n return parseStr();\n if (jsonString[index] === '{')\n return parseObj();\n if (jsonString[index] === '[')\n return parseArr();\n if (jsonString.substring(index, index + 4) === 'null' ||\n (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) {\n index += 4;\n return null;\n }\n if (jsonString.substring(index, index + 4) === 'true' ||\n (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) {\n index += 4;\n return true;\n }\n if (jsonString.substring(index, index + 5) === 'false' ||\n (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) {\n index += 5;\n return false;\n }\n if (jsonString.substring(index, index + 8) === 'Infinity' ||\n (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) {\n index += 8;\n return Infinity;\n }\n if (jsonString.substring(index, index + 9) === '-Infinity' ||\n (Allow.MINUS_INFINITY & allow &&\n 1 < length - index &&\n length - index < 9 &&\n '-Infinity'.startsWith(jsonString.substring(index)))) {\n index += 9;\n return -Infinity;\n }\n if (jsonString.substring(index, index + 3) === 'NaN' ||\n (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) {\n index += 3;\n return NaN;\n }\n return parseNum();\n };\n const parseStr = () => {\n const start = index;\n let escape = false;\n index++; // skip initial quote\n while (index < length && (jsonString[index] !== '\"' || (escape && jsonString[index - 1] === '\\\\'))) {\n escape = jsonString[index] === '\\\\' ? !escape : false;\n index++;\n }\n if (jsonString.charAt(index) == '\"') {\n try {\n return JSON.parse(jsonString.substring(start, ++index - Number(escape)));\n }\n catch (e) {\n throwMalformedError(String(e));\n }\n }\n else if (Allow.STR & allow) {\n try {\n return JSON.parse(jsonString.substring(start, index - Number(escape)) + '\"');\n }\n catch (e) {\n // SyntaxError: Invalid escape sequence\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\\\')) + '\"');\n }\n }\n markPartialJSON('Unterminated string literal');\n };\n const parseObj = () => {\n index++; // skip initial brace\n skipBlank();\n const obj = {};\n try {\n while (jsonString[index] !== '}') {\n skipBlank();\n if (index >= length && Allow.OBJ & allow)\n return obj;\n const key = parseStr();\n skipBlank();\n index++; // skip colon\n try {\n const value = parseAny();\n Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });\n }\n catch (e) {\n if (Allow.OBJ & allow)\n return obj;\n else\n throw e;\n }\n skipBlank();\n if (jsonString[index] === ',')\n index++; // skip comma\n }\n }\n catch (e) {\n if (Allow.OBJ & allow)\n return obj;\n else\n markPartialJSON(\"Expected '}' at end of object\");\n }\n index++; // skip final brace\n return obj;\n };\n const parseArr = () => {\n index++; // skip initial bracket\n const arr = [];\n try {\n while (jsonString[index] !== ']') {\n arr.push(parseAny());\n skipBlank();\n if (jsonString[index] === ',') {\n index++; // skip comma\n }\n }\n }\n catch (e) {\n if (Allow.ARR & allow) {\n return arr;\n }\n markPartialJSON(\"Expected ']' at end of array\");\n }\n index++; // skip final bracket\n return arr;\n };\n const parseNum = () => {\n if (index === 0) {\n if (jsonString === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString);\n }\n catch (e) {\n if (Allow.NUM & allow) {\n try {\n if ('.' === jsonString[jsonString.length - 1])\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.')));\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e')));\n }\n catch (e) { }\n }\n throwMalformedError(String(e));\n }\n }\n const start = index;\n if (jsonString[index] === '-')\n index++;\n while (jsonString[index] && !',]}'.includes(jsonString[index]))\n index++;\n if (index == length && !(Allow.NUM & allow))\n markPartialJSON('Unterminated number literal');\n try {\n return JSON.parse(jsonString.substring(start, index));\n }\n catch (e) {\n if (jsonString.substring(start, index) === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e')));\n }\n catch (e) {\n throwMalformedError(String(e));\n }\n }\n };\n const skipBlank = () => {\n while (index < length && ' \\n\\r\\t'.includes(jsonString[index])) {\n index++;\n }\n };\n return parseAny();\n};\n// using this function with malformed JSON is undefined behavior\nconst partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);\nexport { partialParse, PartialJSON, MalformedJSON };\n//# sourceMappingURL=parser.mjs.map","export * from \"./core/streaming.mjs\";\n//# sourceMappingURL=streaming.mjs.map","var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.mjs\";\nimport { APIUserAbortError, ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError, } from \"../error.mjs\";\nimport { hasAutoParseableInput, isAutoParsableResponseFormat, isAutoParsableTool, isChatCompletionFunctionTool, maybeParseChatCompletion, shouldParseToolCall, } from \"../lib/parser.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { AbstractChatCompletionRunner, } from \"./AbstractChatCompletionRunner.mjs\";\nexport class ChatCompletionStream extends AbstractChatCompletionRunner {\n constructor(params) {\n super();\n _ChatCompletionStream_instances.add(this);\n _ChatCompletionStream_params.set(this, void 0);\n _ChatCompletionStream_choiceEventStates.set(this, void 0);\n _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);\n __classPrivateFieldSet(this, _ChatCompletionStream_params, params, \"f\");\n __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], \"f\");\n }\n get currentChatCompletionSnapshot() {\n return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n }\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream) {\n const runner = new ChatCompletionStream(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n static createChatCompletion(client, params, options) {\n const runner = new ChatCompletionStream(params);\n runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));\n return runner;\n }\n async _createChatCompletion(client, params, options) {\n super._createChatCompletion;\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_beginRequest).call(this);\n const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const chunk of stream) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_addChunk).call(this, chunk);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_beginRequest).call(this);\n this._connected();\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n let chatId;\n for await (const chunk of stream) {\n if (chatId && chatId !== chunk.id) {\n // A new request has been made.\n this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_addChunk).call(this, chunk);\n chatId = chunk.id;\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, \"f\");\n }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) {\n let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, \"f\")[choice.index];\n if (state) {\n return state;\n }\n state = {\n content_done: false,\n refusal_done: false,\n logprobs_content_done: false,\n logprobs_refusal_done: false,\n done_tool_calls: new Set(),\n current_tool_call_index: null,\n };\n __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, \"f\")[choice.index] = state;\n return state;\n }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) {\n if (this.ended)\n return;\n const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);\n this._emit('chunk', chunk, completion);\n for (const choice of chunk.choices) {\n const choiceSnapshot = completion.choices[choice.index];\n if (choice.delta.content != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.content) {\n this._emit('content', choice.delta.content, choiceSnapshot.message.content);\n this._emit('content.delta', {\n delta: choice.delta.content,\n snapshot: choiceSnapshot.message.content,\n parsed: choiceSnapshot.message.parsed,\n });\n }\n if (choice.delta.refusal != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.refusal) {\n this._emit('refusal.delta', {\n delta: choice.delta.refusal,\n snapshot: choiceSnapshot.message.refusal,\n });\n }\n if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.content.delta', {\n content: choice.logprobs?.content,\n snapshot: choiceSnapshot.logprobs?.content ?? [],\n });\n }\n if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.refusal.delta', {\n refusal: choice.logprobs?.refusal,\n snapshot: choiceSnapshot.logprobs?.refusal ?? [],\n });\n }\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (choiceSnapshot.finish_reason) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);\n if (state.current_tool_call_index != null) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);\n }\n }\n for (const toolCall of choice.delta.tool_calls ?? []) {\n if (state.current_tool_call_index !== toolCall.index) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);\n // new tool call started, the previous one is done\n if (state.current_tool_call_index != null) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);\n }\n }\n state.current_tool_call_index = toolCall.index;\n }\n for (const toolCallDelta of choice.delta.tool_calls ?? []) {\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];\n if (!toolCallSnapshot?.type) {\n continue;\n }\n if (toolCallSnapshot?.type === 'function') {\n this._emit('tool_calls.function.arguments.delta', {\n name: toolCallSnapshot.function?.name,\n index: toolCallDelta.index,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: toolCallSnapshot.function.parsed_arguments,\n arguments_delta: toolCallDelta.function?.arguments ?? '',\n });\n }\n else {\n assertNever(toolCallSnapshot?.type);\n }\n }\n }\n }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) {\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (state.done_tool_calls.has(toolCallIndex)) {\n // we've already fired the done event\n return;\n }\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];\n if (!toolCallSnapshot) {\n throw new Error('no tool call snapshot');\n }\n if (!toolCallSnapshot.type) {\n throw new Error('tool call snapshot missing `type`');\n }\n if (toolCallSnapshot.type === 'function') {\n const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); // TS doesn't narrow based on isChatCompletionTool\n this._emit('tool_calls.function.arguments.done', {\n name: toolCallSnapshot.function.name,\n index: toolCallIndex,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)\n : null,\n });\n }\n else {\n assertNever(toolCallSnapshot.type);\n }\n }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) {\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (choiceSnapshot.message.content && !state.content_done) {\n state.content_done = true;\n const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);\n this._emit('content.done', {\n content: choiceSnapshot.message.content,\n parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null,\n });\n }\n if (choiceSnapshot.message.refusal && !state.refusal_done) {\n state.refusal_done = true;\n this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal });\n }\n if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {\n state.logprobs_content_done = true;\n this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content });\n }\n if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {\n state.logprobs_refusal_done = true;\n this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal });\n }\n }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n if (!snapshot) {\n throw new OpenAIError(`request ended without sending any chunks`);\n }\n __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, \"f\");\n __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], \"f\");\n return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"));\n }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() {\n const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\")?.response_format;\n if (isAutoParsableResponseFormat(responseFormat)) {\n return responseFormat;\n }\n return null;\n }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) {\n var _a, _b, _c, _d;\n let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n const { choices, ...rest } = chunk;\n if (!snapshot) {\n snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, {\n ...rest,\n choices: [],\n }, \"f\");\n }\n else {\n Object.assign(snapshot, rest);\n }\n for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {\n let choice = snapshot.choices[index];\n if (!choice) {\n choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };\n }\n if (logprobs) {\n if (!choice.logprobs) {\n choice.logprobs = Object.assign({}, logprobs);\n }\n else {\n const { content, refusal, ...rest } = logprobs;\n assertIsEmpty(rest);\n Object.assign(choice.logprobs, rest);\n if (content) {\n (_a = choice.logprobs).content ?? (_a.content = []);\n choice.logprobs.content.push(...content);\n }\n if (refusal) {\n (_b = choice.logprobs).refusal ?? (_b.refusal = []);\n choice.logprobs.refusal.push(...refusal);\n }\n }\n }\n if (finish_reason) {\n choice.finish_reason = finish_reason;\n if (__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"))) {\n if (finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n }\n }\n Object.assign(choice, other);\n if (!delta)\n continue; // Shouldn't happen; just in case.\n const { content, refusal, function_call, role, tool_calls, ...rest } = delta;\n assertIsEmpty(rest);\n Object.assign(choice.message, rest);\n if (refusal) {\n choice.message.refusal = (choice.message.refusal || '') + refusal;\n }\n if (role)\n choice.message.role = role;\n if (function_call) {\n if (!choice.message.function_call) {\n choice.message.function_call = function_call;\n }\n else {\n if (function_call.name)\n choice.message.function_call.name = function_call.name;\n if (function_call.arguments) {\n (_c = choice.message.function_call).arguments ?? (_c.arguments = '');\n choice.message.function_call.arguments += function_call.arguments;\n }\n }\n }\n if (content) {\n choice.message.content = (choice.message.content || '') + content;\n if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {\n choice.message.parsed = partialParse(choice.message.content);\n }\n }\n if (tool_calls) {\n if (!choice.message.tool_calls)\n choice.message.tool_calls = [];\n for (const { index, id, type, function: fn, ...rest } of tool_calls) {\n const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {}));\n Object.assign(tool_call, rest);\n if (id)\n tool_call.id = id;\n if (type)\n tool_call.type = type;\n if (fn)\n tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' });\n if (fn?.name)\n tool_call.function.name = fn.name;\n if (fn?.arguments) {\n tool_call.function.arguments += fn.arguments;\n if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"), tool_call)) {\n tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);\n }\n }\n }\n }\n }\n return snapshot;\n }, Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n this.on('chunk', (chunk) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(chunk);\n }\n else {\n pushQueue.push(chunk);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\nfunction finalizeChatCompletion(snapshot, params) {\n const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;\n const completion = {\n ...rest,\n id,\n choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {\n if (!finish_reason) {\n throw new OpenAIError(`missing finish_reason for choice ${index}`);\n }\n const { content = null, function_call, tool_calls, ...messageRest } = message;\n const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine.\n if (!role) {\n throw new OpenAIError(`missing role for choice ${index}`);\n }\n if (function_call) {\n const { arguments: args, name } = function_call;\n if (args == null) {\n throw new OpenAIError(`missing function_call.arguments for choice ${index}`);\n }\n if (!name) {\n throw new OpenAIError(`missing function_call.name for choice ${index}`);\n }\n return {\n ...choiceRest,\n message: {\n content,\n function_call: { arguments: args, name },\n role,\n refusal: message.refusal ?? null,\n },\n finish_reason,\n index,\n logprobs,\n };\n }\n if (tool_calls) {\n return {\n ...choiceRest,\n index,\n finish_reason,\n logprobs,\n message: {\n ...messageRest,\n role,\n content,\n refusal: message.refusal ?? null,\n tool_calls: tool_calls.map((tool_call, i) => {\n const { function: fn, type, id, ...toolRest } = tool_call;\n const { arguments: args, name, ...fnRest } = fn || {};\n if (id == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\\n${str(snapshot)}`);\n }\n if (type == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\\n${str(snapshot)}`);\n }\n if (name == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\\n${str(snapshot)}`);\n }\n if (args == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\\n${str(snapshot)}`);\n }\n return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };\n }),\n },\n };\n }\n return {\n ...choiceRest,\n message: { ...messageRest, content, role, refusal: message.refusal ?? null },\n finish_reason,\n index,\n logprobs,\n };\n }),\n created,\n model,\n object: 'chat.completion',\n ...(system_fingerprint ? { system_fingerprint } : {}),\n };\n return maybeParseChatCompletion(completion, params);\n}\nfunction str(x) {\n return JSON.stringify(x);\n}\n/**\n * Ensures the given argument is an empty object, useful for\n * asserting that all known properties on an object have been\n * destructured.\n */\nfunction assertIsEmpty(obj) {\n return;\n}\nfunction assertNever(_x) { }\n//# sourceMappingURL=ChatCompletionStream.mjs.map","import { ChatCompletionStream } from \"./ChatCompletionStream.mjs\";\nexport class ChatCompletionStreamingRunner extends ChatCompletionStream {\n static fromReadableStream(stream) {\n const runner = new ChatCompletionStreamingRunner(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n static runTools(client, params, options) {\n const runner = new ChatCompletionStreamingRunner(\n // @ts-expect-error TODO these types are incompatible\n params);\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n}\n//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as MessagesAPI from \"./messages.mjs\";\nimport { Messages } from \"./messages.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nimport { ChatCompletionRunner } from \"../../../lib/ChatCompletionRunner.mjs\";\nimport { ChatCompletionStreamingRunner } from \"../../../lib/ChatCompletionStreamingRunner.mjs\";\nimport { ChatCompletionStream } from \"../../../lib/ChatCompletionStream.mjs\";\nimport { parseChatCompletion, validateInputTools } from \"../../../lib/parser.mjs\";\nexport class Completions extends APIResource {\n constructor() {\n super(...arguments);\n this.messages = new MessagesAPI.Messages(this._client);\n }\n create(body, options) {\n return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false });\n }\n /**\n * Get a stored chat completion. Only Chat Completions that have been created with\n * the `store` parameter set to `true` will be returned.\n *\n * @example\n * ```ts\n * const chatCompletion =\n * await client.chat.completions.retrieve('completion_id');\n * ```\n */\n retrieve(completionID, options) {\n return this._client.get(path `/chat/completions/${completionID}`, options);\n }\n /**\n * Modify a stored chat completion. Only Chat Completions that have been created\n * with the `store` parameter set to `true` can be modified. Currently, the only\n * supported modification is to update the `metadata` field.\n *\n * @example\n * ```ts\n * const chatCompletion = await client.chat.completions.update(\n * 'completion_id',\n * { metadata: { foo: 'string' } },\n * );\n * ```\n */\n update(completionID, body, options) {\n return this._client.post(path `/chat/completions/${completionID}`, { body, ...options });\n }\n /**\n * List stored Chat Completions. Only Chat Completions that have been stored with\n * the `store` parameter set to `true` will be returned.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const chatCompletion of client.chat.completions.list()) {\n * // ...\n * }\n * ```\n */\n list(query = {}, options) {\n return this._client.getAPIList('/chat/completions', (CursorPage), { query, ...options });\n }\n /**\n * Delete a stored chat completion. Only Chat Completions that have been created\n * with the `store` parameter set to `true` can be deleted.\n *\n * @example\n * ```ts\n * const chatCompletionDeleted =\n * await client.chat.completions.delete('completion_id');\n * ```\n */\n delete(completionID, options) {\n return this._client.delete(path `/chat/completions/${completionID}`, options);\n }\n parse(body, options) {\n validateInputTools(body.tools);\n return this._client.chat.completions\n .create(body, {\n ...options,\n headers: {\n ...options?.headers,\n 'X-Stainless-Helper-Method': 'chat.completions.parse',\n },\n })\n ._thenUnwrap((completion) => parseChatCompletion(completion, body));\n }\n runTools(body, options) {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runTools(this._client, body, options);\n }\n return ChatCompletionRunner.runTools(this._client, body, options);\n }\n /**\n * Creates a chat completion stream\n */\n stream(body, options) {\n return ChatCompletionStream.createChatCompletion(this._client, body, options);\n }\n}\nexport { ChatCompletionStreamingRunner } from \"../../../lib/ChatCompletionStreamingRunner.mjs\";\nexport { ParsingToolFunction, } from \"../../../lib/RunnableFunction.mjs\";\nexport { ChatCompletionStream } from \"../../../lib/ChatCompletionStream.mjs\";\nexport { ChatCompletionRunner } from \"../../../lib/ChatCompletionRunner.mjs\";\nCompletions.Messages = Messages;\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as CompletionsAPI from \"./completions/completions.mjs\";\nimport { Completions, } from \"./completions/completions.mjs\";\nexport class Chat extends APIResource {\n constructor() {\n super(...arguments);\n this.completions = new CompletionsAPI.Completions(this._client);\n }\n}\nChat.Completions = Completions;\n//# sourceMappingURL=chat.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport { Completions, } from \"./completions.mjs\";\nexport * from \"./completions.mjs\";\nexport { Messages } from \"./messages.mjs\";\n//# sourceMappingURL=index.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport { Chat } from \"./chat.mjs\";\nexport { Completions, } from \"./completions/index.mjs\";\n//# sourceMappingURL=index.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { isReadonlyArray } from \"./utils/values.mjs\";\nconst brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');\nfunction* iterateHeaders(headers) {\n if (!headers)\n return;\n if (brand_privateNullableHeaders in headers) {\n const { values, nulls } = headers;\n yield* values.entries();\n for (const name of nulls) {\n yield [name, null];\n }\n return;\n }\n let shouldClear = false;\n let iter;\n if (headers instanceof Headers) {\n iter = headers.entries();\n }\n else if (isReadonlyArray(headers)) {\n iter = headers;\n }\n else {\n shouldClear = true;\n iter = Object.entries(headers ?? {});\n }\n for (let row of iter) {\n const name = row[0];\n if (typeof name !== 'string')\n throw new TypeError('expected header name to be a string');\n const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];\n let didClear = false;\n for (const value of values) {\n if (value === undefined)\n continue;\n // Objects keys always overwrite older headers, they never append.\n // Yield a null to clear the header before adding the new values.\n if (shouldClear && !didClear) {\n didClear = true;\n yield [name, null];\n }\n yield [name, value];\n }\n }\n}\nexport const buildHeaders = (newHeaders) => {\n const targetHeaders = new Headers();\n const nullHeaders = new Set();\n for (const headers of newHeaders) {\n const seenHeaders = new Set();\n for (const [name, value] of iterateHeaders(headers)) {\n const lowerName = name.toLowerCase();\n if (!seenHeaders.has(lowerName)) {\n targetHeaders.delete(name);\n seenHeaders.add(lowerName);\n }\n if (value === null) {\n targetHeaders.delete(name);\n nullHeaders.add(lowerName);\n }\n else {\n targetHeaders.append(name, value);\n nullHeaders.delete(lowerName);\n }\n }\n }\n return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };\n};\nexport const isEmptyHeaders = (headers) => {\n for (const _ of iterateHeaders(headers))\n return false;\n return true;\n};\n//# sourceMappingURL=headers.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nexport class Speech extends APIResource {\n /**\n * Generates audio from the input text.\n *\n * @example\n * ```ts\n * const speech = await client.audio.speech.create({\n * input: 'input',\n * model: 'string',\n * voice: 'ash',\n * });\n *\n * const content = await speech.blob();\n * console.log(content);\n * ```\n */\n create(body, options) {\n return this._client.post('/audio/speech', {\n body,\n ...options,\n headers: buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]),\n __binaryResponse: true,\n });\n }\n}\n//# sourceMappingURL=speech.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { multipartFormRequestOptions } from \"../../internal/uploads.mjs\";\nexport class Transcriptions extends APIResource {\n create(body, options) {\n return this._client.post('/audio/transcriptions', multipartFormRequestOptions({\n body,\n ...options,\n stream: body.stream ?? false,\n __metadata: { model: body.model },\n }, this._client));\n }\n}\n//# sourceMappingURL=transcriptions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { multipartFormRequestOptions } from \"../../internal/uploads.mjs\";\nexport class Translations extends APIResource {\n create(body, options) {\n return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client));\n }\n}\n//# sourceMappingURL=translations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as SpeechAPI from \"./speech.mjs\";\nimport { Speech } from \"./speech.mjs\";\nimport * as TranscriptionsAPI from \"./transcriptions.mjs\";\nimport { Transcriptions, } from \"./transcriptions.mjs\";\nimport * as TranslationsAPI from \"./translations.mjs\";\nimport { Translations, } from \"./translations.mjs\";\nexport class Audio extends APIResource {\n constructor() {\n super(...arguments);\n this.transcriptions = new TranscriptionsAPI.Transcriptions(this._client);\n this.translations = new TranslationsAPI.Translations(this._client);\n this.speech = new SpeechAPI.Speech(this._client);\n }\n}\nAudio.Transcriptions = Transcriptions;\nAudio.Translations = Translations;\nAudio.Speech = Speech;\n//# sourceMappingURL=audio.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { CursorPage } from \"../core/pagination.mjs\";\nimport { path } from \"../internal/utils/path.mjs\";\nexport class Batches extends APIResource {\n /**\n * Creates and executes a batch from an uploaded file of requests\n */\n create(body, options) {\n return this._client.post('/batches', { body, ...options });\n }\n /**\n * Retrieves a batch.\n */\n retrieve(batchID, options) {\n return this._client.get(path `/batches/${batchID}`, options);\n }\n /**\n * List your organization's batches.\n */\n list(query = {}, options) {\n return this._client.getAPIList('/batches', (CursorPage), { query, ...options });\n }\n /**\n * Cancels an in-progress batch. The batch will be in status `cancelling` for up to\n * 10 minutes, before changing to `cancelled`, where it will have partial results\n * (if any) available in the output file.\n */\n cancel(batchID, options) {\n return this._client.post(path `/batches/${batchID}/cancel`, options);\n }\n}\n//# sourceMappingURL=batches.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { CursorPage } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Assistants extends APIResource {\n /**\n * Create an assistant with a model and instructions.\n *\n * @example\n * ```ts\n * const assistant = await client.beta.assistants.create({\n * model: 'gpt-4o',\n * });\n * ```\n */\n create(body, options) {\n return this._client.post('/assistants', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Retrieves an assistant.\n *\n * @example\n * ```ts\n * const assistant = await client.beta.assistants.retrieve(\n * 'assistant_id',\n * );\n * ```\n */\n retrieve(assistantID, options) {\n return this._client.get(path `/assistants/${assistantID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Modifies an assistant.\n *\n * @example\n * ```ts\n * const assistant = await client.beta.assistants.update(\n * 'assistant_id',\n * );\n * ```\n */\n update(assistantID, body, options) {\n return this._client.post(path `/assistants/${assistantID}`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Returns a list of assistants.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const assistant of client.beta.assistants.list()) {\n * // ...\n * }\n * ```\n */\n list(query = {}, options) {\n return this._client.getAPIList('/assistants', (CursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Delete an assistant.\n *\n * @example\n * ```ts\n * const assistantDeleted =\n * await client.beta.assistants.delete('assistant_id');\n * ```\n */\n delete(assistantID, options) {\n return this._client.delete(path `/assistants/${assistantID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=assistants.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nexport class Sessions extends APIResource {\n /**\n * Create an ephemeral API token for use in client-side applications with the\n * Realtime API. Can be configured with the same session parameters as the\n * `session.update` client event.\n *\n * It responds with a session object, plus a `client_secret` key which contains a\n * usable ephemeral API token that can be used to authenticate browser clients for\n * the Realtime API.\n *\n * @example\n * ```ts\n * const session =\n * await client.beta.realtime.sessions.create();\n * ```\n */\n create(body, options) {\n return this._client.post('/realtime/sessions', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=sessions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nexport class TranscriptionSessions extends APIResource {\n /**\n * Create an ephemeral API token for use in client-side applications with the\n * Realtime API specifically for realtime transcriptions. Can be configured with\n * the same session parameters as the `transcription_session.update` client event.\n *\n * It responds with a session object, plus a `client_secret` key which contains a\n * usable ephemeral API token that can be used to authenticate browser clients for\n * the Realtime API.\n *\n * @example\n * ```ts\n * const transcriptionSession =\n * await client.beta.realtime.transcriptionSessions.create();\n * ```\n */\n create(body, options) {\n return this._client.post('/realtime/transcription_sessions', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=transcription-sessions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as SessionsAPI from \"./sessions.mjs\";\nimport { Sessions, } from \"./sessions.mjs\";\nimport * as TranscriptionSessionsAPI from \"./transcription-sessions.mjs\";\nimport { TranscriptionSessions, } from \"./transcription-sessions.mjs\";\n/**\n * @deprecated Realtime has now launched and is generally available. The old beta API is now deprecated.\n */\nexport class Realtime extends APIResource {\n constructor() {\n super(...arguments);\n this.sessions = new SessionsAPI.Sessions(this._client);\n this.transcriptionSessions = new TranscriptionSessionsAPI.TranscriptionSessions(this._client);\n }\n}\nRealtime.Sessions = Sessions;\nRealtime.TranscriptionSessions = TranscriptionSessions;\n//# sourceMappingURL=realtime.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Sessions extends APIResource {\n /**\n * Create a ChatKit session\n *\n * @example\n * ```ts\n * const chatSession =\n * await client.beta.chatkit.sessions.create({\n * user: 'x',\n * workflow: { id: 'id' },\n * });\n * ```\n */\n create(body, options) {\n return this._client.post('/chatkit/sessions', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]),\n });\n }\n /**\n * Cancel a ChatKit session\n *\n * @example\n * ```ts\n * const chatSession =\n * await client.beta.chatkit.sessions.cancel('cksess_123');\n * ```\n */\n cancel(sessionID, options) {\n return this._client.post(path `/chatkit/sessions/${sessionID}/cancel`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=sessions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { ConversationCursorPage, } from \"../../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Threads extends APIResource {\n /**\n * Retrieve a ChatKit thread\n *\n * @example\n * ```ts\n * const chatkitThread =\n * await client.beta.chatkit.threads.retrieve('cthr_123');\n * ```\n */\n retrieve(threadID, options) {\n return this._client.get(path `/chatkit/threads/${threadID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]),\n });\n }\n /**\n * List ChatKit threads\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const chatkitThread of client.beta.chatkit.threads.list()) {\n * // ...\n * }\n * ```\n */\n list(query = {}, options) {\n return this._client.getAPIList('/chatkit/threads', (ConversationCursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]),\n });\n }\n /**\n * Delete a ChatKit thread\n *\n * @example\n * ```ts\n * const thread = await client.beta.chatkit.threads.delete(\n * 'cthr_123',\n * );\n * ```\n */\n delete(threadID, options) {\n return this._client.delete(path `/chatkit/threads/${threadID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]),\n });\n }\n /**\n * List ChatKit thread items\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const thread of client.beta.chatkit.threads.listItems(\n * 'cthr_123',\n * )) {\n * // ...\n * }\n * ```\n */\n listItems(threadID, query = {}, options) {\n return this._client.getAPIList(path `/chatkit/threads/${threadID}/items`, (ConversationCursorPage), { query, ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]) });\n }\n}\n//# sourceMappingURL=threads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as SessionsAPI from \"./sessions.mjs\";\nimport { Sessions } from \"./sessions.mjs\";\nimport * as ThreadsAPI from \"./threads.mjs\";\nimport { Threads, } from \"./threads.mjs\";\nexport class ChatKit extends APIResource {\n constructor() {\n super(...arguments);\n this.sessions = new SessionsAPI.Sessions(this._client);\n this.threads = new ThreadsAPI.Threads(this._client);\n }\n}\nChatKit.Sessions = Sessions;\nChatKit.Threads = Threads;\n//# sourceMappingURL=chatkit.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Messages extends APIResource {\n /**\n * Create a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n create(threadID, body, options) {\n return this._client.post(path `/threads/${threadID}/messages`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Retrieve a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(messageID, params, options) {\n const { thread_id } = params;\n return this._client.get(path `/threads/${thread_id}/messages/${messageID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Modifies a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n update(messageID, params, options) {\n const { thread_id, ...body } = params;\n return this._client.post(path `/threads/${thread_id}/messages/${messageID}`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Returns a list of messages for a given thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n list(threadID, query = {}, options) {\n return this._client.getAPIList(path `/threads/${threadID}/messages`, (CursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Deletes a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n delete(messageID, params, options) {\n const { thread_id } = params;\n return this._client.delete(path `/threads/${thread_id}/messages/${messageID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=messages.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../../core/resource.mjs\";\nimport { CursorPage } from \"../../../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../../../internal/headers.mjs\";\nimport { path } from \"../../../../internal/utils/path.mjs\";\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Steps extends APIResource {\n /**\n * Retrieves a run step.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(stepID, params, options) {\n const { thread_id, run_id, ...query } = params;\n return this._client.get(path `/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Returns a list of run steps belonging to a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n list(runID, params, options) {\n const { thread_id, ...query } = params;\n return this._client.getAPIList(path `/threads/${thread_id}/runs/${runID}/steps`, (CursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=steps.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { OpenAIError } from \"../../core/error.mjs\";\nimport { encodeUTF8 } from \"./bytes.mjs\";\nexport const toBase64 = (data) => {\n if (!data)\n return '';\n if (typeof globalThis.Buffer !== 'undefined') {\n return globalThis.Buffer.from(data).toString('base64');\n }\n if (typeof data === 'string') {\n data = encodeUTF8(data);\n }\n if (typeof btoa !== 'undefined') {\n return btoa(String.fromCharCode.apply(null, data));\n }\n throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined');\n};\nexport const fromBase64 = (str) => {\n if (typeof globalThis.Buffer !== 'undefined') {\n const buf = globalThis.Buffer.from(str, 'base64');\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n if (typeof atob !== 'undefined') {\n const bstr = atob(str);\n const buf = new Uint8Array(bstr.length);\n for (let i = 0; i < bstr.length; i++) {\n buf[i] = bstr.charCodeAt(i);\n }\n return buf;\n }\n throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined');\n};\n/**\n * Converts a Base64 encoded string to a Float32Array.\n * @param base64Str - The Base64 encoded string.\n * @returns An Array of numbers interpreted as Float32 values.\n */\nexport const toFloat32Array = (base64Str) => {\n if (typeof Buffer !== 'undefined') {\n // for Node.js environment\n const buf = Buffer.from(base64Str, 'base64');\n return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));\n }\n else {\n // for legacy web platform APIs\n const binaryStr = atob(base64Str);\n const len = binaryStr.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryStr.charCodeAt(i);\n }\n return Array.from(new Float32Array(bytes.buffer));\n }\n};\n//# sourceMappingURL=base64.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env) => {\n if (typeof globalThis.process !== 'undefined') {\n return globalThis.process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof globalThis.Deno !== 'undefined') {\n return globalThis.Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\n//# sourceMappingURL=env.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport * from \"./utils/values.mjs\";\nexport * from \"./utils/base64.mjs\";\nexport * from \"./utils/env.mjs\";\nexport * from \"./utils/log.mjs\";\nexport * from \"./utils/uuid.mjs\";\nexport * from \"./utils/sleep.mjs\";\n//# sourceMappingURL=utils.mjs.map","var _AssistantStream_instances, _a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../internal/tslib.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { APIUserAbortError, OpenAIError } from \"../error.mjs\";\nimport { EventStream } from \"./EventStream.mjs\";\nimport { isObj } from \"../internal/utils.mjs\";\nexport class AssistantStream extends EventStream {\n constructor() {\n super(...arguments);\n _AssistantStream_instances.add(this);\n //Track all events in a single list for reference\n _AssistantStream_events.set(this, []);\n //Used to accumulate deltas\n //We are accumulating many types so the value here is not strict\n _AssistantStream_runStepSnapshots.set(this, {});\n _AssistantStream_messageSnapshots.set(this, {});\n _AssistantStream_messageSnapshot.set(this, void 0);\n _AssistantStream_finalRun.set(this, void 0);\n _AssistantStream_currentContentIndex.set(this, void 0);\n _AssistantStream_currentContent.set(this, void 0);\n _AssistantStream_currentToolCallIndex.set(this, void 0);\n _AssistantStream_currentToolCall.set(this, void 0);\n //For current snapshot methods\n _AssistantStream_currentEvent.set(this, void 0);\n _AssistantStream_currentRunSnapshot.set(this, void 0);\n _AssistantStream_currentRunStepSnapshot.set(this, void 0);\n }\n [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n //Catch all for passing along all events\n this.on('event', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n }\n else {\n pushQueue.push(event);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n static fromReadableStream(stream) {\n const runner = new _a();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this._connected();\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n static createToolAssistantStream(runId, runs, params, options) {\n const runner = new _a();\n runner._run(() => runner._runToolAssistantStream(runId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n async _createToolAssistantStream(run, runId, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await run.submitToolOutputs(runId, body, {\n ...options,\n signal: this.controller.signal,\n });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n static createThreadAssistantStream(params, thread, options) {\n const runner = new _a();\n runner._run(() => runner._threadAssistantStream(params, thread, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n static createAssistantStream(threadId, runs, params, options) {\n const runner = new _a();\n runner._run(() => runner._runAssistantStream(threadId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n currentEvent() {\n return __classPrivateFieldGet(this, _AssistantStream_currentEvent, \"f\");\n }\n currentRun() {\n return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, \"f\");\n }\n currentMessageSnapshot() {\n return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\");\n }\n currentRunStepSnapshot() {\n return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, \"f\");\n }\n async finalRunSteps() {\n await this.done();\n return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\"));\n }\n async finalMessages() {\n await this.done();\n return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, \"f\"));\n }\n async finalRun() {\n await this.done();\n if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\"))\n throw Error('Final run was not received.');\n return __classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\");\n }\n async _createThreadAssistantStream(thread, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n async _createAssistantStream(run, threadId, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n static accumulateDelta(acc, delta) {\n for (const [key, deltaValue] of Object.entries(delta)) {\n if (!acc.hasOwnProperty(key)) {\n acc[key] = deltaValue;\n continue;\n }\n let accValue = acc[key];\n if (accValue === null || accValue === undefined) {\n acc[key] = deltaValue;\n continue;\n }\n // We don't accumulate these special properties\n if (key === 'index' || key === 'type') {\n acc[key] = deltaValue;\n continue;\n }\n // Type-specific accumulation logic\n if (typeof accValue === 'string' && typeof deltaValue === 'string') {\n accValue += deltaValue;\n }\n else if (typeof accValue === 'number' && typeof deltaValue === 'number') {\n accValue += deltaValue;\n }\n else if (isObj(accValue) && isObj(deltaValue)) {\n accValue = this.accumulateDelta(accValue, deltaValue);\n }\n else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {\n if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) {\n accValue.push(...deltaValue); // Use spread syntax for efficient addition\n continue;\n }\n for (const deltaEntry of deltaValue) {\n if (!isObj(deltaEntry)) {\n throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);\n }\n const index = deltaEntry['index'];\n if (index == null) {\n console.error(deltaEntry);\n throw new Error('Expected array delta entry to have an `index` property');\n }\n if (typeof index !== 'number') {\n throw new Error(`Expected array delta entry \\`index\\` property to be a number but got ${index}`);\n }\n const accEntry = accValue[index];\n if (accEntry == null) {\n accValue.push(deltaEntry);\n }\n else {\n accValue[index] = this.accumulateDelta(accEntry, deltaEntry);\n }\n }\n continue;\n }\n else {\n throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);\n }\n acc[key] = accValue;\n }\n return acc;\n }\n _addRun(run) {\n return run;\n }\n async _threadAssistantStream(params, thread, options) {\n return await this._createThreadAssistantStream(thread, params, options);\n }\n async _runAssistantStream(threadId, runs, params, options) {\n return await this._createAssistantStream(runs, threadId, params, options);\n }\n async _runToolAssistantStream(runId, runs, params, options) {\n return await this._createToolAssistantStream(runs, runId, params, options);\n }\n}\n_a = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, \"f\");\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleEvent).call(this, event);\n switch (event.event) {\n case 'thread.created':\n //No action on this event.\n break;\n case 'thread.run.created':\n case 'thread.run.queued':\n case 'thread.run.in_progress':\n case 'thread.run.requires_action':\n case 'thread.run.completed':\n case 'thread.run.incomplete':\n case 'thread.run.failed':\n case 'thread.run.cancelling':\n case 'thread.run.cancelled':\n case 'thread.run.expired':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleRun).call(this, event);\n break;\n case 'thread.run.step.created':\n case 'thread.run.step.in_progress':\n case 'thread.run.step.delta':\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleRunStep).call(this, event);\n break;\n case 'thread.message.created':\n case 'thread.message.in_progress':\n case 'thread.message.delta':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleMessage).call(this, event);\n break;\n case 'error':\n //This is included for completeness, but errors are processed in the SSE event processing so this should not occur\n throw new Error('Encountered an error event in event processing - errors should be processed earlier');\n default:\n assertNever(event);\n }\n}, _AssistantStream_endRequest = function _AssistantStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\"))\n throw Error('Final run has not been received');\n return __classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\");\n}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) {\n const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, \"f\");\n __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, \"f\")[accumulatedMessage.id] = accumulatedMessage;\n for (const content of newContent) {\n const snapshotContent = accumulatedMessage.content[content.index];\n if (snapshotContent?.type == 'text') {\n this._emit('textCreated', snapshotContent.text);\n }\n }\n switch (event.event) {\n case 'thread.message.created':\n this._emit('messageCreated', event.data);\n break;\n case 'thread.message.in_progress':\n break;\n case 'thread.message.delta':\n this._emit('messageDelta', event.data.delta, accumulatedMessage);\n if (event.data.delta.content) {\n for (const content of event.data.delta.content) {\n //If it is text delta, emit a text delta event\n if (content.type == 'text' && content.text) {\n let textDelta = content.text;\n let snapshot = accumulatedMessage.content[content.index];\n if (snapshot && snapshot.type == 'text') {\n this._emit('textDelta', textDelta, snapshot.text);\n }\n else {\n throw Error('The snapshot associated with this text delta is not text or missing');\n }\n }\n if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\")) {\n //See if we have in progress content\n if (__classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\")) {\n switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").type) {\n case 'text':\n this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n case 'image_file':\n this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n }\n }\n __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, \"f\");\n }\n __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], \"f\");\n }\n }\n break;\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //We emit the latest content we were working on on completion (including incomplete)\n if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\") !== undefined) {\n const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\")];\n if (currentContent) {\n switch (currentContent.type) {\n case 'image_file':\n this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n case 'text':\n this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n }\n }\n }\n if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\")) {\n this._emit('messageDone', event.data);\n }\n __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, \"f\");\n }\n}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) {\n const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateRunStep).call(this, event);\n __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, \"f\");\n switch (event.event) {\n case 'thread.run.step.created':\n this._emit('runStepCreated', event.data);\n break;\n case 'thread.run.step.delta':\n const delta = event.data.delta;\n if (delta.step_details &&\n delta.step_details.type == 'tool_calls' &&\n delta.step_details.tool_calls &&\n accumulatedRunStep.step_details.type == 'tool_calls') {\n for (const toolCall of delta.step_details.tool_calls) {\n if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, \"f\")) {\n this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);\n }\n else {\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n }\n __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, \"f\");\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], \"f\");\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"))\n this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n }\n }\n }\n this._emit('runStepDelta', event.data.delta, accumulatedRunStep);\n break;\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, \"f\");\n const details = event.data.step_details;\n if (details.type == 'tool_calls') {\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, \"f\");\n }\n }\n this._emit('runStepDone', event.data, accumulatedRunStep);\n break;\n case 'thread.run.step.in_progress':\n break;\n }\n}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) {\n __classPrivateFieldGet(this, _AssistantStream_events, \"f\").push(event);\n this._emit('event', event);\n}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) {\n switch (event.event) {\n case 'thread.run.step.created':\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = event.data;\n return event.data;\n case 'thread.run.step.delta':\n let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n if (!snapshot) {\n throw Error('Received a RunStepDelta before creation of a snapshot');\n }\n let data = event.data;\n if (data.delta) {\n const accumulated = _a.accumulateDelta(snapshot, data.delta);\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = accumulated;\n }\n return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n case 'thread.run.step.in_progress':\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = event.data;\n break;\n }\n if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id])\n return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n throw new Error('No snapshot available');\n}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) {\n let newContent = [];\n switch (event.event) {\n case 'thread.message.created':\n //On creation the snapshot is just the initial message\n return [event.data, newContent];\n case 'thread.message.delta':\n if (!snapshot) {\n throw Error('Received a delta with no existing snapshot (there should be one from message creation)');\n }\n let data = event.data;\n //If this delta does not have content, nothing to process\n if (data.delta.content) {\n for (const contentElement of data.delta.content) {\n if (contentElement.index in snapshot.content) {\n let currentContent = snapshot.content[contentElement.index];\n snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);\n }\n else {\n snapshot.content[contentElement.index] = contentElement;\n // This is a new element\n newContent.push(contentElement);\n }\n }\n }\n return [snapshot, newContent];\n case 'thread.message.in_progress':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //No changes on other thread events\n if (snapshot) {\n return [snapshot, newContent];\n }\n else {\n throw Error('Received thread message event with no existing snapshot');\n }\n }\n throw Error('Tried to accumulate a non-message event');\n}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {\n return _a.accumulateDelta(currentContent, contentElement);\n}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {\n __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, \"f\");\n switch (event.event) {\n case 'thread.run.created':\n break;\n case 'thread.run.queued':\n break;\n case 'thread.run.in_progress':\n break;\n case 'thread.run.requires_action':\n case 'thread.run.cancelled':\n case 'thread.run.failed':\n case 'thread.run.completed':\n case 'thread.run.expired':\n case 'thread.run.incomplete':\n __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, \"f\");\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, \"f\");\n }\n break;\n case 'thread.run.cancelling':\n break;\n }\n};\nfunction assertNever(_x) { }\n//# sourceMappingURL=AssistantStream.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../../core/resource.mjs\";\nimport * as StepsAPI from \"./steps.mjs\";\nimport { Steps, } from \"./steps.mjs\";\nimport { CursorPage } from \"../../../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../../../internal/headers.mjs\";\nimport { AssistantStream } from \"../../../../lib/AssistantStream.mjs\";\nimport { sleep } from \"../../../../internal/utils/sleep.mjs\";\nimport { path } from \"../../../../internal/utils/path.mjs\";\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Runs extends APIResource {\n constructor() {\n super(...arguments);\n this.steps = new StepsAPI.Steps(this._client);\n }\n create(threadID, params, options) {\n const { include, ...body } = params;\n return this._client.post(path `/threads/${threadID}/runs`, {\n query: { include },\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n stream: params.stream ?? false,\n });\n }\n /**\n * Retrieves a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(runID, params, options) {\n const { thread_id } = params;\n return this._client.get(path `/threads/${thread_id}/runs/${runID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Modifies a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n update(runID, params, options) {\n const { thread_id, ...body } = params;\n return this._client.post(path `/threads/${thread_id}/runs/${runID}`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Returns a list of runs belonging to a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n list(threadID, query = {}, options) {\n return this._client.getAPIList(path `/threads/${threadID}/runs`, (CursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Cancels a run that is `in_progress`.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n cancel(runID, params, options) {\n const { thread_id } = params;\n return this._client.post(path `/threads/${thread_id}/runs/${runID}/cancel`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * A helper to create a run an poll for a terminal state. More information on Run\n * lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndPoll(threadId, body, options) {\n const run = await this.create(threadId, body, options);\n return await this.poll(run.id, { thread_id: threadId }, options);\n }\n /**\n * Create a Run stream\n *\n * @deprecated use `stream` instead\n */\n createAndStream(threadId, body, options) {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n /**\n * A helper to poll a run status until it reaches a terminal state. More\n * information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async poll(runId, params, options) {\n const headers = buildHeaders([\n options?.headers,\n {\n 'X-Stainless-Poll-Helper': 'true',\n 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined,\n },\n ]);\n while (true) {\n const { data: run, response } = await this.retrieve(runId, params, {\n ...options,\n headers: { ...options?.headers, ...headers },\n }).withResponse();\n switch (run.status) {\n //If we are in any sort of intermediate state we poll\n case 'queued':\n case 'in_progress':\n case 'cancelling':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n //We return the run in any terminal state.\n case 'requires_action':\n case 'incomplete':\n case 'cancelled':\n case 'completed':\n case 'failed':\n case 'expired':\n return run;\n }\n }\n }\n /**\n * Create a Run stream\n */\n stream(threadId, body, options) {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n submitToolOutputs(runID, params, options) {\n const { thread_id, ...body } = params;\n return this._client.post(path `/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n stream: params.stream ?? false,\n });\n }\n /**\n * A helper to submit a tool output to a run and poll for a terminal run state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async submitToolOutputsAndPoll(runId, params, options) {\n const run = await this.submitToolOutputs(runId, params, options);\n return await this.poll(run.id, params, options);\n }\n /**\n * Submit the tool outputs from a previous run and stream the run to a terminal\n * state. More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n submitToolOutputsStream(runId, params, options) {\n return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options);\n }\n}\nRuns.Steps = Steps;\n//# sourceMappingURL=runs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as MessagesAPI from \"./messages.mjs\";\nimport { Messages, } from \"./messages.mjs\";\nimport * as RunsAPI from \"./runs/runs.mjs\";\nimport { Runs, } from \"./runs/runs.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { AssistantStream } from \"../../../lib/AssistantStream.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Threads extends APIResource {\n constructor() {\n super(...arguments);\n this.runs = new RunsAPI.Runs(this._client);\n this.messages = new MessagesAPI.Messages(this._client);\n }\n /**\n * Create a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n create(body = {}, options) {\n return this._client.post('/threads', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Retrieves a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(threadID, options) {\n return this._client.get(path `/threads/${threadID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Modifies a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n update(threadID, body, options) {\n return this._client.post(path `/threads/${threadID}`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Delete a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n delete(threadID, options) {\n return this._client.delete(path `/threads/${threadID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n createAndRun(body, options) {\n return this._client.post('/threads/runs', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n stream: body.stream ?? false,\n });\n }\n /**\n * A helper to create a thread, start a run and then poll for a terminal state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndRunPoll(body, options) {\n const run = await this.createAndRun(body, options);\n return await this.runs.poll(run.id, { thread_id: run.thread_id }, options);\n }\n /**\n * Create a thread and stream the run back\n */\n createAndRunStream(body, options) {\n return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);\n }\n}\nThreads.Runs = Runs;\nThreads.Messages = Messages;\n//# sourceMappingURL=threads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as AssistantsAPI from \"./assistants.mjs\";\nimport { Assistants, } from \"./assistants.mjs\";\nimport * as RealtimeAPI from \"./realtime/realtime.mjs\";\nimport { Realtime, } from \"./realtime/realtime.mjs\";\nimport * as ChatKitAPI from \"./chatkit/chatkit.mjs\";\nimport { ChatKit } from \"./chatkit/chatkit.mjs\";\nimport * as ThreadsAPI from \"./threads/threads.mjs\";\nimport { Threads, } from \"./threads/threads.mjs\";\nexport class Beta extends APIResource {\n constructor() {\n super(...arguments);\n this.realtime = new RealtimeAPI.Realtime(this._client);\n this.chatkit = new ChatKitAPI.ChatKit(this._client);\n this.assistants = new AssistantsAPI.Assistants(this._client);\n this.threads = new ThreadsAPI.Threads(this._client);\n }\n}\nBeta.Realtime = Realtime;\nBeta.ChatKit = ChatKit;\nBeta.Assistants = Assistants;\nBeta.Threads = Threads;\n//# sourceMappingURL=beta.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nexport class Completions extends APIResource {\n create(body, options) {\n return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });\n }\n}\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Content extends APIResource {\n /**\n * Retrieve Container File Content\n */\n retrieve(fileID, params, options) {\n const { container_id } = params;\n return this._client.get(path `/containers/${container_id}/files/${fileID}/content`, {\n ...options,\n headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]),\n __binaryResponse: true,\n });\n }\n}\n//# sourceMappingURL=content.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as ContentAPI from \"./content.mjs\";\nimport { Content } from \"./content.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../../internal/headers.mjs\";\nimport { multipartFormRequestOptions } from \"../../../internal/uploads.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Files extends APIResource {\n constructor() {\n super(...arguments);\n this.content = new ContentAPI.Content(this._client);\n }\n /**\n * Create a Container File\n *\n * You can send either a multipart/form-data request with the raw file content, or\n * a JSON request with a file ID.\n */\n create(containerID, body, options) {\n return this._client.post(path `/containers/${containerID}/files`, multipartFormRequestOptions({ body, ...options }, this._client));\n }\n /**\n * Retrieve Container File\n */\n retrieve(fileID, params, options) {\n const { container_id } = params;\n return this._client.get(path `/containers/${container_id}/files/${fileID}`, options);\n }\n /**\n * List Container files\n */\n list(containerID, query = {}, options) {\n return this._client.getAPIList(path `/containers/${containerID}/files`, (CursorPage), {\n query,\n ...options,\n });\n }\n /**\n * Delete Container File\n */\n delete(fileID, params, options) {\n const { container_id } = params;\n return this._client.delete(path `/containers/${container_id}/files/${fileID}`, {\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n}\nFiles.Content = Content;\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as FilesAPI from \"./files/files.mjs\";\nimport { Files, } from \"./files/files.mjs\";\nimport { CursorPage } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Containers extends APIResource {\n constructor() {\n super(...arguments);\n this.files = new FilesAPI.Files(this._client);\n }\n /**\n * Create Container\n */\n create(body, options) {\n return this._client.post('/containers', { body, ...options });\n }\n /**\n * Retrieve Container\n */\n retrieve(containerID, options) {\n return this._client.get(path `/containers/${containerID}`, options);\n }\n /**\n * List Containers\n */\n list(query = {}, options) {\n return this._client.getAPIList('/containers', (CursorPage), { query, ...options });\n }\n /**\n * Delete Container\n */\n delete(containerID, options) {\n return this._client.delete(path `/containers/${containerID}`, {\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n}\nContainers.Files = Files;\n//# sourceMappingURL=containers.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { ConversationCursorPage, } from \"../../core/pagination.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Items extends APIResource {\n /**\n * Create items in a conversation with the given ID.\n */\n create(conversationID, params, options) {\n const { include, ...body } = params;\n return this._client.post(path `/conversations/${conversationID}/items`, {\n query: { include },\n body,\n ...options,\n });\n }\n /**\n * Get a single item from a conversation with the given IDs.\n */\n retrieve(itemID, params, options) {\n const { conversation_id, ...query } = params;\n return this._client.get(path `/conversations/${conversation_id}/items/${itemID}`, { query, ...options });\n }\n /**\n * List all items for a conversation with the given ID.\n */\n list(conversationID, query = {}, options) {\n return this._client.getAPIList(path `/conversations/${conversationID}/items`, (ConversationCursorPage), { query, ...options });\n }\n /**\n * Delete an item from a conversation with the given IDs.\n */\n delete(itemID, params, options) {\n const { conversation_id } = params;\n return this._client.delete(path `/conversations/${conversation_id}/items/${itemID}`, options);\n }\n}\n//# sourceMappingURL=items.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as ItemsAPI from \"./items.mjs\";\nimport { Items, } from \"./items.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Conversations extends APIResource {\n constructor() {\n super(...arguments);\n this.items = new ItemsAPI.Items(this._client);\n }\n /**\n * Create a conversation.\n */\n create(body = {}, options) {\n return this._client.post('/conversations', { body, ...options });\n }\n /**\n * Get a conversation\n */\n retrieve(conversationID, options) {\n return this._client.get(path `/conversations/${conversationID}`, options);\n }\n /**\n * Update a conversation\n */\n update(conversationID, body, options) {\n return this._client.post(path `/conversations/${conversationID}`, { body, ...options });\n }\n /**\n * Delete a conversation. Items in the conversation will not be deleted.\n */\n delete(conversationID, options) {\n return this._client.delete(path `/conversations/${conversationID}`, options);\n }\n}\nConversations.Items = Items;\n//# sourceMappingURL=conversations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { loggerFor, toFloat32Array } from \"../internal/utils.mjs\";\nexport class Embeddings extends APIResource {\n /**\n * Creates an embedding vector representing the input text.\n *\n * @example\n * ```ts\n * const createEmbeddingResponse =\n * await client.embeddings.create({\n * input: 'The quick brown fox jumped over the lazy dog',\n * model: 'text-embedding-3-small',\n * });\n * ```\n */\n create(body, options) {\n const hasUserProvidedEncodingFormat = !!body.encoding_format;\n // No encoding_format specified, defaulting to base64 for performance reasons\n // See https://github.com/openai/openai-node/pull/1312\n let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64';\n if (hasUserProvidedEncodingFormat) {\n loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format);\n }\n const response = this._client.post('/embeddings', {\n body: {\n ...body,\n encoding_format: encoding_format,\n },\n ...options,\n });\n // if the user specified an encoding_format, return the response as-is\n if (hasUserProvidedEncodingFormat) {\n return response;\n }\n // in this stage, we are sure the user did not specify an encoding_format\n // and we defaulted to base64 for performance reasons\n // we are sure then that the response is base64 encoded, let's decode it\n // the returned result will be a float32 array since this is OpenAI API's default encoding\n loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64');\n return response._thenUnwrap((response) => {\n if (response && response.data) {\n response.data.forEach((embeddingBase64Obj) => {\n const embeddingBase64Str = embeddingBase64Obj.embedding;\n embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str);\n });\n }\n return response;\n });\n }\n}\n//# sourceMappingURL=embeddings.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class OutputItems extends APIResource {\n /**\n * Get an evaluation run output item by ID.\n */\n retrieve(outputItemID, params, options) {\n const { eval_id, run_id } = params;\n return this._client.get(path `/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options);\n }\n /**\n * Get a list of output items for an evaluation run.\n */\n list(runID, params, options) {\n const { eval_id, ...query } = params;\n return this._client.getAPIList(path `/evals/${eval_id}/runs/${runID}/output_items`, (CursorPage), { query, ...options });\n }\n}\n//# sourceMappingURL=output-items.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as OutputItemsAPI from \"./output-items.mjs\";\nimport { OutputItems, } from \"./output-items.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Runs extends APIResource {\n constructor() {\n super(...arguments);\n this.outputItems = new OutputItemsAPI.OutputItems(this._client);\n }\n /**\n * Kicks off a new run for a given evaluation, specifying the data source, and what\n * model configuration to use to test. The datasource will be validated against the\n * schema specified in the config of the evaluation.\n */\n create(evalID, body, options) {\n return this._client.post(path `/evals/${evalID}/runs`, { body, ...options });\n }\n /**\n * Get an evaluation run by ID.\n */\n retrieve(runID, params, options) {\n const { eval_id } = params;\n return this._client.get(path `/evals/${eval_id}/runs/${runID}`, options);\n }\n /**\n * Get a list of runs for an evaluation.\n */\n list(evalID, query = {}, options) {\n return this._client.getAPIList(path `/evals/${evalID}/runs`, (CursorPage), {\n query,\n ...options,\n });\n }\n /**\n * Delete an eval run.\n */\n delete(runID, params, options) {\n const { eval_id } = params;\n return this._client.delete(path `/evals/${eval_id}/runs/${runID}`, options);\n }\n /**\n * Cancel an ongoing evaluation run.\n */\n cancel(runID, params, options) {\n const { eval_id } = params;\n return this._client.post(path `/evals/${eval_id}/runs/${runID}`, options);\n }\n}\nRuns.OutputItems = OutputItems;\n//# sourceMappingURL=runs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as RunsAPI from \"./runs/runs.mjs\";\nimport { Runs, } from \"./runs/runs.mjs\";\nimport { CursorPage } from \"../../core/pagination.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Evals extends APIResource {\n constructor() {\n super(...arguments);\n this.runs = new RunsAPI.Runs(this._client);\n }\n /**\n * Create the structure of an evaluation that can be used to test a model's\n * performance. An evaluation is a set of testing criteria and the config for a\n * data source, which dictates the schema of the data used in the evaluation. After\n * creating an evaluation, you can run it on different models and model parameters.\n * We support several types of graders and datasources. For more information, see\n * the [Evals guide](https://platform.openai.com/docs/guides/evals).\n */\n create(body, options) {\n return this._client.post('/evals', { body, ...options });\n }\n /**\n * Get an evaluation by ID.\n */\n retrieve(evalID, options) {\n return this._client.get(path `/evals/${evalID}`, options);\n }\n /**\n * Update certain properties of an evaluation.\n */\n update(evalID, body, options) {\n return this._client.post(path `/evals/${evalID}`, { body, ...options });\n }\n /**\n * List evaluations for a project.\n */\n list(query = {}, options) {\n return this._client.getAPIList('/evals', (CursorPage), { query, ...options });\n }\n /**\n * Delete an evaluation.\n */\n delete(evalID, options) {\n return this._client.delete(path `/evals/${evalID}`, options);\n }\n}\nEvals.Runs = Runs;\n//# sourceMappingURL=evals.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { CursorPage } from \"../core/pagination.mjs\";\nimport { buildHeaders } from \"../internal/headers.mjs\";\nimport { sleep } from \"../internal/utils/sleep.mjs\";\nimport { APIConnectionTimeoutError } from \"../error.mjs\";\nimport { multipartFormRequestOptions } from \"../internal/uploads.mjs\";\nimport { path } from \"../internal/utils/path.mjs\";\nexport class Files extends APIResource {\n /**\n * Upload a file that can be used across various endpoints. Individual files can be\n * up to 512 MB, and the size of all files uploaded by one organization can be up\n * to 1 TB.\n *\n * - The Assistants API supports files up to 2 million tokens and of specific file\n * types. See the\n * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools)\n * for details.\n * - The Fine-tuning API only supports `.jsonl` files. The input also has certain\n * required formats for fine-tuning\n * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input)\n * or\n * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)\n * models.\n * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input\n * also has a specific required\n * [format](https://platform.openai.com/docs/api-reference/batch/request-input).\n *\n * Please [contact us](https://help.openai.com/) if you need to increase these\n * storage limits.\n */\n create(body, options) {\n return this._client.post('/files', multipartFormRequestOptions({ body, ...options }, this._client));\n }\n /**\n * Returns information about a specific file.\n */\n retrieve(fileID, options) {\n return this._client.get(path `/files/${fileID}`, options);\n }\n /**\n * Returns a list of files.\n */\n list(query = {}, options) {\n return this._client.getAPIList('/files', (CursorPage), { query, ...options });\n }\n /**\n * Delete a file and remove it from all vector stores.\n */\n delete(fileID, options) {\n return this._client.delete(path `/files/${fileID}`, options);\n }\n /**\n * Returns the contents of the specified file.\n */\n content(fileID, options) {\n return this._client.get(path `/files/${fileID}/content`, {\n ...options,\n headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]),\n __binaryResponse: true,\n });\n }\n /**\n * Waits for the given file to be processed, default timeout is 30 mins.\n */\n async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {\n const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);\n const start = Date.now();\n let file = await this.retrieve(id);\n while (!file.status || !TERMINAL_STATES.has(file.status)) {\n await sleep(pollInterval);\n file = await this.retrieve(id);\n if (Date.now() - start > maxWait) {\n throw new APIConnectionTimeoutError({\n message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,\n });\n }\n }\n return file;\n }\n}\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nexport class Methods extends APIResource {\n}\n//# sourceMappingURL=methods.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nexport class Graders extends APIResource {\n /**\n * Run a grader.\n *\n * @example\n * ```ts\n * const response = await client.fineTuning.alpha.graders.run({\n * grader: {\n * input: 'input',\n * name: 'name',\n * operation: 'eq',\n * reference: 'reference',\n * type: 'string_check',\n * },\n * model_sample: 'model_sample',\n * });\n * ```\n */\n run(body, options) {\n return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options });\n }\n /**\n * Validate a grader.\n *\n * @example\n * ```ts\n * const response =\n * await client.fineTuning.alpha.graders.validate({\n * grader: {\n * input: 'input',\n * name: 'name',\n * operation: 'eq',\n * reference: 'reference',\n * type: 'string_check',\n * },\n * });\n * ```\n */\n validate(body, options) {\n return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options });\n }\n}\n//# sourceMappingURL=graders.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as GradersAPI from \"./graders.mjs\";\nimport { Graders, } from \"./graders.mjs\";\nexport class Alpha extends APIResource {\n constructor() {\n super(...arguments);\n this.graders = new GradersAPI.Graders(this._client);\n }\n}\nAlpha.Graders = Graders;\n//# sourceMappingURL=alpha.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { Page } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Permissions extends APIResource {\n /**\n * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).\n *\n * This enables organization owners to share fine-tuned models with other projects\n * in their organization.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(\n * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',\n * { project_ids: ['string'] },\n * )) {\n * // ...\n * }\n * ```\n */\n create(fineTunedModelCheckpoint, body, options) {\n return this._client.getAPIList(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (Page), { body, method: 'post', ...options });\n }\n /**\n * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n *\n * Organization owners can use this endpoint to view all permissions for a\n * fine-tuned model checkpoint.\n *\n * @example\n * ```ts\n * const permission =\n * await client.fineTuning.checkpoints.permissions.retrieve(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n retrieve(fineTunedModelCheckpoint, query = {}, options) {\n return this._client.get(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {\n query,\n ...options,\n });\n }\n /**\n * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n *\n * Organization owners can use this endpoint to delete a permission for a\n * fine-tuned model checkpoint.\n *\n * @example\n * ```ts\n * const permission =\n * await client.fineTuning.checkpoints.permissions.delete(\n * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB',\n * {\n * fine_tuned_model_checkpoint:\n * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',\n * },\n * );\n * ```\n */\n delete(permissionID, params, options) {\n const { fine_tuned_model_checkpoint } = params;\n return this._client.delete(path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options);\n }\n}\n//# sourceMappingURL=permissions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as PermissionsAPI from \"./permissions.mjs\";\nimport { Permissions, } from \"./permissions.mjs\";\nexport class Checkpoints extends APIResource {\n constructor() {\n super(...arguments);\n this.permissions = new PermissionsAPI.Permissions(this._client);\n }\n}\nCheckpoints.Permissions = Permissions;\n//# sourceMappingURL=checkpoints.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Checkpoints extends APIResource {\n /**\n * List checkpoints for a fine-tuning job.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * )) {\n * // ...\n * }\n * ```\n */\n list(fineTuningJobID, query = {}, options) {\n return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options });\n }\n}\n//# sourceMappingURL=checkpoints.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../core/resource.mjs\";\nimport * as CheckpointsAPI from \"./checkpoints.mjs\";\nimport { Checkpoints, } from \"./checkpoints.mjs\";\nimport { CursorPage } from \"../../../core/pagination.mjs\";\nimport { path } from \"../../../internal/utils/path.mjs\";\nexport class Jobs extends APIResource {\n constructor() {\n super(...arguments);\n this.checkpoints = new CheckpointsAPI.Checkpoints(this._client);\n }\n /**\n * Creates a fine-tuning job which begins the process of creating a new model from\n * a given dataset.\n *\n * Response includes details of the enqueued job including job status and the name\n * of the fine-tuned models once complete.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.create({\n * model: 'gpt-4o-mini',\n * training_file: 'file-abc123',\n * });\n * ```\n */\n create(body, options) {\n return this._client.post('/fine_tuning/jobs', { body, ...options });\n }\n /**\n * Get info about a fine-tuning job.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.retrieve(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n retrieve(fineTuningJobID, options) {\n return this._client.get(path `/fine_tuning/jobs/${fineTuningJobID}`, options);\n }\n /**\n * List your organization's fine-tuning jobs\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fineTuningJob of client.fineTuning.jobs.list()) {\n * // ...\n * }\n * ```\n */\n list(query = {}, options) {\n return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options });\n }\n /**\n * Immediately cancel a fine-tune job.\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.cancel(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n cancel(fineTuningJobID, options) {\n return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options);\n }\n /**\n * Get status updates for a fine-tuning job.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * )) {\n * // ...\n * }\n * ```\n */\n listEvents(fineTuningJobID, query = {}, options) {\n return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options });\n }\n /**\n * Pause a fine-tune job.\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.pause(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n pause(fineTuningJobID, options) {\n return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options);\n }\n /**\n * Resume a fine-tune job.\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.resume(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n resume(fineTuningJobID, options) {\n return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options);\n }\n}\nJobs.Checkpoints = Checkpoints;\n//# sourceMappingURL=jobs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as MethodsAPI from \"./methods.mjs\";\nimport { Methods, } from \"./methods.mjs\";\nimport * as AlphaAPI from \"./alpha/alpha.mjs\";\nimport { Alpha } from \"./alpha/alpha.mjs\";\nimport * as CheckpointsAPI from \"./checkpoints/checkpoints.mjs\";\nimport { Checkpoints } from \"./checkpoints/checkpoints.mjs\";\nimport * as JobsAPI from \"./jobs/jobs.mjs\";\nimport { Jobs, } from \"./jobs/jobs.mjs\";\nexport class FineTuning extends APIResource {\n constructor() {\n super(...arguments);\n this.methods = new MethodsAPI.Methods(this._client);\n this.jobs = new JobsAPI.Jobs(this._client);\n this.checkpoints = new CheckpointsAPI.Checkpoints(this._client);\n this.alpha = new AlphaAPI.Alpha(this._client);\n }\n}\nFineTuning.Methods = Methods;\nFineTuning.Jobs = Jobs;\nFineTuning.Checkpoints = Checkpoints;\nFineTuning.Alpha = Alpha;\n//# sourceMappingURL=fine-tuning.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nexport class GraderModels extends APIResource {\n}\n//# sourceMappingURL=grader-models.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as GraderModelsAPI from \"./grader-models.mjs\";\nimport { GraderModels, } from \"./grader-models.mjs\";\nexport class Graders extends APIResource {\n constructor() {\n super(...arguments);\n this.graderModels = new GraderModelsAPI.GraderModels(this._client);\n }\n}\nGraders.GraderModels = GraderModels;\n//# sourceMappingURL=graders.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { multipartFormRequestOptions } from \"../internal/uploads.mjs\";\nexport class Images extends APIResource {\n /**\n * Creates a variation of a given image. This endpoint only supports `dall-e-2`.\n *\n * @example\n * ```ts\n * const imagesResponse = await client.images.createVariation({\n * image: fs.createReadStream('otter.png'),\n * });\n * ```\n */\n createVariation(body, options) {\n return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }, this._client));\n }\n edit(body, options) {\n return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client));\n }\n generate(body, options) {\n return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false });\n }\n}\n//# sourceMappingURL=images.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { Page } from \"../core/pagination.mjs\";\nimport { path } from \"../internal/utils/path.mjs\";\nexport class Models extends APIResource {\n /**\n * Retrieves a model instance, providing basic information about the model such as\n * the owner and permissioning.\n */\n retrieve(model, options) {\n return this._client.get(path `/models/${model}`, options);\n }\n /**\n * Lists the currently available models, and provides basic information about each\n * one such as the owner and availability.\n */\n list(options) {\n return this._client.getAPIList('/models', (Page), options);\n }\n /**\n * Delete a fine-tuned model. You must have the Owner role in your organization to\n * delete a model.\n */\n delete(model, options) {\n return this._client.delete(path `/models/${model}`, options);\n }\n}\n//# sourceMappingURL=models.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nexport class Moderations extends APIResource {\n /**\n * Classifies if text and/or image inputs are potentially harmful. Learn more in\n * the [moderation guide](https://platform.openai.com/docs/guides/moderation).\n */\n create(body, options) {\n return this._client.post('/moderations', { body, ...options });\n }\n}\n//# sourceMappingURL=moderations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Calls extends APIResource {\n /**\n * Accept an incoming SIP call and configure the realtime session that will handle\n * it.\n *\n * @example\n * ```ts\n * await client.realtime.calls.accept('call_id', {\n * type: 'realtime',\n * });\n * ```\n */\n accept(callID, body, options) {\n return this._client.post(path `/realtime/calls/${callID}/accept`, {\n body,\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n /**\n * End an active Realtime API call, whether it was initiated over SIP or WebRTC.\n *\n * @example\n * ```ts\n * await client.realtime.calls.hangup('call_id');\n * ```\n */\n hangup(callID, options) {\n return this._client.post(path `/realtime/calls/${callID}/hangup`, {\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n /**\n * Transfer an active SIP call to a new destination using the SIP REFER verb.\n *\n * @example\n * ```ts\n * await client.realtime.calls.refer('call_id', {\n * target_uri: 'tel:+14155550123',\n * });\n * ```\n */\n refer(callID, body, options) {\n return this._client.post(path `/realtime/calls/${callID}/refer`, {\n body,\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n /**\n * Decline an incoming SIP call by returning a SIP status code to the caller.\n *\n * @example\n * ```ts\n * await client.realtime.calls.reject('call_id');\n * ```\n */\n reject(callID, body = {}, options) {\n return this._client.post(path `/realtime/calls/${callID}/reject`, {\n body,\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n}\n//# sourceMappingURL=calls.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nexport class ClientSecrets extends APIResource {\n /**\n * Create a Realtime client secret with an associated session configuration.\n *\n * @example\n * ```ts\n * const clientSecret =\n * await client.realtime.clientSecrets.create();\n * ```\n */\n create(body, options) {\n return this._client.post('/realtime/client_secrets', { body, ...options });\n }\n}\n//# sourceMappingURL=client-secrets.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as CallsAPI from \"./calls.mjs\";\nimport { Calls } from \"./calls.mjs\";\nimport * as ClientSecretsAPI from \"./client-secrets.mjs\";\nimport { ClientSecrets, } from \"./client-secrets.mjs\";\nexport class Realtime extends APIResource {\n constructor() {\n super(...arguments);\n this.clientSecrets = new ClientSecretsAPI.ClientSecrets(this._client);\n this.calls = new CallsAPI.Calls(this._client);\n }\n}\nRealtime.ClientSecrets = ClientSecrets;\nRealtime.Calls = Calls;\n//# sourceMappingURL=realtime.mjs.map","var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"../../internal/tslib.mjs\";\nimport { APIUserAbortError, OpenAIError } from \"../../error.mjs\";\nimport { EventStream } from \"../EventStream.mjs\";\nimport { maybeParseResponse } from \"../ResponsesParser.mjs\";\nexport class ResponseStream extends EventStream {\n constructor(params) {\n super();\n _ResponseStream_instances.add(this);\n _ResponseStream_params.set(this, void 0);\n _ResponseStream_currentResponseSnapshot.set(this, void 0);\n _ResponseStream_finalResponse.set(this, void 0);\n __classPrivateFieldSet(this, _ResponseStream_params, params, \"f\");\n }\n static createResponse(client, params, options) {\n const runner = new ResponseStream(params);\n runner._run(() => runner._createOrRetrieveResponse(client, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n async _createOrRetrieveResponse(client, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ResponseStream_instances, \"m\", _ResponseStream_beginRequest).call(this);\n let stream;\n let starting_after = null;\n if ('response_id' in params) {\n stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true });\n starting_after = params.starting_after ?? null;\n }\n else {\n stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });\n }\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _ResponseStream_instances, \"m\", _ResponseStream_addEvent).call(this, event, starting_after);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return __classPrivateFieldGet(this, _ResponseStream_instances, \"m\", _ResponseStream_endRequest).call(this);\n }\n [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, \"f\");\n }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) {\n if (this.ended)\n return;\n const maybeEmit = (name, event) => {\n if (starting_after == null || event.sequence_number > starting_after) {\n this._emit(name, event);\n }\n };\n const response = __classPrivateFieldGet(this, _ResponseStream_instances, \"m\", _ResponseStream_accumulateResponse).call(this, event);\n maybeEmit('event', event);\n switch (event.type) {\n case 'response.output_text.delta': {\n const output = response.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'message') {\n const content = output.content[event.content_index];\n if (!content) {\n throw new OpenAIError(`missing content at index ${event.content_index}`);\n }\n if (content.type !== 'output_text') {\n throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);\n }\n maybeEmit('response.output_text.delta', {\n ...event,\n snapshot: content.text,\n });\n }\n break;\n }\n case 'response.function_call_arguments.delta': {\n const output = response.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'function_call') {\n maybeEmit('response.function_call_arguments.delta', {\n ...event,\n snapshot: output.arguments,\n });\n }\n break;\n }\n default:\n maybeEmit(event.type, event);\n break;\n }\n }, _ResponseStream_endRequest = function _ResponseStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, \"f\");\n if (!snapshot) {\n throw new OpenAIError(`request ended without sending any events`);\n }\n __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, \"f\");\n const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, \"f\"));\n __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, \"f\");\n return parsedResponse;\n }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) {\n let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, \"f\");\n if (!snapshot) {\n if (event.type !== 'response.created') {\n throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);\n }\n snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, \"f\");\n return snapshot;\n }\n switch (event.type) {\n case 'response.output_item.added': {\n snapshot.output.push(event.item);\n break;\n }\n case 'response.content_part.added': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n const type = output.type;\n const part = event.part;\n if (type === 'message' && part.type !== 'reasoning_text') {\n output.content.push(part);\n }\n else if (type === 'reasoning' && part.type === 'reasoning_text') {\n if (!output.content) {\n output.content = [];\n }\n output.content.push(part);\n }\n break;\n }\n case 'response.output_text.delta': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'message') {\n const content = output.content[event.content_index];\n if (!content) {\n throw new OpenAIError(`missing content at index ${event.content_index}`);\n }\n if (content.type !== 'output_text') {\n throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);\n }\n content.text += event.delta;\n }\n break;\n }\n case 'response.function_call_arguments.delta': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'function_call') {\n output.arguments += event.delta;\n }\n break;\n }\n case 'response.reasoning_text.delta': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'reasoning') {\n const content = output.content?.[event.content_index];\n if (!content) {\n throw new OpenAIError(`missing content at index ${event.content_index}`);\n }\n if (content.type !== 'reasoning_text') {\n throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);\n }\n content.text += event.delta;\n }\n break;\n }\n case 'response.completed': {\n __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, \"f\");\n break;\n }\n }\n return snapshot;\n }, Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n this.on('event', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n }\n else {\n pushQueue.push(event);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true }));\n }\n const event = pushQueue.shift();\n return { value: event, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n /**\n * @returns a promise that resolves with the final Response, or rejects\n * if an error occurred or the stream ended prematurely without producing a REsponse.\n */\n async finalResponse() {\n await this.done();\n const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, \"f\");\n if (!response)\n throw new OpenAIError('stream ended without producing a ChatCompletion');\n return response;\n }\n}\nfunction finalizeResponse(snapshot, params) {\n return maybeParseResponse(snapshot, params);\n}\n//# sourceMappingURL=ResponseStream.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { CursorPage } from \"../../core/pagination.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class InputItems extends APIResource {\n /**\n * Returns a list of input items for a given response.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const responseItem of client.responses.inputItems.list(\n * 'response_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(responseID, query = {}, options) {\n return this._client.getAPIList(path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options });\n }\n}\n//# sourceMappingURL=input-items.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nexport class InputTokens extends APIResource {\n /**\n * Get input token counts\n *\n * @example\n * ```ts\n * const response = await client.responses.inputTokens.count();\n * ```\n */\n count(body = {}, options) {\n return this._client.post('/responses/input_tokens', { body, ...options });\n }\n}\n//# sourceMappingURL=input-tokens.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { parseResponse, addOutputText, } from \"../../lib/ResponsesParser.mjs\";\nimport { ResponseStream } from \"../../lib/responses/ResponseStream.mjs\";\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as InputItemsAPI from \"./input-items.mjs\";\nimport { InputItems } from \"./input-items.mjs\";\nimport * as InputTokensAPI from \"./input-tokens.mjs\";\nimport { InputTokens } from \"./input-tokens.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Responses extends APIResource {\n constructor() {\n super(...arguments);\n this.inputItems = new InputItemsAPI.InputItems(this._client);\n this.inputTokens = new InputTokensAPI.InputTokens(this._client);\n }\n create(body, options) {\n return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => {\n if ('object' in rsp && rsp.object === 'response') {\n addOutputText(rsp);\n }\n return rsp;\n });\n }\n retrieve(responseID, query = {}, options) {\n return this._client.get(path `/responses/${responseID}`, {\n query,\n ...options,\n stream: query?.stream ?? false,\n })._thenUnwrap((rsp) => {\n if ('object' in rsp && rsp.object === 'response') {\n addOutputText(rsp);\n }\n return rsp;\n });\n }\n /**\n * Deletes a model response with the given ID.\n *\n * @example\n * ```ts\n * await client.responses.delete(\n * 'resp_677efb5139a88190b512bc3fef8e535d',\n * );\n * ```\n */\n delete(responseID, options) {\n return this._client.delete(path `/responses/${responseID}`, {\n ...options,\n headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),\n });\n }\n parse(body, options) {\n return this._client.responses\n .create(body, options)\n ._thenUnwrap((response) => parseResponse(response, body));\n }\n /**\n * Creates a model response stream\n */\n stream(body, options) {\n return ResponseStream.createResponse(this._client, body, options);\n }\n /**\n * Cancels a model response with the given ID. Only responses created with the\n * `background` parameter set to `true` can be cancelled.\n * [Learn more](https://platform.openai.com/docs/guides/background).\n *\n * @example\n * ```ts\n * const response = await client.responses.cancel(\n * 'resp_677efb5139a88190b512bc3fef8e535d',\n * );\n * ```\n */\n cancel(responseID, options) {\n return this._client.post(path `/responses/${responseID}/cancel`, options);\n }\n}\nResponses.InputItems = InputItems;\nResponses.InputTokens = InputTokens;\n//# sourceMappingURL=responses.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { multipartFormRequestOptions } from \"../../internal/uploads.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Parts extends APIResource {\n /**\n * Adds a\n * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.\n * A Part represents a chunk of bytes from the file you are trying to upload.\n *\n * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload\n * maximum of 8 GB.\n *\n * It is possible to add multiple Parts in parallel. You can decide the intended\n * order of the Parts when you\n * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).\n */\n create(uploadID, body, options) {\n return this._client.post(path `/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options }, this._client));\n }\n}\n//# sourceMappingURL=parts.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as PartsAPI from \"./parts.mjs\";\nimport { Parts } from \"./parts.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Uploads extends APIResource {\n constructor() {\n super(...arguments);\n this.parts = new PartsAPI.Parts(this._client);\n }\n /**\n * Creates an intermediate\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object\n * that you can add\n * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.\n * Currently, an Upload can accept at most 8 GB in total and expires after an hour\n * after you create it.\n *\n * Once you complete the Upload, we will create a\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * contains all the parts you uploaded. This File is usable in the rest of our\n * platform as a regular File object.\n *\n * For certain `purpose` values, the correct `mime_type` must be specified. Please\n * refer to documentation for the\n * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).\n *\n * For guidance on the proper filename extensions for each purpose, please follow\n * the documentation on\n * [creating a File](https://platform.openai.com/docs/api-reference/files/create).\n */\n create(body, options) {\n return this._client.post('/uploads', { body, ...options });\n }\n /**\n * Cancels the Upload. No Parts may be added after an Upload is cancelled.\n */\n cancel(uploadID, options) {\n return this._client.post(path `/uploads/${uploadID}/cancel`, options);\n }\n /**\n * Completes the\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).\n *\n * Within the returned Upload object, there is a nested\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * is ready to use in the rest of the platform.\n *\n * You can specify the order of the Parts by passing in an ordered list of the Part\n * IDs.\n *\n * The number of bytes uploaded upon completion must match the number of bytes\n * initially specified when creating the Upload object. No Parts may be added after\n * an Upload is completed.\n */\n complete(uploadID, body, options) {\n return this._client.post(path `/uploads/${uploadID}/complete`, { body, ...options });\n }\n}\nUploads.Parts = Parts;\n//# sourceMappingURL=uploads.mjs.map","/**\n * Like `Promise.allSettled()` but throws an error if any promises are rejected.\n */\nexport const allSettledWithThrow = async (promises) => {\n const results = await Promise.allSettled(promises);\n const rejected = results.filter((result) => result.status === 'rejected');\n if (rejected.length) {\n for (const result of rejected) {\n console.error(result.reason);\n }\n throw new Error(`${rejected.length} promise(s) failed - see the above errors`);\n }\n // Note: TS was complaining about using `.filter().map()` here for some reason\n const values = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n values.push(result.value);\n }\n }\n return values;\n};\n//# sourceMappingURL=Util.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { CursorPage } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { sleep } from \"../../internal/utils/sleep.mjs\";\nimport { allSettledWithThrow } from \"../../lib/Util.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class FileBatches extends APIResource {\n /**\n * Create a vector store file batch.\n */\n create(vectorStoreID, body, options) {\n return this._client.post(path `/vector_stores/${vectorStoreID}/file_batches`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Retrieves a vector store file batch.\n */\n retrieve(batchID, params, options) {\n const { vector_store_id } = params;\n return this._client.get(path `/vector_stores/${vector_store_id}/file_batches/${batchID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Cancel a vector store file batch. This attempts to cancel the processing of\n * files in this batch as soon as possible.\n */\n cancel(batchID, params, options) {\n const { vector_store_id } = params;\n return this._client.post(path `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Create a vector store batch and poll until all files have been processed.\n */\n async createAndPoll(vectorStoreId, body, options) {\n const batch = await this.create(vectorStoreId, body);\n return await this.poll(vectorStoreId, batch.id, options);\n }\n /**\n * Returns a list of vector store files in a batch.\n */\n listFiles(batchID, params, options) {\n const { vector_store_id, ...query } = params;\n return this._client.getAPIList(path `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (CursorPage), { query, ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) });\n }\n /**\n * Wait for the given file batch to be processed.\n *\n * Note: this will return even if one of the files failed to process, you need to\n * check batch.file_counts.failed_count to handle this case.\n */\n async poll(vectorStoreID, batchID, options) {\n const headers = buildHeaders([\n options?.headers,\n {\n 'X-Stainless-Poll-Helper': 'true',\n 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined,\n },\n ]);\n while (true) {\n const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, {\n ...options,\n headers,\n }).withResponse();\n switch (batch.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'cancelled':\n case 'completed':\n return batch;\n }\n }\n }\n /**\n * Uploads the given files concurrently and then creates a vector store file batch.\n *\n * The concurrency limit is configurable using the `maxConcurrency` parameter.\n */\n async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {\n if (files == null || files.length == 0) {\n throw new Error(`No \\`files\\` provided to process. If you've already uploaded files you should use \\`.createAndPoll()\\` instead`);\n }\n const configuredConcurrency = options?.maxConcurrency ?? 5;\n // We cap the number of workers at the number of files (so we don't start any unnecessary workers)\n const concurrencyLimit = Math.min(configuredConcurrency, files.length);\n const client = this._client;\n const fileIterator = files.values();\n const allFileIds = [...fileIds];\n // This code is based on this design. The libraries don't accommodate our environment limits.\n // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all\n async function processFiles(iterator) {\n for (let item of iterator) {\n const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);\n allFileIds.push(fileObj.id);\n }\n }\n // Start workers to process results\n const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);\n // Wait for all processing to complete.\n await allSettledWithThrow(workers);\n return await this.createAndPoll(vectorStoreId, {\n file_ids: allFileIds,\n });\n }\n}\n//# sourceMappingURL=file-batches.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport { CursorPage, Page } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { sleep } from \"../../internal/utils.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class Files extends APIResource {\n /**\n * Create a vector store file by attaching a\n * [File](https://platform.openai.com/docs/api-reference/files) to a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).\n */\n create(vectorStoreID, body, options) {\n return this._client.post(path `/vector_stores/${vectorStoreID}/files`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Retrieves a vector store file.\n */\n retrieve(fileID, params, options) {\n const { vector_store_id } = params;\n return this._client.get(path `/vector_stores/${vector_store_id}/files/${fileID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Update attributes on a vector store file.\n */\n update(fileID, params, options) {\n const { vector_store_id, ...body } = params;\n return this._client.post(path `/vector_stores/${vector_store_id}/files/${fileID}`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Returns a list of vector store files.\n */\n list(vectorStoreID, query = {}, options) {\n return this._client.getAPIList(path `/vector_stores/${vectorStoreID}/files`, (CursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Delete a vector store file. This will remove the file from the vector store but\n * the file itself will not be deleted. To delete the file, use the\n * [delete file](https://platform.openai.com/docs/api-reference/files/delete)\n * endpoint.\n */\n delete(fileID, params, options) {\n const { vector_store_id } = params;\n return this._client.delete(path `/vector_stores/${vector_store_id}/files/${fileID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Attach a file to the given vector store and wait for it to be processed.\n */\n async createAndPoll(vectorStoreId, body, options) {\n const file = await this.create(vectorStoreId, body, options);\n return await this.poll(vectorStoreId, file.id, options);\n }\n /**\n * Wait for the vector store file to finish processing.\n *\n * Note: this will return even if the file failed to process, you need to check\n * file.last_error and file.status to handle these cases\n */\n async poll(vectorStoreID, fileID, options) {\n const headers = buildHeaders([\n options?.headers,\n {\n 'X-Stainless-Poll-Helper': 'true',\n 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined,\n },\n ]);\n while (true) {\n const fileResponse = await this.retrieve(fileID, {\n vector_store_id: vectorStoreID,\n }, { ...options, headers }).withResponse();\n const file = fileResponse.data;\n switch (file.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'completed':\n return file;\n }\n }\n }\n /**\n * Upload a file to the `files` API and then attach it to the given vector store.\n *\n * Note the file will be asynchronously processed (you can use the alternative\n * polling helper method to wait for processing to complete).\n */\n async upload(vectorStoreId, file, options) {\n const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);\n return this.create(vectorStoreId, { file_id: fileInfo.id }, options);\n }\n /**\n * Add a file to a vector store and poll until processing is complete.\n */\n async uploadAndPoll(vectorStoreId, file, options) {\n const fileInfo = await this.upload(vectorStoreId, file, options);\n return await this.poll(vectorStoreId, fileInfo.id, options);\n }\n /**\n * Retrieve the parsed contents of a vector store file.\n */\n content(fileID, params, options) {\n const { vector_store_id } = params;\n return this._client.getAPIList(path `/vector_stores/${vector_store_id}/files/${fileID}/content`, (Page), { ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) });\n }\n}\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../core/resource.mjs\";\nimport * as FileBatchesAPI from \"./file-batches.mjs\";\nimport { FileBatches, } from \"./file-batches.mjs\";\nimport * as FilesAPI from \"./files.mjs\";\nimport { Files, } from \"./files.mjs\";\nimport { CursorPage, Page } from \"../../core/pagination.mjs\";\nimport { buildHeaders } from \"../../internal/headers.mjs\";\nimport { path } from \"../../internal/utils/path.mjs\";\nexport class VectorStores extends APIResource {\n constructor() {\n super(...arguments);\n this.files = new FilesAPI.Files(this._client);\n this.fileBatches = new FileBatchesAPI.FileBatches(this._client);\n }\n /**\n * Create a vector store.\n */\n create(body, options) {\n return this._client.post('/vector_stores', {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Retrieves a vector store.\n */\n retrieve(vectorStoreID, options) {\n return this._client.get(path `/vector_stores/${vectorStoreID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Modifies a vector store.\n */\n update(vectorStoreID, body, options) {\n return this._client.post(path `/vector_stores/${vectorStoreID}`, {\n body,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Returns a list of vector stores.\n */\n list(query = {}, options) {\n return this._client.getAPIList('/vector_stores', (CursorPage), {\n query,\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Delete a vector store.\n */\n delete(vectorStoreID, options) {\n return this._client.delete(path `/vector_stores/${vectorStoreID}`, {\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n /**\n * Search a vector store for relevant chunks based on a query and file attributes\n * filter.\n */\n search(vectorStoreID, body, options) {\n return this._client.getAPIList(path `/vector_stores/${vectorStoreID}/search`, (Page), {\n body,\n method: 'post',\n ...options,\n headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),\n });\n }\n}\nVectorStores.Files = Files;\nVectorStores.FileBatches = FileBatches;\n//# sourceMappingURL=vector-stores.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../core/resource.mjs\";\nimport { ConversationCursorPage } from \"../core/pagination.mjs\";\nimport { buildHeaders } from \"../internal/headers.mjs\";\nimport { maybeMultipartFormRequestOptions } from \"../internal/uploads.mjs\";\nimport { path } from \"../internal/utils/path.mjs\";\nexport class Videos extends APIResource {\n /**\n * Create a video\n */\n create(body, options) {\n return this._client.post('/videos', maybeMultipartFormRequestOptions({ body, ...options }, this._client));\n }\n /**\n * Retrieve a video\n */\n retrieve(videoID, options) {\n return this._client.get(path `/videos/${videoID}`, options);\n }\n /**\n * List videos\n */\n list(query = {}, options) {\n return this._client.getAPIList('/videos', (ConversationCursorPage), { query, ...options });\n }\n /**\n * Delete a video\n */\n delete(videoID, options) {\n return this._client.delete(path `/videos/${videoID}`, options);\n }\n /**\n * Download video content\n */\n downloadContent(videoID, query = {}, options) {\n return this._client.get(path `/videos/${videoID}/content`, {\n query,\n ...options,\n headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]),\n __binaryResponse: true,\n });\n }\n /**\n * Create a video remix\n */\n remix(videoID, body, options) {\n return this._client.post(path `/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options }, this._client));\n }\n}\n//# sourceMappingURL=videos.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader;\nimport { __classPrivateFieldGet } from \"../internal/tslib.mjs\";\nimport { InvalidWebhookSignatureError } from \"../error.mjs\";\nimport { APIResource } from \"../core/resource.mjs\";\nimport { buildHeaders } from \"../internal/headers.mjs\";\nexport class Webhooks extends APIResource {\n constructor() {\n super(...arguments);\n _Webhooks_instances.add(this);\n }\n /**\n * Validates that the given payload was sent by OpenAI and parses the payload.\n */\n async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {\n await this.verifySignature(payload, headers, secret, tolerance);\n return JSON.parse(payload);\n }\n /**\n * Validates whether or not the webhook payload was sent by OpenAI.\n *\n * An error will be raised if the webhook payload was not sent by OpenAI.\n *\n * @param payload - The webhook payload\n * @param headers - The webhook headers\n * @param secret - The webhook secret (optional, will use client secret if not provided)\n * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes)\n */\n async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {\n if (typeof crypto === 'undefined' ||\n typeof crypto.subtle.importKey !== 'function' ||\n typeof crypto.subtle.verify !== 'function') {\n throw new Error('Webhook signature verification is only supported when the `crypto` global is defined');\n }\n __classPrivateFieldGet(this, _Webhooks_instances, \"m\", _Webhooks_validateSecret).call(this, secret);\n const headersObj = buildHeaders([headers]).values;\n const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, \"m\", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-signature');\n const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, \"m\", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-timestamp');\n const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, \"m\", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-id');\n // Validate timestamp to prevent replay attacks\n const timestampSeconds = parseInt(timestamp, 10);\n if (isNaN(timestampSeconds)) {\n throw new InvalidWebhookSignatureError('Invalid webhook timestamp format');\n }\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (nowSeconds - timestampSeconds > tolerance) {\n throw new InvalidWebhookSignatureError('Webhook timestamp is too old');\n }\n if (timestampSeconds > nowSeconds + tolerance) {\n throw new InvalidWebhookSignatureError('Webhook timestamp is too new');\n }\n // Extract signatures from v1, format\n // The signature header can have multiple values, separated by spaces.\n // Each value is in the format v1,. We should accept if any match.\n const signatures = signatureHeader\n .split(' ')\n .map((part) => (part.startsWith('v1,') ? part.substring(3) : part));\n // Decode the secret if it starts with whsec_\n const decodedSecret = secret.startsWith('whsec_') ?\n Buffer.from(secret.replace('whsec_', ''), 'base64')\n : Buffer.from(secret, 'utf-8');\n // Create the signed payload: {webhook_id}.{timestamp}.{payload}\n const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;\n // Import the secret as a cryptographic key for HMAC\n const key = await crypto.subtle.importKey('raw', decodedSecret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);\n // Check if any signature matches using timing-safe WebCrypto verify\n for (const signature of signatures) {\n try {\n const signatureBytes = Buffer.from(signature, 'base64');\n const isValid = await crypto.subtle.verify('HMAC', key, signatureBytes, new TextEncoder().encode(signedPayload));\n if (isValid) {\n return; // Valid signature found\n }\n }\n catch {\n // Invalid base64 or signature format, continue to next signature\n continue;\n }\n }\n throw new InvalidWebhookSignatureError('The given webhook signature does not match the expected signature');\n }\n}\n_Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) {\n if (typeof secret !== 'string' || secret.length === 0) {\n throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`);\n }\n}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) {\n if (!headers) {\n throw new Error(`Headers are required`);\n }\n const value = headers.get(name);\n if (value === null || value === undefined) {\n throw new Error(`Missing required header: ${name}`);\n }\n return value;\n};\n//# sourceMappingURL=webhooks.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport * from \"./chat/index.mjs\";\nexport * from \"./shared.mjs\";\nexport { Audio } from \"./audio/audio.mjs\";\nexport { Batches, } from \"./batches.mjs\";\nexport { Beta } from \"./beta/beta.mjs\";\nexport { Completions, } from \"./completions.mjs\";\nexport { Containers, } from \"./containers/containers.mjs\";\nexport { Conversations } from \"./conversations/conversations.mjs\";\nexport { Embeddings, } from \"./embeddings.mjs\";\nexport { Evals, } from \"./evals/evals.mjs\";\nexport { Files, } from \"./files.mjs\";\nexport { FineTuning } from \"./fine-tuning/fine-tuning.mjs\";\nexport { Graders } from \"./graders/graders.mjs\";\nexport { Images, } from \"./images.mjs\";\nexport { Models } from \"./models.mjs\";\nexport { Moderations, } from \"./moderations.mjs\";\nexport { Realtime } from \"./realtime/realtime.mjs\";\nexport { Responses } from \"./responses/responses.mjs\";\nexport { Uploads } from \"./uploads/uploads.mjs\";\nexport { VectorStores, } from \"./vector-stores/vector-stores.mjs\";\nexport { Videos, } from \"./videos.mjs\";\nexport { Webhooks } from \"./webhooks.mjs\";\n//# sourceMappingURL=index.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _OpenAI_instances, _a, _OpenAI_encoder, _OpenAI_baseURLOverridden;\nimport { __classPrivateFieldGet, __classPrivateFieldSet } from \"./internal/tslib.mjs\";\nimport { uuid4 } from \"./internal/utils/uuid.mjs\";\nimport { validatePositiveInteger, isAbsoluteURL, safeJSON } from \"./internal/utils/values.mjs\";\nimport { sleep } from \"./internal/utils/sleep.mjs\";\nimport { castToError, isAbortError } from \"./internal/errors.mjs\";\nimport { getPlatformHeaders } from \"./internal/detect-platform.mjs\";\nimport * as Shims from \"./internal/shims.mjs\";\nimport * as Opts from \"./internal/request-options.mjs\";\nimport * as qs from \"./internal/qs/index.mjs\";\nimport { VERSION } from \"./version.mjs\";\nimport * as Errors from \"./core/error.mjs\";\nimport * as Pagination from \"./core/pagination.mjs\";\nimport * as Uploads from \"./core/uploads.mjs\";\nimport * as API from \"./resources/index.mjs\";\nimport { APIPromise } from \"./core/api-promise.mjs\";\nimport { Batches, } from \"./resources/batches.mjs\";\nimport { Completions, } from \"./resources/completions.mjs\";\nimport { Embeddings, } from \"./resources/embeddings.mjs\";\nimport { Files, } from \"./resources/files.mjs\";\nimport { Images, } from \"./resources/images.mjs\";\nimport { Models } from \"./resources/models.mjs\";\nimport { Moderations, } from \"./resources/moderations.mjs\";\nimport { Videos, } from \"./resources/videos.mjs\";\nimport { Webhooks } from \"./resources/webhooks.mjs\";\nimport { Audio } from \"./resources/audio/audio.mjs\";\nimport { Beta } from \"./resources/beta/beta.mjs\";\nimport { Chat } from \"./resources/chat/chat.mjs\";\nimport { Containers, } from \"./resources/containers/containers.mjs\";\nimport { Conversations } from \"./resources/conversations/conversations.mjs\";\nimport { Evals, } from \"./resources/evals/evals.mjs\";\nimport { FineTuning } from \"./resources/fine-tuning/fine-tuning.mjs\";\nimport { Graders } from \"./resources/graders/graders.mjs\";\nimport { Realtime } from \"./resources/realtime/realtime.mjs\";\nimport { Responses } from \"./resources/responses/responses.mjs\";\nimport { Uploads as UploadsAPIUploads, } from \"./resources/uploads/uploads.mjs\";\nimport { VectorStores, } from \"./resources/vector-stores/vector-stores.mjs\";\nimport { isRunningInBrowser } from \"./internal/detect-platform.mjs\";\nimport { buildHeaders } from \"./internal/headers.mjs\";\nimport { readEnv } from \"./internal/utils/env.mjs\";\nimport { formatRequestDetails, loggerFor, parseLogLevel, } from \"./internal/utils/log.mjs\";\nimport { isEmptyObj } from \"./internal/utils/values.mjs\";\n/**\n * API Client for interfacing with the OpenAI API.\n */\nexport class OpenAI {\n /**\n * API Client for interfacing with the OpenAI API.\n *\n * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]\n * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.\n * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) {\n _OpenAI_instances.add(this);\n _OpenAI_encoder.set(this, void 0);\n this.completions = new API.Completions(this);\n this.chat = new API.Chat(this);\n this.embeddings = new API.Embeddings(this);\n this.files = new API.Files(this);\n this.images = new API.Images(this);\n this.audio = new API.Audio(this);\n this.moderations = new API.Moderations(this);\n this.models = new API.Models(this);\n this.fineTuning = new API.FineTuning(this);\n this.graders = new API.Graders(this);\n this.vectorStores = new API.VectorStores(this);\n this.webhooks = new API.Webhooks(this);\n this.beta = new API.Beta(this);\n this.batches = new API.Batches(this);\n this.uploads = new API.Uploads(this);\n this.responses = new API.Responses(this);\n this.realtime = new API.Realtime(this);\n this.conversations = new API.Conversations(this);\n this.evals = new API.Evals(this);\n this.containers = new API.Containers(this);\n this.videos = new API.Videos(this);\n if (apiKey === undefined) {\n throw new Errors.OpenAIError('Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.');\n }\n const options = {\n apiKey,\n organization,\n project,\n webhookSecret,\n ...opts,\n baseURL: baseURL || `https://api.openai.com/v1`,\n };\n if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {\n throw new Errors.OpenAIError(\"It looks like you're running in a browser-like environment.\\n\\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\\nIf you understand the risks and have appropriate mitigations in place,\\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\\n\\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\\n\\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\\n\");\n }\n this.baseURL = options.baseURL;\n this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;\n this.logger = options.logger ?? console;\n const defaultLogLevel = 'warn';\n // Set default logLevel early so that we can log a warning in parseLogLevel.\n this.logLevel = defaultLogLevel;\n this.logLevel =\n parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??\n parseLogLevel(readEnv('OPENAI_LOG'), \"process.env['OPENAI_LOG']\", this) ??\n defaultLogLevel;\n this.fetchOptions = options.fetchOptions;\n this.maxRetries = options.maxRetries ?? 2;\n this.fetch = options.fetch ?? Shims.getDefaultFetch();\n __classPrivateFieldSet(this, _OpenAI_encoder, Opts.FallbackEncoder, \"f\");\n this._options = options;\n this.apiKey = typeof apiKey === 'string' ? apiKey : 'Missing Key';\n this.organization = organization;\n this.project = project;\n this.webhookSecret = webhookSecret;\n }\n /**\n * Create a new client instance re-using the same options given to the current client with optional overriding.\n */\n withOptions(options) {\n const client = new this.constructor({\n ...this._options,\n baseURL: this.baseURL,\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n logger: this.logger,\n logLevel: this.logLevel,\n fetch: this.fetch,\n fetchOptions: this.fetchOptions,\n apiKey: this.apiKey,\n organization: this.organization,\n project: this.project,\n webhookSecret: this.webhookSecret,\n ...options,\n });\n return client;\n }\n defaultQuery() {\n return this._options.defaultQuery;\n }\n validateHeaders({ values, nulls }) {\n return;\n }\n async authHeaders(opts) {\n return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);\n }\n stringifyQuery(query) {\n return qs.stringify(query, { arrayFormat: 'brackets' });\n }\n getUserAgent() {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n defaultIdempotencyKey() {\n return `stainless-node-retry-${uuid4()}`;\n }\n makeStatusError(status, error, message, headers) {\n return Errors.APIError.generate(status, error, message, headers);\n }\n async _callApiKey() {\n const apiKey = this._options.apiKey;\n if (typeof apiKey !== 'function')\n return false;\n let token;\n try {\n token = await apiKey();\n }\n catch (err) {\n if (err instanceof Errors.OpenAIError)\n throw err;\n throw new Errors.OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, \n // @ts-ignore\n { cause: err });\n }\n if (typeof token !== 'string' || !token) {\n throw new Errors.OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);\n }\n this.apiKey = token;\n return true;\n }\n buildURL(path, query, defaultBaseURL) {\n const baseURL = (!__classPrivateFieldGet(this, _OpenAI_instances, \"m\", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;\n const url = isAbsoluteURL(path) ?\n new URL(path)\n : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query };\n }\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query);\n }\n return url.toString();\n }\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n async prepareOptions(options) {\n await this._callApiKey();\n }\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n async prepareRequest(request, { url, options }) { }\n get(path, opts) {\n return this.methodRequest('get', path, opts);\n }\n post(path, opts) {\n return this.methodRequest('post', path, opts);\n }\n patch(path, opts) {\n return this.methodRequest('patch', path, opts);\n }\n put(path, opts) {\n return this.methodRequest('put', path, opts);\n }\n delete(path, opts) {\n return this.methodRequest('delete', path, opts);\n }\n methodRequest(method, path, opts) {\n return this.request(Promise.resolve(opts).then((opts) => {\n return { method, path, ...opts };\n }));\n }\n request(options, remainingRetries = null) {\n return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));\n }\n async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n await this.prepareOptions(options);\n const { req, url, timeout } = await this.buildRequest(options, {\n retryCount: maxRetries - retriesRemaining,\n });\n await this.prepareRequest(req, { url, options });\n /** Not an API request ID, just for correlating local log entries. */\n const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');\n const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;\n const startTime = Date.now();\n loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({\n retryOfRequestLogID,\n method: options.method,\n url,\n options,\n headers: req.headers,\n }));\n if (options.signal?.aborted) {\n throw new Errors.APIUserAbortError();\n }\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n const headersTime = Date.now();\n if (response instanceof globalThis.Error) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n if (options.signal?.aborted) {\n throw new Errors.APIUserAbortError();\n }\n // detect native connection timeout errors\n // deno throws \"TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)\"\n // undici throws \"TypeError: fetch failed\" with cause \"ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)\"\n // others do not provide enough information to distinguish timeouts from other connection errors\n const isTimeout = isAbortError(response) ||\n /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));\n if (retriesRemaining) {\n loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);\n loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }));\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);\n }\n loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);\n loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }));\n if (isTimeout) {\n throw new Errors.APIConnectionTimeoutError();\n }\n throw new Errors.APIConnectionError({ cause: response });\n }\n const specialHeaders = [...response.headers.entries()]\n .filter(([name]) => name === 'x-request-id')\n .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))\n .join('');\n const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;\n if (!response.ok) {\n const shouldRetry = await this.shouldRetry(response);\n if (retriesRemaining && shouldRetry) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n // We don't need the body of this response.\n await Shims.CancelReadableStream(response.body);\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n durationMs: headersTime - startTime,\n }));\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);\n }\n const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n const errText = await response.text().catch((err) => castToError(err).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n message: errMessage,\n durationMs: Date.now() - startTime,\n }));\n const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);\n throw err;\n }\n loggerFor(this).info(responseInfo);\n loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n durationMs: headersTime - startTime,\n }));\n return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };\n }\n getAPIList(path, Page, opts) {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n requestAPIList(Page, options) {\n const request = this.makeRequest(options, null, undefined);\n return new Pagination.PagePromise(this, request, Page);\n }\n async fetchWithTimeout(url, init, ms, controller) {\n const { signal, method, ...options } = init || {};\n if (signal)\n signal.addEventListener('abort', () => controller.abort());\n const timeout = setTimeout(() => controller.abort(), ms);\n const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||\n (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);\n const fetchOptions = {\n signal: controller.signal,\n ...(isReadableBody ? { duplex: 'half' } : {}),\n method: 'GET',\n ...options,\n };\n if (method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = method.toUpperCase();\n }\n try {\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n return await this.fetch.call(undefined, url, fetchOptions);\n }\n finally {\n clearTimeout(timeout);\n }\n }\n async shouldRetry(response) {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true')\n return true;\n if (shouldRetryHeader === 'false')\n return false;\n // Retry on request timeouts.\n if (response.status === 408)\n return true;\n // Retry on lock timeouts.\n if (response.status === 409)\n return true;\n // Retry on rate limits.\n if (response.status === 429)\n return true;\n // Retry internal errors.\n if (response.status >= 500)\n return true;\n return false;\n }\n async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {\n let timeoutMillis;\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.get('retry-after');\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n }\n else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n return this.makeRequest(options, retriesRemaining - 1, requestLogID);\n }\n calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n const numRetries = maxRetries - retriesRemaining;\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n return sleepSeconds * jitter * 1000;\n }\n async buildRequest(inputOptions, { retryCount = 0 } = {}) {\n const options = { ...inputOptions };\n const { method, path, query, defaultBaseURL } = options;\n const url = this.buildURL(path, query, defaultBaseURL);\n if ('timeout' in options)\n validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const { bodyHeaders, body } = this.buildBody({ options });\n const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });\n const req = {\n method,\n headers: reqHeaders,\n ...(options.signal && { signal: options.signal }),\n ...(globalThis.ReadableStream &&\n body instanceof globalThis.ReadableStream && { duplex: 'half' }),\n ...(body && { body }),\n ...(this.fetchOptions ?? {}),\n ...(options.fetchOptions ?? {}),\n };\n return { req, url, timeout: options.timeout };\n }\n async buildHeaders({ options, method, bodyHeaders, retryCount, }) {\n let idempotencyHeaders = {};\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey)\n options.idempotencyKey = this.defaultIdempotencyKey();\n idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;\n }\n const headers = buildHeaders([\n idempotencyHeaders,\n {\n Accept: 'application/json',\n 'User-Agent': this.getUserAgent(),\n 'X-Stainless-Retry-Count': String(retryCount),\n ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),\n ...getPlatformHeaders(),\n 'OpenAI-Organization': this.organization,\n 'OpenAI-Project': this.project,\n },\n await this.authHeaders(options),\n this._options.defaultHeaders,\n bodyHeaders,\n options.headers,\n ]);\n this.validateHeaders(headers);\n return headers.values;\n }\n buildBody({ options: { body, headers: rawHeaders } }) {\n if (!body) {\n return { bodyHeaders: undefined, body: undefined };\n }\n const headers = buildHeaders([rawHeaders]);\n if (\n // Pass raw type verbatim\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof DataView ||\n (typeof body === 'string' &&\n // Preserve legacy string encoding behavior for now\n headers.values.has('content-type')) ||\n // `Blob` is superset of `File`\n (globalThis.Blob && body instanceof globalThis.Blob) ||\n // `FormData` -> `multipart/form-data`\n body instanceof FormData ||\n // `URLSearchParams` -> `application/x-www-form-urlencoded`\n body instanceof URLSearchParams ||\n // Send chunked stream (each chunk has own `length`)\n (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {\n return { bodyHeaders: undefined, body: body };\n }\n else if (typeof body === 'object' &&\n (Symbol.asyncIterator in body ||\n (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {\n return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };\n }\n else {\n return __classPrivateFieldGet(this, _OpenAI_encoder, \"f\").call(this, { body, headers });\n }\n }\n}\n_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {\n return this.baseURL !== 'https://api.openai.com/v1';\n};\nOpenAI.OpenAI = _a;\nOpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes\nOpenAI.OpenAIError = Errors.OpenAIError;\nOpenAI.APIError = Errors.APIError;\nOpenAI.APIConnectionError = Errors.APIConnectionError;\nOpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\nOpenAI.APIUserAbortError = Errors.APIUserAbortError;\nOpenAI.NotFoundError = Errors.NotFoundError;\nOpenAI.ConflictError = Errors.ConflictError;\nOpenAI.RateLimitError = Errors.RateLimitError;\nOpenAI.BadRequestError = Errors.BadRequestError;\nOpenAI.AuthenticationError = Errors.AuthenticationError;\nOpenAI.InternalServerError = Errors.InternalServerError;\nOpenAI.PermissionDeniedError = Errors.PermissionDeniedError;\nOpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError;\nOpenAI.InvalidWebhookSignatureError = Errors.InvalidWebhookSignatureError;\nOpenAI.toFile = Uploads.toFile;\nOpenAI.Completions = Completions;\nOpenAI.Chat = Chat;\nOpenAI.Embeddings = Embeddings;\nOpenAI.Files = Files;\nOpenAI.Images = Images;\nOpenAI.Audio = Audio;\nOpenAI.Moderations = Moderations;\nOpenAI.Models = Models;\nOpenAI.FineTuning = FineTuning;\nOpenAI.Graders = Graders;\nOpenAI.VectorStores = VectorStores;\nOpenAI.Webhooks = Webhooks;\nOpenAI.Beta = Beta;\nOpenAI.Batches = Batches;\nOpenAI.Uploads = UploadsAPIUploads;\nOpenAI.Responses = Responses;\nOpenAI.Realtime = Realtime;\nOpenAI.Conversations = Conversations;\nOpenAI.Evals = Evals;\nOpenAI.Containers = Containers;\nOpenAI.Videos = Videos;\n//# sourceMappingURL=client.mjs.map","import { buildHeaders } from \"./internal/headers.mjs\";\nimport * as Errors from \"./error.mjs\";\nimport { isObj, readEnv } from \"./internal/utils.mjs\";\nimport { OpenAI } from \"./client.mjs\";\n/** API Client for interfacing with the Azure OpenAI API. */\nexport class AzureOpenAI extends OpenAI {\n /**\n * API Client for interfacing with the Azure OpenAI API.\n *\n * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]\n * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`\n * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]\n * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('AZURE_OPENAI_API_KEY'), apiVersion = readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {\n if (!apiVersion) {\n throw new Errors.OpenAIError(\"The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).\");\n }\n if (typeof azureADTokenProvider === 'function') {\n dangerouslyAllowBrowser = true;\n }\n if (!azureADTokenProvider && !apiKey) {\n throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');\n }\n if (azureADTokenProvider && apiKey) {\n throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');\n }\n opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };\n if (!baseURL) {\n if (!endpoint) {\n endpoint = process.env['AZURE_OPENAI_ENDPOINT'];\n }\n if (!endpoint) {\n throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');\n }\n baseURL = `${endpoint}/openai`;\n }\n else {\n if (endpoint) {\n throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');\n }\n }\n super({\n apiKey: azureADTokenProvider ?? apiKey,\n baseURL,\n ...opts,\n ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),\n });\n this.apiVersion = '';\n this.apiVersion = apiVersion;\n this.deploymentName = deployment;\n }\n async buildRequest(options, props = {}) {\n if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {\n if (!isObj(options.body)) {\n throw new Error('Expected request body to be an object');\n }\n const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];\n if (model !== undefined && !this.baseURL.includes('/deployments')) {\n options.path = `/deployments/${model}${options.path}`;\n }\n }\n return super.buildRequest(options, props);\n }\n async authHeaders(opts) {\n if (typeof this._options.apiKey === 'string') {\n return buildHeaders([{ 'api-key': this.apiKey }]);\n }\n return super.authHeaders(opts);\n }\n}\nconst _deployments_endpoints = new Set([\n '/completions',\n '/chat/completions',\n '/embeddings',\n '/audio/transcriptions',\n '/audio/translations',\n '/audio/speech',\n '/images/generations',\n '/batches',\n '/images/edits',\n]);\n//# sourceMappingURL=azure.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport { OpenAI as default } from \"./client.mjs\";\nexport { toFile } from \"./core/uploads.mjs\";\nexport { APIPromise } from \"./core/api-promise.mjs\";\nexport { OpenAI } from \"./client.mjs\";\nexport { PagePromise } from \"./core/pagination.mjs\";\nexport { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, InvalidWebhookSignatureError, } from \"./core/error.mjs\";\nexport { AzureOpenAI } from \"./azure.mjs\";\n//# sourceMappingURL=index.mjs.map","import { isReasoningModel, messageToOpenAIRole } from \"../utils/misc.js\";\nimport { getEndpoint } from \"../utils/azure.js\";\nimport { _convertToOpenAITool, convertResponsesCustomTool, formatFunctionDefinitions, isBuiltInTool, isCustomTool } from \"../utils/tools.js\";\nimport { getStructuredOutputMethod, interopZodResponseFormat } from \"../utils/output.js\";\nimport { OpenAI as OpenAI$1 } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { RunnableLambda, RunnablePassthrough, RunnableSequence } from \"@langchain/core/runnables\";\nimport { JsonOutputParser, StructuredOutputParser } from \"@langchain/core/output_parsers\";\nimport { JsonOutputKeyToolsParser } from \"@langchain/core/output_parsers/openai_tools\";\nimport { getSchemaDescription, isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\n\n//#region src/chat_models/base.ts\n/** @internal */\nvar BaseChatOpenAI = class extends BaseChatModel {\n\ttemperature;\n\ttopP;\n\tfrequencyPenalty;\n\tpresencePenalty;\n\tn;\n\tlogitBias;\n\tmodel = \"gpt-3.5-turbo\";\n\tmodelKwargs;\n\tstop;\n\tstopSequences;\n\tuser;\n\ttimeout;\n\tstreaming = false;\n\tstreamUsage = true;\n\tmaxTokens;\n\tlogprobs;\n\ttopLogprobs;\n\tapiKey;\n\torganization;\n\t__includeRawResponse;\n\t/** @internal */\n\tclient;\n\t/** @internal */\n\tclientConfig;\n\t/**\n\t* Whether the model supports the `strict` argument when passing in tools.\n\t* If `undefined` the `strict` argument will not be passed to OpenAI.\n\t*/\n\tsupportsStrictToolCalling;\n\taudio;\n\tmodalities;\n\treasoning;\n\t/**\n\t* Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable\n\t* output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your\n\t* OpenAI organization or project. This must be configured directly with OpenAI.\n\t*\n\t* See:\n\t* https://platform.openai.com/docs/guides/your-data\n\t* https://platform.openai.com/docs/api-reference/responses/create#responses-create-store\n\t*\n\t* @default false\n\t*/\n\tzdrEnabled;\n\t/**\n\t* Service tier to use for this request. Can be \"auto\", \"default\", or \"flex\" or \"priority\".\n\t* Specifies the service tier for prioritization and latency optimization.\n\t*/\n\tservice_tier;\n\t/**\n\t* Used by OpenAI to cache responses for similar requests to optimize your cache\n\t* hit rates.\n\t* [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n\t*/\n\tpromptCacheKey;\n\t/**\n\t* The verbosity of the model's response.\n\t*/\n\tverbosity;\n\tdefaultOptions;\n\t_llmType() {\n\t\treturn \"openai\";\n\t}\n\tstatic lc_name() {\n\t\treturn \"ChatOpenAI\";\n\t}\n\tget callKeys() {\n\t\treturn [\n\t\t\t...super.callKeys,\n\t\t\t\"options\",\n\t\t\t\"function_call\",\n\t\t\t\"functions\",\n\t\t\t\"tools\",\n\t\t\t\"tool_choice\",\n\t\t\t\"promptIndex\",\n\t\t\t\"response_format\",\n\t\t\t\"seed\",\n\t\t\t\"reasoning\",\n\t\t\t\"service_tier\"\n\t\t];\n\t}\n\tlc_serializable = true;\n\tget lc_secrets() {\n\t\treturn {\n\t\t\tapiKey: \"OPENAI_API_KEY\",\n\t\t\torganization: \"OPENAI_ORGANIZATION\"\n\t\t};\n\t}\n\tget lc_aliases() {\n\t\treturn {\n\t\t\tapiKey: \"openai_api_key\",\n\t\t\tmodelName: \"model\"\n\t\t};\n\t}\n\tget lc_serializable_keys() {\n\t\treturn [\n\t\t\t\"configuration\",\n\t\t\t\"logprobs\",\n\t\t\t\"topLogprobs\",\n\t\t\t\"prefixMessages\",\n\t\t\t\"supportsStrictToolCalling\",\n\t\t\t\"modalities\",\n\t\t\t\"audio\",\n\t\t\t\"temperature\",\n\t\t\t\"maxTokens\",\n\t\t\t\"topP\",\n\t\t\t\"frequencyPenalty\",\n\t\t\t\"presencePenalty\",\n\t\t\t\"n\",\n\t\t\t\"logitBias\",\n\t\t\t\"user\",\n\t\t\t\"streaming\",\n\t\t\t\"streamUsage\",\n\t\t\t\"model\",\n\t\t\t\"modelName\",\n\t\t\t\"modelKwargs\",\n\t\t\t\"stop\",\n\t\t\t\"stopSequences\",\n\t\t\t\"timeout\",\n\t\t\t\"apiKey\",\n\t\t\t\"cache\",\n\t\t\t\"maxConcurrency\",\n\t\t\t\"maxRetries\",\n\t\t\t\"verbose\",\n\t\t\t\"callbacks\",\n\t\t\t\"tags\",\n\t\t\t\"metadata\",\n\t\t\t\"disableStreaming\",\n\t\t\t\"zdrEnabled\",\n\t\t\t\"reasoning\",\n\t\t\t\"promptCacheKey\",\n\t\t\t\"verbosity\"\n\t\t];\n\t}\n\tgetLsParams(options) {\n\t\tconst params = this.invocationParams(options);\n\t\treturn {\n\t\t\tls_provider: \"openai\",\n\t\t\tls_model_name: this.model,\n\t\t\tls_model_type: \"chat\",\n\t\t\tls_temperature: params.temperature ?? void 0,\n\t\t\tls_max_tokens: params.max_tokens ?? void 0,\n\t\t\tls_stop: options.stop\n\t\t};\n\t}\n\t/** @ignore */\n\t_identifyingParams() {\n\t\treturn {\n\t\t\tmodel_name: this.model,\n\t\t\t...this.invocationParams(),\n\t\t\t...this.clientConfig\n\t\t};\n\t}\n\t/**\n\t* Get the identifying parameters for the model\n\t*/\n\tidentifyingParams() {\n\t\treturn this._identifyingParams();\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields ?? {});\n\t\tconst configApiKey = typeof fields?.configuration?.apiKey === \"string\" ? fields?.configuration?.apiKey : void 0;\n\t\tthis.apiKey = fields?.apiKey ?? configApiKey ?? getEnvironmentVariable(\"OPENAI_API_KEY\");\n\t\tthis.organization = fields?.configuration?.organization ?? getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\t\tthis.model = fields?.model ?? fields?.modelName ?? this.model;\n\t\tthis.modelKwargs = fields?.modelKwargs ?? {};\n\t\tthis.timeout = fields?.timeout;\n\t\tthis.temperature = fields?.temperature ?? this.temperature;\n\t\tthis.topP = fields?.topP ?? this.topP;\n\t\tthis.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;\n\t\tthis.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;\n\t\tthis.logprobs = fields?.logprobs;\n\t\tthis.topLogprobs = fields?.topLogprobs;\n\t\tthis.n = fields?.n ?? this.n;\n\t\tthis.logitBias = fields?.logitBias;\n\t\tthis.stop = fields?.stopSequences ?? fields?.stop;\n\t\tthis.stopSequences = this.stop;\n\t\tthis.user = fields?.user;\n\t\tthis.__includeRawResponse = fields?.__includeRawResponse;\n\t\tthis.audio = fields?.audio;\n\t\tthis.modalities = fields?.modalities;\n\t\tthis.reasoning = fields?.reasoning;\n\t\tthis.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens;\n\t\tthis.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey;\n\t\tthis.verbosity = fields?.verbosity ?? this.verbosity;\n\t\tthis.disableStreaming = fields?.disableStreaming === true;\n\t\tthis.streaming = fields?.streaming === true;\n\t\tif (this.disableStreaming) this.streaming = false;\n\t\tif (fields?.streaming === false) this.disableStreaming = true;\n\t\tthis.streamUsage = fields?.streamUsage ?? this.streamUsage;\n\t\tif (this.disableStreaming) this.streamUsage = false;\n\t\tthis.clientConfig = {\n\t\t\tapiKey: this.apiKey,\n\t\t\torganization: this.organization,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t...fields?.configuration\n\t\t};\n\t\tif (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling;\n\t\tif (fields?.service_tier !== void 0) this.service_tier = fields.service_tier;\n\t\tthis.zdrEnabled = fields?.zdrEnabled ?? false;\n\t}\n\t/**\n\t* Returns backwards compatible reasoning parameters from constructor params and call options\n\t* @internal\n\t*/\n\t_getReasoningParams(options) {\n\t\tif (!isReasoningModel(this.model)) return;\n\t\tlet reasoning;\n\t\tif (this.reasoning !== void 0) reasoning = {\n\t\t\t...reasoning,\n\t\t\t...this.reasoning\n\t\t};\n\t\tif (options?.reasoning !== void 0) reasoning = {\n\t\t\t...reasoning,\n\t\t\t...options.reasoning\n\t\t};\n\t\treturn reasoning;\n\t}\n\t/**\n\t* Returns an openai compatible response format from a set of options\n\t* @internal\n\t*/\n\t_getResponseFormat(resFormat) {\n\t\tif (resFormat && resFormat.type === \"json_schema\" && resFormat.json_schema.schema && isInteropZodSchema(resFormat.json_schema.schema)) return interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description });\n\t\treturn resFormat;\n\t}\n\t_combineCallOptions(additionalOptions) {\n\t\treturn {\n\t\t\t...this.defaultOptions,\n\t\t\t...additionalOptions ?? {}\n\t\t};\n\t}\n\t/** @internal */\n\t_getClientOptions(options) {\n\t\tif (!this.client) {\n\t\t\tconst openAIEndpointConfig = { baseURL: this.clientConfig.baseURL };\n\t\t\tconst endpoint = getEndpoint(openAIEndpointConfig);\n\t\t\tconst params = {\n\t\t\t\t...this.clientConfig,\n\t\t\t\tbaseURL: endpoint,\n\t\t\t\ttimeout: this.timeout,\n\t\t\t\tmaxRetries: 0\n\t\t\t};\n\t\t\tif (!params.baseURL) delete params.baseURL;\n\t\t\tthis.client = new OpenAI$1(params);\n\t\t}\n\t\tconst requestOptions = {\n\t\t\t...this.clientConfig,\n\t\t\t...options\n\t\t};\n\t\treturn requestOptions;\n\t}\n\t_convertChatOpenAIToolToCompletionsTool(tool, fields) {\n\t\tif (isCustomTool(tool)) return convertResponsesCustomTool(tool.metadata.customTool);\n\t\tif (isOpenAITool(tool)) {\n\t\t\tif (fields?.strict !== void 0) return {\n\t\t\t\t...tool,\n\t\t\t\tfunction: {\n\t\t\t\t\t...tool.function,\n\t\t\t\t\tstrict: fields.strict\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn tool;\n\t\t}\n\t\treturn _convertToOpenAITool(tool, fields);\n\t}\n\tbindTools(tools, kwargs) {\n\t\tlet strict;\n\t\tif (kwargs?.strict !== void 0) strict = kwargs.strict;\n\t\telse if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;\n\t\treturn this.withConfig({\n\t\t\ttools: tools.map((tool) => isBuiltInTool(tool) || isCustomTool(tool) ? tool : this._convertChatOpenAIToolToCompletionsTool(tool, { strict })),\n\t\t\t...kwargs\n\t\t});\n\t}\n\tasync stream(input, options) {\n\t\treturn super.stream(input, this._combineCallOptions(options));\n\t}\n\tasync invoke(input, options) {\n\t\treturn super.invoke(input, this._combineCallOptions(options));\n\t}\n\t/** @ignore */\n\t_combineLLMOutput(...llmOutputs) {\n\t\treturn llmOutputs.reduce((acc, llmOutput) => {\n\t\t\tif (llmOutput && llmOutput.tokenUsage) {\n\t\t\t\tacc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0;\n\t\t\t\tacc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0;\n\t\t\t\tacc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0;\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, { tokenUsage: {\n\t\t\tcompletionTokens: 0,\n\t\t\tpromptTokens: 0,\n\t\t\ttotalTokens: 0\n\t\t} });\n\t}\n\tasync getNumTokensFromMessages(messages) {\n\t\tlet totalCount = 0;\n\t\tlet tokensPerMessage = 0;\n\t\tlet tokensPerName = 0;\n\t\tif (this.model === \"gpt-3.5-turbo-0301\") {\n\t\t\ttokensPerMessage = 4;\n\t\t\ttokensPerName = -1;\n\t\t} else {\n\t\t\ttokensPerMessage = 3;\n\t\t\ttokensPerName = 1;\n\t\t}\n\t\tconst countPerMessage = await Promise.all(messages.map(async (message) => {\n\t\t\tconst textCount = await this.getNumTokens(message.content);\n\t\t\tconst roleCount = await this.getNumTokens(messageToOpenAIRole(message));\n\t\t\tconst nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0;\n\t\t\tlet count = textCount + tokensPerMessage + roleCount + nameCount;\n\t\t\tconst openAIMessage = message;\n\t\t\tif (openAIMessage._getType() === \"function\") count -= 2;\n\t\t\tif (openAIMessage.additional_kwargs?.function_call) count += 3;\n\t\t\tif (openAIMessage?.additional_kwargs.function_call?.name) count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name);\n\t\t\tif (openAIMessage.additional_kwargs.function_call?.arguments) try {\n\t\t\t\tcount += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments)));\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Error parsing function arguments\", error, JSON.stringify(openAIMessage.additional_kwargs.function_call));\n\t\t\t\tcount += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments);\n\t\t\t}\n\t\t\ttotalCount += count;\n\t\t\treturn count;\n\t\t}));\n\t\ttotalCount += 3;\n\t\treturn {\n\t\t\ttotalCount,\n\t\t\tcountPerMessage\n\t\t};\n\t}\n\t/** @internal */\n\tasync _getNumTokensFromGenerations(generations) {\n\t\tconst generationUsages = await Promise.all(generations.map(async (generation) => {\n\t\t\tif (generation.message.additional_kwargs?.function_call) return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0];\n\t\t\telse return await this.getNumTokens(generation.message.content);\n\t\t}));\n\t\treturn generationUsages.reduce((a, b) => a + b, 0);\n\t}\n\t/** @internal */\n\tasync _getEstimatedTokenCountFromPrompt(messages, functions, function_call) {\n\t\tlet tokens = (await this.getNumTokensFromMessages(messages)).totalCount;\n\t\tif (functions && function_call !== \"auto\") {\n\t\t\tconst promptDefinitions = formatFunctionDefinitions(functions);\n\t\t\ttokens += await this.getNumTokens(promptDefinitions);\n\t\t\ttokens += 9;\n\t\t}\n\t\tif (functions && messages.find((m) => m._getType() === \"system\")) tokens -= 4;\n\t\tif (function_call === \"none\") tokens += 1;\n\t\telse if (typeof function_call === \"object\") tokens += await this.getNumTokens(function_call.name) + 4;\n\t\treturn tokens;\n\t}\n\t/** @internal */\n\t_getStructuredOutputMethod(config) {\n\t\tconst ensuredConfig = { ...config };\n\t\tif (!this.model.startsWith(\"gpt-3\") && !this.model.startsWith(\"gpt-4-\") && this.model !== \"gpt-4\") {\n\t\t\tif (ensuredConfig?.method === void 0) return \"jsonSchema\";\n\t\t} else if (ensuredConfig.method === \"jsonSchema\") console.warn(`[WARNING]: JSON Schema is not supported for model \"${this.model}\". Falling back to tool calling.`);\n\t\treturn ensuredConfig.method;\n\t}\n\t/**\n\t* Add structured output to the model.\n\t*\n\t* The OpenAI model family supports the following structured output methods:\n\t* - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`,\n\t* `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later.\n\t* - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality\n\t* of your application.\n\t* - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model\n\t* output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify.\n\t* We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case.\n\t*\n\t* The default method is `functionCalling`.\n\t*\n\t* @see https://platform.openai.com/docs/guides/structured-outputs\n\t* @param outputSchema - The schema to use for structured output.\n\t* @param config - The structured output method options.\n\t* @returns The model with structured output.\n\t*/\n\twithStructuredOutput(outputSchema, config) {\n\t\tlet llm;\n\t\tlet outputParser;\n\t\tconst { schema, name, includeRaw } = {\n\t\t\t...config,\n\t\t\tschema: outputSchema\n\t\t};\n\t\tif (config?.strict !== void 0 && config.method === \"jsonMode\") throw new Error(\"Argument `strict` is only supported for `method` = 'function_calling'\");\n\t\tconst method = getStructuredOutputMethod(this.model, config?.method);\n\t\tif (method === \"jsonMode\") {\n\t\t\tif (isInteropZodSchema(schema)) outputParser = StructuredOutputParser.fromZodSchema(schema);\n\t\t\telse outputParser = new JsonOutputParser();\n\t\t\tconst asJsonSchema = toJsonSchema(schema);\n\t\t\tllm = this.withConfig({\n\t\t\t\toutputVersion: \"v0\",\n\t\t\t\tresponse_format: { type: \"json_object\" },\n\t\t\t\tls_structured_output_format: {\n\t\t\t\t\tkwargs: { method: \"json_mode\" },\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttitle: name ?? \"extract\",\n\t\t\t\t\t\t...asJsonSchema\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (method === \"jsonSchema\") {\n\t\t\tconst openaiJsonSchemaParams = {\n\t\t\t\tname: name ?? \"extract\",\n\t\t\t\tdescription: getSchemaDescription(schema),\n\t\t\t\tschema,\n\t\t\t\tstrict: config?.strict\n\t\t\t};\n\t\t\tconst asJsonSchema = toJsonSchema(openaiJsonSchemaParams.schema);\n\t\t\tllm = this.withConfig({\n\t\t\t\toutputVersion: \"v0\",\n\t\t\t\tresponse_format: {\n\t\t\t\t\ttype: \"json_schema\",\n\t\t\t\t\tjson_schema: openaiJsonSchemaParams\n\t\t\t\t},\n\t\t\t\tls_structured_output_format: {\n\t\t\t\t\tkwargs: { method: \"json_schema\" },\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttitle: openaiJsonSchemaParams.name,\n\t\t\t\t\t\tdescription: openaiJsonSchemaParams.description,\n\t\t\t\t\t\t...asJsonSchema\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (isInteropZodSchema(schema)) {\n\t\t\t\tconst altParser = StructuredOutputParser.fromZodSchema(schema);\n\t\t\t\toutputParser = RunnableLambda.from((aiMessage) => {\n\t\t\t\t\tif (\"parsed\" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed;\n\t\t\t\t\treturn altParser;\n\t\t\t\t});\n\t\t\t} else outputParser = new JsonOutputParser();\n\t\t} else {\n\t\t\tlet functionName = name ?? \"extract\";\n\t\t\tif (isInteropZodSchema(schema)) {\n\t\t\t\tconst asJsonSchema = toJsonSchema(schema);\n\t\t\t\tllm = this.withConfig({\n\t\t\t\t\toutputVersion: \"v0\",\n\t\t\t\t\ttools: [{\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\tname: functionName,\n\t\t\t\t\t\t\tdescription: asJsonSchema.description,\n\t\t\t\t\t\t\tparameters: asJsonSchema\n\t\t\t\t\t\t}\n\t\t\t\t\t}],\n\t\t\t\t\ttool_choice: {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: functionName }\n\t\t\t\t\t},\n\t\t\t\t\tls_structured_output_format: {\n\t\t\t\t\t\tkwargs: { method: \"function_calling\" },\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttitle: functionName,\n\t\t\t\t\t\t\t...asJsonSchema\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t...config?.strict !== void 0 ? { strict: config.strict } : {}\n\t\t\t\t});\n\t\t\t\toutputParser = new JsonOutputKeyToolsParser({\n\t\t\t\t\treturnSingle: true,\n\t\t\t\t\tkeyName: functionName,\n\t\t\t\t\tzodSchema: schema\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlet openAIFunctionDefinition;\n\t\t\t\tif (typeof schema.name === \"string\" && typeof schema.parameters === \"object\" && schema.parameters != null) {\n\t\t\t\t\topenAIFunctionDefinition = schema;\n\t\t\t\t\tfunctionName = schema.name;\n\t\t\t\t} else {\n\t\t\t\t\tfunctionName = schema.title ?? functionName;\n\t\t\t\t\topenAIFunctionDefinition = {\n\t\t\t\t\t\tname: functionName,\n\t\t\t\t\t\tdescription: schema.description ?? \"\",\n\t\t\t\t\t\tparameters: schema\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst asJsonSchema = toJsonSchema(schema);\n\t\t\t\tllm = this.withConfig({\n\t\t\t\t\toutputVersion: \"v0\",\n\t\t\t\t\ttools: [{\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: openAIFunctionDefinition\n\t\t\t\t\t}],\n\t\t\t\t\ttool_choice: {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tfunction: { name: functionName }\n\t\t\t\t\t},\n\t\t\t\t\tls_structured_output_format: {\n\t\t\t\t\t\tkwargs: { method: \"function_calling\" },\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttitle: functionName,\n\t\t\t\t\t\t\t...asJsonSchema\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t...config?.strict !== void 0 ? { strict: config.strict } : {}\n\t\t\t\t});\n\t\t\t\toutputParser = new JsonOutputKeyToolsParser({\n\t\t\t\t\treturnSingle: true,\n\t\t\t\t\tkeyName: functionName\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (!includeRaw) return llm.pipe(outputParser);\n\t\tconst parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });\n\t\tconst parserNone = RunnablePassthrough.assign({ parsed: () => null });\n\t\tconst parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });\n\t\treturn RunnableSequence.from([{ raw: llm }, parsedWithFallback]);\n\t}\n};\n\n//#endregion\nexport { BaseChatOpenAI };\n//# sourceMappingURL=base.js.map","//#region src/utils/errors.ts\nfunction addLangChainErrorFields(error, lc_error_code) {\n\terror.lc_error_code = lc_error_code;\n\terror.message = `${error.message}\\n\\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\\n`;\n\treturn error;\n}\n\n//#endregion\nexport { addLangChainErrorFields };\n//# sourceMappingURL=errors.js.map","import { addLangChainErrorFields } from \"./errors.js\";\nimport { APIConnectionTimeoutError, APIUserAbortError } from \"openai\";\n\n//#region src/utils/client.ts\nfunction wrapOpenAIClientError(e) {\n\tif (!e || typeof e !== \"object\") return e;\n\tlet error;\n\tif (e.constructor.name === APIConnectionTimeoutError.name && \"message\" in e && typeof e.message === \"string\") {\n\t\terror = new Error(e.message);\n\t\terror.name = \"TimeoutError\";\n\t} else if (e.constructor.name === APIUserAbortError.name && \"message\" in e && typeof e.message === \"string\") {\n\t\terror = new Error(e.message);\n\t\terror.name = \"AbortError\";\n\t} else if (\"status\" in e && e.status === 400 && \"message\" in e && typeof e.message === \"string\" && e.message.includes(\"tool_calls\")) error = addLangChainErrorFields(e, \"INVALID_TOOL_RESULTS\");\n\telse if (\"status\" in e && e.status === 401) error = addLangChainErrorFields(e, \"MODEL_AUTHENTICATION\");\n\telse if (\"status\" in e && e.status === 429) error = addLangChainErrorFields(e, \"MODEL_RATE_LIMIT\");\n\telse if (\"status\" in e && e.status === 404) error = addLangChainErrorFields(e, \"MODEL_NOT_FOUND\");\n\telse error = e;\n\treturn error;\n}\n\n//#endregion\nexport { wrapOpenAIClientError };\n//# sourceMappingURL=client.js.map","import { iife, isReasoningModel, messageToOpenAIRole } from \"./misc.js\";\nimport { ToolMessage, isAIMessage } from \"@langchain/core/messages\";\n\n//#region src/utils/standard.ts\nfunction _convertToChatCompletionsData(block) {\n\tif (block.type === \"image\") {\n\t\tif (block.url) return {\n\t\t\ttype: \"image_url\",\n\t\t\timage_url: { url: block.url }\n\t\t};\n\t\telse if (block.data) return {\n\t\t\ttype: \"image_url\",\n\t\t\timage_url: { url: `data:${block.mimeType};base64,${block.data}` }\n\t\t};\n\t}\n\tif (block.type === \"audio\") {\n\t\tif (block.data) {\n\t\t\tconst format = iife(() => {\n\t\t\t\tconst [, format$1] = block.mimeType.split(\"/\");\n\t\t\t\tif (format$1 === \"wav\" || format$1 === \"mp3\") return format$1;\n\t\t\t\treturn \"wav\";\n\t\t\t});\n\t\t\treturn {\n\t\t\t\ttype: \"input_audio\",\n\t\t\t\tinput_audio: {\n\t\t\t\t\tdata: block.data.toString(),\n\t\t\t\t\tformat\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\tif (block.type === \"file\") {\n\t\tif (block.data) return {\n\t\t\ttype: \"file\",\n\t\t\tfile: { file_data: block.data.toString() }\n\t\t};\n\t\tif (block.fileId) return {\n\t\t\ttype: \"file\",\n\t\t\tfile: { file_id: block.fileId }\n\t\t};\n\t}\n\treturn void 0;\n}\nfunction _convertToCompletionsMessageFromV1(message, model) {\n\tlet role = messageToOpenAIRole(message);\n\tif (role === \"system\" && isReasoningModel(model)) role = \"developer\";\n\tif (role === \"developer\") return {\n\t\trole: \"developer\",\n\t\tcontent: message.contentBlocks.filter((block) => block.type === \"text\")\n\t};\n\telse if (role === \"system\") return {\n\t\trole: \"system\",\n\t\tcontent: message.contentBlocks.filter((block) => block.type === \"text\")\n\t};\n\telse if (role === \"assistant\") return {\n\t\trole: \"assistant\",\n\t\tcontent: message.contentBlocks.filter((block) => block.type === \"text\")\n\t};\n\telse if (role === \"tool\" && ToolMessage.isInstance(message)) return {\n\t\trole: \"tool\",\n\t\ttool_call_id: message.tool_call_id,\n\t\tcontent: message.contentBlocks.filter((block) => block.type === \"text\")\n\t};\n\telse if (role === \"function\") return {\n\t\trole: \"function\",\n\t\tname: message.name ?? \"\",\n\t\tcontent: message.contentBlocks.filter((block) => block.type === \"text\").join(\"\")\n\t};\n\tfunction* iterateUserContent(blocks) {\n\t\tfor (const block of blocks) {\n\t\t\tif (block.type === \"text\") yield {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: block.text\n\t\t\t};\n\t\t\tconst data = _convertToChatCompletionsData(block);\n\t\t\tif (data) yield data;\n\t\t}\n\t}\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: Array.from(iterateUserContent(message.contentBlocks))\n\t};\n}\nfunction _convertToResponsesMessageFromV1(message) {\n\tconst isResponsesMessage = isAIMessage(message) && message.response_metadata?.model_provider === \"openai\";\n\tfunction* iterateItems() {\n\t\tconst messageRole = iife(() => {\n\t\t\ttry {\n\t\t\t\tconst role = messageToOpenAIRole(message);\n\t\t\t\tif (role === \"system\" || role === \"developer\" || role === \"assistant\" || role === \"user\") return role;\n\t\t\t\treturn \"assistant\";\n\t\t\t} catch {\n\t\t\t\treturn \"assistant\";\n\t\t\t}\n\t\t});\n\t\tlet currentMessage = void 0;\n\t\tconst functionCallIdsWithBlocks = /* @__PURE__ */ new Set();\n\t\tconst serverFunctionCallIdsWithBlocks = /* @__PURE__ */ new Set();\n\t\tconst pendingFunctionChunks = /* @__PURE__ */ new Map();\n\t\tconst pendingServerFunctionChunks = /* @__PURE__ */ new Map();\n\t\tfunction* flushMessage() {\n\t\t\tif (!currentMessage) return;\n\t\t\tconst content = currentMessage.content;\n\t\t\tif (typeof content === \"string\" && content.length > 0 || Array.isArray(content) && content.length > 0) yield currentMessage;\n\t\t\tcurrentMessage = void 0;\n\t\t}\n\t\tconst pushMessageContent = (content) => {\n\t\t\tif (!currentMessage) currentMessage = {\n\t\t\t\ttype: \"message\",\n\t\t\t\trole: messageRole,\n\t\t\t\tcontent: []\n\t\t\t};\n\t\t\tif (typeof currentMessage.content === \"string\") currentMessage.content = currentMessage.content.length > 0 ? [{\n\t\t\t\ttype: \"input_text\",\n\t\t\t\ttext: currentMessage.content\n\t\t\t}, ...content] : [...content];\n\t\t\telse currentMessage.content.push(...content);\n\t\t};\n\t\tconst toJsonString = (value) => {\n\t\t\tif (typeof value === \"string\") return value;\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(value ?? {});\n\t\t\t} catch {\n\t\t\t\treturn \"{}\";\n\t\t\t}\n\t\t};\n\t\tconst resolveImageItem = (block) => {\n\t\t\tconst detail = iife(() => {\n\t\t\t\tconst raw = block.metadata?.detail;\n\t\t\t\tif (raw === \"low\" || raw === \"high\" || raw === \"auto\") return raw;\n\t\t\t\treturn \"auto\";\n\t\t\t});\n\t\t\tif (block.fileId) return {\n\t\t\t\ttype: \"input_image\",\n\t\t\t\tdetail,\n\t\t\t\tfile_id: block.fileId\n\t\t\t};\n\t\t\tif (block.url) return {\n\t\t\t\ttype: \"input_image\",\n\t\t\t\tdetail,\n\t\t\t\timage_url: block.url\n\t\t\t};\n\t\t\tif (block.data) {\n\t\t\t\tconst base64Data = typeof block.data === \"string\" ? block.data : Buffer.from(block.data).toString(\"base64\");\n\t\t\t\tconst mimeType = block.mimeType ?? \"image/png\";\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\tdetail,\n\t\t\t\t\timage_url: `data:${mimeType};base64,${base64Data}`\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn void 0;\n\t\t};\n\t\tconst resolveFileItem = (block) => {\n\t\t\tconst filename = block.metadata?.filename ?? block.metadata?.name ?? block.metadata?.title;\n\t\t\tif (block.fileId && typeof filename === \"string\") return {\n\t\t\t\ttype: \"input_file\",\n\t\t\t\tfile_id: block.fileId,\n\t\t\t\t...filename ? { filename } : {}\n\t\t\t};\n\t\t\tif (block.url && typeof filename === \"string\") return {\n\t\t\t\ttype: \"input_file\",\n\t\t\t\tfile_url: block.url,\n\t\t\t\t...filename ? { filename } : {}\n\t\t\t};\n\t\t\tif (block.data && typeof filename === \"string\") {\n\t\t\t\tconst encoded = typeof block.data === \"string\" ? block.data : Buffer.from(block.data).toString(\"base64\");\n\t\t\t\tconst mimeType = block.mimeType ?? \"application/octet-stream\";\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"input_file\",\n\t\t\t\t\tfile_data: `data:${mimeType};base64,${encoded}`,\n\t\t\t\t\t...filename ? { filename } : {}\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn void 0;\n\t\t};\n\t\tconst convertReasoningBlock = (block) => {\n\t\t\tconst summaryEntries = iife(() => {\n\t\t\t\tif (Array.isArray(block.summary)) {\n\t\t\t\t\tconst candidate = block.summary;\n\t\t\t\t\tconst mapped = candidate?.map((item) => item?.text).filter((text) => typeof text === \"string\") ?? [];\n\t\t\t\t\tif (mapped.length > 0) return mapped;\n\t\t\t\t}\n\t\t\t\treturn block.reasoning ? [block.reasoning] : [];\n\t\t\t});\n\t\t\tconst summary = summaryEntries.length > 0 ? summaryEntries.map((text) => ({\n\t\t\t\ttype: \"summary_text\",\n\t\t\t\ttext\n\t\t\t})) : [{\n\t\t\t\ttype: \"summary_text\",\n\t\t\t\ttext: \"\"\n\t\t\t}];\n\t\t\tconst reasoningItem = {\n\t\t\t\ttype: \"reasoning\",\n\t\t\t\tid: block.id ?? \"\",\n\t\t\t\tsummary\n\t\t\t};\n\t\t\tif (block.reasoning) reasoningItem.content = [{\n\t\t\t\ttype: \"reasoning_text\",\n\t\t\t\ttext: block.reasoning\n\t\t\t}];\n\t\t\treturn reasoningItem;\n\t\t};\n\t\tconst convertFunctionCall = (block) => ({\n\t\t\ttype: \"function_call\",\n\t\t\tname: block.name ?? \"\",\n\t\t\tcall_id: block.id ?? \"\",\n\t\t\targuments: toJsonString(block.args)\n\t\t});\n\t\tconst convertFunctionCallOutput = (block) => {\n\t\t\tconst output = toJsonString(block.output);\n\t\t\tconst status = block.status === \"success\" ? \"completed\" : block.status === \"error\" ? \"incomplete\" : void 0;\n\t\t\treturn {\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: block.toolCallId ?? \"\",\n\t\t\t\toutput,\n\t\t\t\t...status ? { status } : {}\n\t\t\t};\n\t\t};\n\t\tfor (const block of message.contentBlocks) if (block.type === \"text\") pushMessageContent([{\n\t\t\ttype: \"input_text\",\n\t\t\ttext: block.text\n\t\t}]);\n\t\telse if (block.type === \"invalid_tool_call\") {} else if (block.type === \"reasoning\") {\n\t\t\tyield* flushMessage();\n\t\t\tyield convertReasoningBlock(block);\n\t\t} else if (block.type === \"tool_call\") {\n\t\t\tyield* flushMessage();\n\t\t\tconst id = block.id ?? \"\";\n\t\t\tif (id) {\n\t\t\t\tfunctionCallIdsWithBlocks.add(id);\n\t\t\t\tpendingFunctionChunks.delete(id);\n\t\t\t}\n\t\t\tyield convertFunctionCall(block);\n\t\t} else if (block.type === \"tool_call_chunk\") {\n\t\t\tif (block.id) {\n\t\t\t\tconst existing = pendingFunctionChunks.get(block.id) ?? {\n\t\t\t\t\tname: block.name,\n\t\t\t\t\targs: []\n\t\t\t\t};\n\t\t\t\tif (block.name) existing.name = block.name;\n\t\t\t\tif (block.args) existing.args.push(block.args);\n\t\t\t\tpendingFunctionChunks.set(block.id, existing);\n\t\t\t}\n\t\t} else if (block.type === \"server_tool_call\") {\n\t\t\tyield* flushMessage();\n\t\t\tconst id = block.id ?? \"\";\n\t\t\tif (id) {\n\t\t\t\tserverFunctionCallIdsWithBlocks.add(id);\n\t\t\t\tpendingServerFunctionChunks.delete(id);\n\t\t\t}\n\t\t\tyield convertFunctionCall(block);\n\t\t} else if (block.type === \"server_tool_call_chunk\") {\n\t\t\tif (block.id) {\n\t\t\t\tconst existing = pendingServerFunctionChunks.get(block.id) ?? {\n\t\t\t\t\tname: block.name,\n\t\t\t\t\targs: []\n\t\t\t\t};\n\t\t\t\tif (block.name) existing.name = block.name;\n\t\t\t\tif (block.args) existing.args.push(block.args);\n\t\t\t\tpendingServerFunctionChunks.set(block.id, existing);\n\t\t\t}\n\t\t} else if (block.type === \"server_tool_call_result\") {\n\t\t\tyield* flushMessage();\n\t\t\tyield convertFunctionCallOutput(block);\n\t\t} else if (block.type === \"audio\") {} else if (block.type === \"file\") {\n\t\t\tconst fileItem = resolveFileItem(block);\n\t\t\tif (fileItem) pushMessageContent([fileItem]);\n\t\t} else if (block.type === \"image\") {\n\t\t\tconst imageItem = resolveImageItem(block);\n\t\t\tif (imageItem) pushMessageContent([imageItem]);\n\t\t} else if (block.type === \"video\") {\n\t\t\tconst videoItem = resolveFileItem(block);\n\t\t\tif (videoItem) pushMessageContent([videoItem]);\n\t\t} else if (block.type === \"text-plain\") {\n\t\t\tif (block.text) pushMessageContent([{\n\t\t\t\ttype: \"input_text\",\n\t\t\t\ttext: block.text\n\t\t\t}]);\n\t\t} else if (block.type === \"non_standard\" && isResponsesMessage) {\n\t\t\tyield* flushMessage();\n\t\t\tyield block.value;\n\t\t}\n\t\tyield* flushMessage();\n\t\tfor (const [id, chunk] of pendingFunctionChunks) {\n\t\t\tif (!id || functionCallIdsWithBlocks.has(id)) continue;\n\t\t\tconst args = chunk.args.join(\"\");\n\t\t\tif (!chunk.name && !args) continue;\n\t\t\tyield {\n\t\t\t\ttype: \"function_call\",\n\t\t\t\tcall_id: id,\n\t\t\t\tname: chunk.name ?? \"\",\n\t\t\t\targuments: args\n\t\t\t};\n\t\t}\n\t\tfor (const [id, chunk] of pendingServerFunctionChunks) {\n\t\t\tif (!id || serverFunctionCallIdsWithBlocks.has(id)) continue;\n\t\t\tconst args = chunk.args.join(\"\");\n\t\t\tif (!chunk.name && !args) continue;\n\t\t\tyield {\n\t\t\t\ttype: \"function_call\",\n\t\t\t\tcall_id: id,\n\t\t\t\tname: chunk.name ?? \"\",\n\t\t\t\targuments: args\n\t\t\t};\n\t\t}\n\t}\n\treturn Array.from(iterateItems());\n}\n\n//#endregion\nexport { _convertToCompletionsMessageFromV1, _convertToResponsesMessageFromV1 };\n//# sourceMappingURL=standard.js.map","import { isReasoningModel, messageToOpenAIRole } from \"./misc.js\";\nimport { _convertToCompletionsMessageFromV1 } from \"./standard.js\";\nimport { convertLangChainToolCallToOpenAI } from \"@langchain/core/output_parsers/openai_tools\";\nimport { convertToProviderContentBlock, isAIMessage, isDataContentBlock, parseBase64DataUrl, parseMimeType } from \"@langchain/core/messages\";\n\n//#region src/utils/message_inputs.ts\nconst completionsApiContentBlockConverter = {\n\tproviderName: \"ChatOpenAI\",\n\tfromStandardTextBlock(block) {\n\t\treturn {\n\t\t\ttype: \"text\",\n\t\t\ttext: block.text\n\t\t};\n\t},\n\tfromStandardImageBlock(block) {\n\t\tif (block.source_type === \"url\") return {\n\t\t\ttype: \"image_url\",\n\t\t\timage_url: {\n\t\t\t\turl: block.url,\n\t\t\t\t...block.metadata?.detail ? { detail: block.metadata.detail } : {}\n\t\t\t}\n\t\t};\n\t\tif (block.source_type === \"base64\") {\n\t\t\tconst url = `data:${block.mime_type ?? \"\"};base64,${block.data}`;\n\t\t\treturn {\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: {\n\t\t\t\t\turl,\n\t\t\t\t\t...block.metadata?.detail ? { detail: block.metadata.detail } : {}\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);\n\t},\n\tfromStandardAudioBlock(block) {\n\t\tif (block.source_type === \"url\") {\n\t\t\tconst data = parseBase64DataUrl({ dataUrl: block.url });\n\t\t\tif (!data) throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`);\n\t\t\tconst rawMimeType = data.mime_type || block.mime_type || \"\";\n\t\t\tlet mimeType;\n\t\t\ttry {\n\t\t\t\tmimeType = parseMimeType(rawMimeType);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);\n\t\t\t}\n\t\t\tif (mimeType.type !== \"audio\" || mimeType.subtype !== \"wav\" && mimeType.subtype !== \"mp3\") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);\n\t\t\treturn {\n\t\t\t\ttype: \"input_audio\",\n\t\t\t\tinput_audio: {\n\t\t\t\t\tformat: mimeType.subtype,\n\t\t\t\t\tdata: data.data\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tif (block.source_type === \"base64\") {\n\t\t\tlet mimeType;\n\t\t\ttry {\n\t\t\t\tmimeType = parseMimeType(block.mime_type ?? \"\");\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);\n\t\t\t}\n\t\t\tif (mimeType.type !== \"audio\" || mimeType.subtype !== \"wav\" && mimeType.subtype !== \"mp3\") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);\n\t\t\treturn {\n\t\t\t\ttype: \"input_audio\",\n\t\t\t\tinput_audio: {\n\t\t\t\t\tformat: mimeType.subtype,\n\t\t\t\t\tdata: block.data\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);\n\t},\n\tfromStandardFileBlock(block) {\n\t\tif (block.source_type === \"url\") {\n\t\t\tconst data = parseBase64DataUrl({ dataUrl: block.url });\n\t\t\tif (!data) throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`);\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tfile: {\n\t\t\t\t\tfile_data: block.url,\n\t\t\t\t\t...block.metadata?.filename || block.metadata?.name ? { filename: block.metadata?.filename || block.metadata?.name } : {}\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tif (block.source_type === \"base64\") return {\n\t\t\ttype: \"file\",\n\t\t\tfile: {\n\t\t\t\tfile_data: `data:${block.mime_type ?? \"\"};base64,${block.data}`,\n\t\t\t\t...block.metadata?.filename || block.metadata?.name || block.metadata?.title ? { filename: block.metadata?.filename || block.metadata?.name || block.metadata?.title } : {}\n\t\t\t}\n\t\t};\n\t\tif (block.source_type === \"id\") return {\n\t\t\ttype: \"file\",\n\t\t\tfile: { file_id: block.id }\n\t\t};\n\t\tthrow new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);\n\t}\n};\nfunction _convertMessagesToOpenAIParams(messages, model) {\n\treturn messages.flatMap((message) => {\n\t\tif (\"output_version\" in message.response_metadata && message.response_metadata?.output_version === \"v1\") return _convertToCompletionsMessageFromV1(message);\n\t\tlet role = messageToOpenAIRole(message);\n\t\tif (role === \"system\" && isReasoningModel(model)) role = \"developer\";\n\t\tconst content = typeof message.content === \"string\" ? message.content : message.content.map((m) => {\n\t\t\tif (isDataContentBlock(m)) return convertToProviderContentBlock(m, completionsApiContentBlockConverter);\n\t\t\treturn m;\n\t\t});\n\t\tconst completionParam = {\n\t\t\trole,\n\t\t\tcontent\n\t\t};\n\t\tif (message.name != null) completionParam.name = message.name;\n\t\tif (message.additional_kwargs.function_call != null) {\n\t\t\tcompletionParam.function_call = message.additional_kwargs.function_call;\n\t\t\tcompletionParam.content = \"\";\n\t\t}\n\t\tif (isAIMessage(message) && !!message.tool_calls?.length) {\n\t\t\tcompletionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI);\n\t\t\tcompletionParam.content = \"\";\n\t\t} else {\n\t\t\tif (message.additional_kwargs.tool_calls != null) completionParam.tool_calls = message.additional_kwargs.tool_calls;\n\t\t\tif (message.tool_call_id != null) completionParam.tool_call_id = message.tool_call_id;\n\t\t}\n\t\tif (message.additional_kwargs.audio && typeof message.additional_kwargs.audio === \"object\" && \"id\" in message.additional_kwargs.audio) {\n\t\t\tconst audioMessage = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\taudio: { id: message.additional_kwargs.audio.id }\n\t\t\t};\n\t\t\treturn [completionParam, audioMessage];\n\t\t}\n\t\treturn completionParam;\n\t});\n}\n\n//#endregion\nexport { _convertMessagesToOpenAIParams, completionsApiContentBlockConverter };\n//# sourceMappingURL=message_inputs.js.map","import { iife, isReasoningModel, messageToOpenAIRole } from \"../utils/misc.js\";\nimport { convertCompletionsCustomTool, formatToOpenAIToolChoice, isBuiltInTool, isBuiltInToolChoice, isCustomTool, isCustomToolCall, isOpenAICustomTool, parseCustomToolCall } from \"../utils/tools.js\";\nimport { _convertOpenAIResponsesUsageToLangChainUsage } from \"../utils/output.js\";\nimport { BaseChatOpenAI } from \"./base.js\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport { _convertToResponsesMessageFromV1 } from \"../utils/standard.js\";\nimport { completionsApiContentBlockConverter } from \"../utils/message_inputs.js\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { makeInvalidToolCall, parseToolCall } from \"@langchain/core/output_parsers/openai_tools\";\nimport { AIMessage, AIMessageChunk, convertToProviderContentBlock, isAIMessage, isDataContentBlock } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk } from \"@langchain/core/outputs\";\n\n//#region src/chat_models/responses.ts\nconst _FUNCTION_CALL_IDS_MAP_KEY = \"__openai_function_call_ids__\";\n/**\n* OpenAI Responses API implementation.\n*\n* Will be exported in a later version of @langchain/openai.\n*\n* @internal\n*/\nvar ChatOpenAIResponses = class extends BaseChatOpenAI {\n\tinvocationParams(options) {\n\t\tlet strict;\n\t\tif (options?.strict !== void 0) strict = options.strict;\n\t\telse if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;\n\t\tconst params = {\n\t\t\tmodel: this.model,\n\t\t\ttemperature: this.temperature,\n\t\t\ttop_p: this.topP,\n\t\t\tuser: this.user,\n\t\t\tstream: this.streaming,\n\t\t\tprevious_response_id: options?.previous_response_id,\n\t\t\ttruncation: options?.truncation,\n\t\t\tinclude: options?.include,\n\t\t\ttools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, {\n\t\t\t\tstream: this.streaming,\n\t\t\t\tstrict\n\t\t\t}) : void 0,\n\t\t\ttool_choice: isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => {\n\t\t\t\tconst formatted = formatToOpenAIToolChoice(options?.tool_choice);\n\t\t\t\tif (typeof formatted === \"object\" && \"type\" in formatted) {\n\t\t\t\t\tif (formatted.type === \"function\") return {\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tname: formatted.function.name\n\t\t\t\t\t};\n\t\t\t\t\telse if (formatted.type === \"allowed_tools\") return {\n\t\t\t\t\t\ttype: \"allowed_tools\",\n\t\t\t\t\t\tmode: formatted.allowed_tools.mode,\n\t\t\t\t\t\ttools: formatted.allowed_tools.tools\n\t\t\t\t\t};\n\t\t\t\t\telse if (formatted.type === \"custom\") return {\n\t\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\t\tname: formatted.custom.name\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn void 0;\n\t\t\t})(),\n\t\t\ttext: (() => {\n\t\t\t\tif (options?.text) return options.text;\n\t\t\t\tconst format = this._getResponseFormat(options?.response_format);\n\t\t\t\tif (format?.type === \"json_schema\") {\n\t\t\t\t\tif (format.json_schema.schema != null) return {\n\t\t\t\t\t\tformat: {\n\t\t\t\t\t\t\ttype: \"json_schema\",\n\t\t\t\t\t\t\tschema: format.json_schema.schema,\n\t\t\t\t\t\t\tdescription: format.json_schema.description,\n\t\t\t\t\t\t\tname: format.json_schema.name,\n\t\t\t\t\t\t\tstrict: format.json_schema.strict\n\t\t\t\t\t\t},\n\t\t\t\t\t\tverbosity: options?.verbosity\n\t\t\t\t\t};\n\t\t\t\t\treturn void 0;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tformat,\n\t\t\t\t\tverbosity: options?.verbosity\n\t\t\t\t};\n\t\t\t})(),\n\t\t\tparallel_tool_calls: options?.parallel_tool_calls,\n\t\t\tmax_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens,\n\t\t\tprompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,\n\t\t\t...this.zdrEnabled ? { store: false } : {},\n\t\t\t...this.modelKwargs\n\t\t};\n\t\tconst reasoning = this._getReasoningParams(options);\n\t\tif (reasoning !== void 0) params.reasoning = reasoning;\n\t\treturn params;\n\t}\n\tasync _generate(messages, options) {\n\t\tconst invocationParams = this.invocationParams(options);\n\t\tif (invocationParams.stream) {\n\t\t\tconst stream = this._streamResponseChunks(messages, options);\n\t\t\tlet finalChunk;\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tchunk.message.response_metadata = {\n\t\t\t\t\t...chunk.generationInfo,\n\t\t\t\t\t...chunk.message.response_metadata\n\t\t\t\t};\n\t\t\t\tfinalChunk = finalChunk?.concat(chunk) ?? chunk;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tgenerations: finalChunk ? [finalChunk] : [],\n\t\t\t\tllmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata }\n\t\t\t};\n\t\t} else {\n\t\t\tconst input = this._convertMessagesToResponsesParams(messages);\n\t\t\tconst data = await this.completionWithRetry({\n\t\t\t\tinput,\n\t\t\t\t...invocationParams,\n\t\t\t\tstream: false\n\t\t\t}, {\n\t\t\t\tsignal: options?.signal,\n\t\t\t\t...options?.options\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tgenerations: [{\n\t\t\t\t\ttext: data.output_text,\n\t\t\t\t\tmessage: this._convertResponsesMessageToBaseMessage(data)\n\t\t\t\t}],\n\t\t\t\tllmOutput: {\n\t\t\t\t\tid: data.id,\n\t\t\t\t\testimatedTokenUsage: data.usage ? {\n\t\t\t\t\t\tpromptTokens: data.usage.input_tokens,\n\t\t\t\t\t\tcompletionTokens: data.usage.output_tokens,\n\t\t\t\t\t\ttotalTokens: data.usage.total_tokens\n\t\t\t\t\t} : void 0\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\tasync *_streamResponseChunks(messages, options, runManager) {\n\t\tconst streamIterable = await this.completionWithRetry({\n\t\t\t...this.invocationParams(options),\n\t\t\tinput: this._convertMessagesToResponsesParams(messages),\n\t\t\tstream: true\n\t\t}, options);\n\t\tfor await (const data of streamIterable) {\n\t\t\tconst chunk = this._convertResponsesDeltaToBaseMessageChunk(data);\n\t\t\tif (chunk == null) continue;\n\t\t\tyield chunk;\n\t\t\tawait runManager?.handleLLMNewToken(chunk.text || \"\", {\n\t\t\t\tprompt: options.promptIndex ?? 0,\n\t\t\t\tcompletion: 0\n\t\t\t}, void 0, void 0, void 0, { chunk });\n\t\t}\n\t}\n\tasync completionWithRetry(request, requestOptions) {\n\t\treturn this.caller.call(async () => {\n\t\t\tconst clientOptions = this._getClientOptions(requestOptions);\n\t\t\ttry {\n\t\t\t\tif (request.text?.format?.type === \"json_schema\" && !request.stream) return await this.client.responses.parse(request, clientOptions);\n\t\t\t\treturn await this.client.responses.create(request, clientOptions);\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapOpenAIClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n\t/** @internal */\n\t_convertResponsesMessageToBaseMessage(response) {\n\t\tif (response.error) {\n\t\t\tconst error = new Error(response.error.message);\n\t\t\terror.name = response.error.code;\n\t\t\tthrow error;\n\t\t}\n\t\tlet messageId;\n\t\tconst content = [];\n\t\tconst tool_calls = [];\n\t\tconst invalid_tool_calls = [];\n\t\tconst response_metadata = {\n\t\t\tmodel_provider: \"openai\",\n\t\t\tmodel: response.model,\n\t\t\tcreated_at: response.created_at,\n\t\t\tid: response.id,\n\t\t\tincomplete_details: response.incomplete_details,\n\t\t\tmetadata: response.metadata,\n\t\t\tobject: response.object,\n\t\t\tstatus: response.status,\n\t\t\tuser: response.user,\n\t\t\tservice_tier: response.service_tier,\n\t\t\tmodel_name: response.model\n\t\t};\n\t\tconst additional_kwargs = {};\n\t\tfor (const item of response.output) if (item.type === \"message\") {\n\t\t\tmessageId = item.id;\n\t\t\tcontent.push(...item.content.flatMap((part) => {\n\t\t\t\tif (part.type === \"output_text\") {\n\t\t\t\t\tif (\"parsed\" in part && part.parsed != null) additional_kwargs.parsed = part.parsed;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\tannotations: part.annotations\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (part.type === \"refusal\") {\n\t\t\t\t\tadditional_kwargs.refusal = part.refusal;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn part;\n\t\t\t}));\n\t\t} else if (item.type === \"function_call\") {\n\t\t\tconst fnAdapter = {\n\t\t\t\tfunction: {\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: item.arguments\n\t\t\t\t},\n\t\t\t\tid: item.call_id\n\t\t\t};\n\t\t\ttry {\n\t\t\t\ttool_calls.push(parseToolCall(fnAdapter, { returnId: true }));\n\t\t\t} catch (e) {\n\t\t\t\tlet errMessage;\n\t\t\t\tif (typeof e === \"object\" && e != null && \"message\" in e && typeof e.message === \"string\") errMessage = e.message;\n\t\t\t\tinvalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage));\n\t\t\t}\n\t\t\tadditional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};\n\t\t\tif (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;\n\t\t} else if (item.type === \"reasoning\") additional_kwargs.reasoning = item;\n\t\telse if (item.type === \"custom_tool_call\") {\n\t\t\tconst parsed = parseCustomToolCall(item);\n\t\t\tif (parsed) tool_calls.push(parsed);\n\t\t\telse invalid_tool_calls.push(makeInvalidToolCall(item, \"Malformed custom tool call\"));\n\t\t} else {\n\t\t\tadditional_kwargs.tool_outputs ??= [];\n\t\t\tadditional_kwargs.tool_outputs.push(item);\n\t\t}\n\t\treturn new AIMessage({\n\t\t\tid: messageId,\n\t\t\tcontent,\n\t\t\ttool_calls,\n\t\t\tinvalid_tool_calls,\n\t\t\tusage_metadata: _convertOpenAIResponsesUsageToLangChainUsage(response.usage),\n\t\t\tadditional_kwargs,\n\t\t\tresponse_metadata\n\t\t});\n\t}\n\t/** @internal */\n\t_convertResponsesDeltaToBaseMessageChunk(chunk) {\n\t\tconst content = [];\n\t\tlet generationInfo = {};\n\t\tlet usage_metadata;\n\t\tconst tool_call_chunks = [];\n\t\tconst response_metadata = { model_provider: \"openai\" };\n\t\tconst additional_kwargs = {};\n\t\tlet id;\n\t\tif (chunk.type === \"response.output_text.delta\") content.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: chunk.delta,\n\t\t\tindex: chunk.content_index\n\t\t});\n\t\telse if (chunk.type === \"response.output_text.annotation.added\") content.push({\n\t\t\ttype: \"text\",\n\t\t\ttext: \"\",\n\t\t\tannotations: [chunk.annotation],\n\t\t\tindex: chunk.content_index\n\t\t});\n\t\telse if (chunk.type === \"response.output_item.added\" && chunk.item.type === \"message\") id = chunk.item.id;\n\t\telse if (chunk.type === \"response.output_item.added\" && chunk.item.type === \"function_call\") {\n\t\t\ttool_call_chunks.push({\n\t\t\t\ttype: \"tool_call_chunk\",\n\t\t\t\tname: chunk.item.name,\n\t\t\t\targs: chunk.item.arguments,\n\t\t\t\tid: chunk.item.call_id,\n\t\t\t\tindex: chunk.output_index\n\t\t\t});\n\t\t\tadditional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [chunk.item.call_id]: chunk.item.id };\n\t\t} else if (chunk.type === \"response.output_item.done\" && [\n\t\t\t\"web_search_call\",\n\t\t\t\"file_search_call\",\n\t\t\t\"computer_call\",\n\t\t\t\"code_interpreter_call\",\n\t\t\t\"mcp_call\",\n\t\t\t\"mcp_list_tools\",\n\t\t\t\"mcp_approval_request\",\n\t\t\t\"image_generation_call\",\n\t\t\t\"custom_tool_call\"\n\t\t].includes(chunk.item.type)) additional_kwargs.tool_outputs = [chunk.item];\n\t\telse if (chunk.type === \"response.created\") {\n\t\t\tresponse_metadata.id = chunk.response.id;\n\t\t\tresponse_metadata.model_name = chunk.response.model;\n\t\t\tresponse_metadata.model = chunk.response.model;\n\t\t} else if (chunk.type === \"response.completed\") {\n\t\t\tconst msg = this._convertResponsesMessageToBaseMessage(chunk.response);\n\t\t\tusage_metadata = _convertOpenAIResponsesUsageToLangChainUsage(chunk.response.usage);\n\t\t\tif (chunk.response.text?.format?.type === \"json_schema\") additional_kwargs.parsed ??= JSON.parse(msg.text);\n\t\t\tfor (const [key, value] of Object.entries(chunk.response)) if (key !== \"id\") response_metadata[key] = value;\n\t\t} else if (chunk.type === \"response.function_call_arguments.delta\" || chunk.type === \"response.custom_tool_call_input.delta\") tool_call_chunks.push({\n\t\t\ttype: \"tool_call_chunk\",\n\t\t\targs: chunk.delta,\n\t\t\tindex: chunk.output_index\n\t\t});\n\t\telse if (chunk.type === \"response.web_search_call.completed\" || chunk.type === \"response.file_search_call.completed\") generationInfo = { tool_outputs: {\n\t\t\tid: chunk.item_id,\n\t\t\ttype: chunk.type.replace(\"response.\", \"\").replace(\".completed\", \"\"),\n\t\t\tstatus: \"completed\"\n\t\t} };\n\t\telse if (chunk.type === \"response.refusal.done\") additional_kwargs.refusal = chunk.refusal;\n\t\telse if (chunk.type === \"response.output_item.added\" && \"item\" in chunk && chunk.item.type === \"reasoning\") {\n\t\t\tconst summary = chunk.item.summary ? chunk.item.summary.map((s, index) => ({\n\t\t\t\t...s,\n\t\t\t\tindex\n\t\t\t})) : void 0;\n\t\t\tadditional_kwargs.reasoning = {\n\t\t\t\tid: chunk.item.id,\n\t\t\t\ttype: chunk.item.type,\n\t\t\t\t...summary ? { summary } : {}\n\t\t\t};\n\t\t} else if (chunk.type === \"response.reasoning_summary_part.added\") additional_kwargs.reasoning = {\n\t\t\ttype: \"reasoning\",\n\t\t\tsummary: [{\n\t\t\t\t...chunk.part,\n\t\t\t\tindex: chunk.summary_index\n\t\t\t}]\n\t\t};\n\t\telse if (chunk.type === \"response.reasoning_summary_text.delta\") additional_kwargs.reasoning = {\n\t\t\ttype: \"reasoning\",\n\t\t\tsummary: [{\n\t\t\t\ttext: chunk.delta,\n\t\t\t\ttype: \"summary_text\",\n\t\t\t\tindex: chunk.summary_index\n\t\t\t}]\n\t\t};\n\t\telse if (chunk.type === \"response.image_generation_call.partial_image\") return null;\n\t\telse return null;\n\t\treturn new ChatGenerationChunk({\n\t\t\ttext: content.map((part) => part.text).join(\"\"),\n\t\t\tmessage: new AIMessageChunk({\n\t\t\t\tid,\n\t\t\t\tcontent,\n\t\t\t\ttool_call_chunks,\n\t\t\t\tusage_metadata,\n\t\t\t\tadditional_kwargs,\n\t\t\t\tresponse_metadata\n\t\t\t}),\n\t\t\tgenerationInfo\n\t\t});\n\t}\n\t/** @internal */\n\t_convertMessagesToResponsesParams(messages) {\n\t\treturn messages.flatMap((lcMsg) => {\n\t\t\tconst responseMetadata = lcMsg.response_metadata;\n\t\t\tif (responseMetadata?.output_version === \"v1\") return _convertToResponsesMessageFromV1(lcMsg);\n\t\t\tconst additional_kwargs = lcMsg.additional_kwargs;\n\t\t\tlet role = messageToOpenAIRole(lcMsg);\n\t\t\tif (role === \"system\" && isReasoningModel(this.model)) role = \"developer\";\n\t\t\tif (role === \"function\") throw new Error(\"Function messages are not supported in Responses API\");\n\t\t\tif (role === \"tool\") {\n\t\t\t\tconst toolMessage = lcMsg;\n\t\t\t\tif (additional_kwargs?.type === \"computer_call_output\") {\n\t\t\t\t\tconst output = (() => {\n\t\t\t\t\t\tif (typeof toolMessage.content === \"string\") return {\n\t\t\t\t\t\t\ttype: \"computer_screenshot\",\n\t\t\t\t\t\t\timage_url: toolMessage.content\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (Array.isArray(toolMessage.content)) {\n\t\t\t\t\t\t\tconst oaiScreenshot = toolMessage.content.find((i) => i.type === \"computer_screenshot\");\n\t\t\t\t\t\t\tif (oaiScreenshot) return oaiScreenshot;\n\t\t\t\t\t\t\tconst lcImage = toolMessage.content.find((i) => i.type === \"image_url\");\n\t\t\t\t\t\t\tif (lcImage) return {\n\t\t\t\t\t\t\t\ttype: \"computer_screenshot\",\n\t\t\t\t\t\t\t\timage_url: typeof lcImage.image_url === \"string\" ? lcImage.image_url : lcImage.image_url.url\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error(\"Invalid computer call output\");\n\t\t\t\t\t})();\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"computer_call_output\",\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tcall_id: toolMessage.tool_call_id\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (toolMessage.additional_kwargs?.customTool) return {\n\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\tcall_id: toolMessage.tool_call_id,\n\t\t\t\t\toutput: toolMessage.content\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"function_call_output\",\n\t\t\t\t\tcall_id: toolMessage.tool_call_id,\n\t\t\t\t\tid: toolMessage.id?.startsWith(\"fc_\") ? toolMessage.id : void 0,\n\t\t\t\t\toutput: typeof toolMessage.content !== \"string\" ? JSON.stringify(toolMessage.content) : toolMessage.content\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (role === \"assistant\") {\n\t\t\t\tif (!this.zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => \"type\" in item)) return responseMetadata?.output;\n\t\t\t\tconst input = [];\n\t\t\t\tif (additional_kwargs?.reasoning && !this.zdrEnabled) {\n\t\t\t\t\tconst reasoningItem = this._convertReasoningSummary(additional_kwargs.reasoning);\n\t\t\t\t\tinput.push(reasoningItem);\n\t\t\t\t}\n\t\t\t\tlet { content } = lcMsg;\n\t\t\t\tif (additional_kwargs?.refusal) {\n\t\t\t\t\tif (typeof content === \"string\") content = [{\n\t\t\t\t\t\ttype: \"output_text\",\n\t\t\t\t\t\ttext: content,\n\t\t\t\t\t\tannotations: []\n\t\t\t\t\t}];\n\t\t\t\t\tcontent = [...content, {\n\t\t\t\t\t\ttype: \"refusal\",\n\t\t\t\t\t\trefusal: additional_kwargs.refusal\n\t\t\t\t\t}];\n\t\t\t\t}\n\t\t\t\tif (typeof content === \"string\" || content.length > 0) input.push({\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t...lcMsg.id && !this.zdrEnabled && lcMsg.id.startsWith(\"msg_\") ? { id: lcMsg.id } : {},\n\t\t\t\t\tcontent: iife(() => {\n\t\t\t\t\t\tif (typeof content === \"string\") return content;\n\t\t\t\t\t\treturn content.flatMap((item) => {\n\t\t\t\t\t\t\tif (item.type === \"text\") return {\n\t\t\t\t\t\t\t\ttype: \"output_text\",\n\t\t\t\t\t\t\t\ttext: item.text,\n\t\t\t\t\t\t\t\tannotations: item.annotations ?? []\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (item.type === \"output_text\" || item.type === \"refusal\") return item;\n\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t});\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\tconst functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];\n\t\t\t\tif (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => {\n\t\t\t\t\tif (isCustomToolCall(toolCall)) return {\n\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\tid: toolCall.call_id,\n\t\t\t\t\t\tcall_id: toolCall.id ?? \"\",\n\t\t\t\t\t\tinput: toolCall.args.input,\n\t\t\t\t\t\tname: toolCall.name\n\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\targuments: JSON.stringify(toolCall.args),\n\t\t\t\t\t\tcall_id: toolCall.id,\n\t\t\t\t\t\t...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}\n\t\t\t\t\t};\n\t\t\t\t}));\n\t\t\t\telse if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({\n\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\tname: toolCall.function.name,\n\t\t\t\t\tcall_id: toolCall.id,\n\t\t\t\t\targuments: toolCall.function.arguments,\n\t\t\t\t\t...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}\n\t\t\t\t})));\n\t\t\t\tconst toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs;\n\t\t\t\tconst fallthroughCallTypes = [\n\t\t\t\t\t\"computer_call\",\n\t\t\t\t\t\"mcp_call\",\n\t\t\t\t\t\"code_interpreter_call\",\n\t\t\t\t\t\"image_generation_call\"\n\t\t\t\t];\n\t\t\t\tif (toolOutputs != null) {\n\t\t\t\t\tconst castToolOutputs = toolOutputs;\n\t\t\t\t\tconst fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));\n\t\t\t\t\tif (fallthroughCalls.length > 0) input.push(...fallthroughCalls);\n\t\t\t\t}\n\t\t\t\treturn input;\n\t\t\t}\n\t\t\tif (role === \"user\" || role === \"system\" || role === \"developer\") {\n\t\t\t\tif (typeof lcMsg.content === \"string\") return {\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\trole,\n\t\t\t\t\tcontent: lcMsg.content\n\t\t\t\t};\n\t\t\t\tconst messages$1 = [];\n\t\t\t\tconst content = lcMsg.content.flatMap((item) => {\n\t\t\t\t\tif (item.type === \"mcp_approval_response\") messages$1.push({\n\t\t\t\t\t\ttype: \"mcp_approval_response\",\n\t\t\t\t\t\tapproval_request_id: item.approval_request_id,\n\t\t\t\t\t\tapprove: item.approve\n\t\t\t\t\t});\n\t\t\t\t\tif (isDataContentBlock(item)) return convertToProviderContentBlock(item, completionsApiContentBlockConverter);\n\t\t\t\t\tif (item.type === \"text\") return {\n\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\ttext: item.text\n\t\t\t\t\t};\n\t\t\t\t\tif (item.type === \"image_url\") {\n\t\t\t\t\t\tconst imageUrl = iife(() => {\n\t\t\t\t\t\t\tif (typeof item.image_url === \"string\") return item.image_url;\n\t\t\t\t\t\t\telse if (typeof item.image_url === \"object\" && item.image_url !== null && \"url\" in item.image_url) return item.image_url.url;\n\t\t\t\t\t\t\treturn void 0;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst detail = iife(() => {\n\t\t\t\t\t\t\tif (typeof item.image_url === \"string\") return \"auto\";\n\t\t\t\t\t\t\telse if (typeof item.image_url === \"object\" && item.image_url !== null && \"detail\" in item.image_url) return item.image_url.detail;\n\t\t\t\t\t\t\treturn void 0;\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\timage_url: imageUrl,\n\t\t\t\t\t\t\tdetail\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (item.type === \"input_text\" || item.type === \"input_image\" || item.type === \"input_file\") return item;\n\t\t\t\t\treturn [];\n\t\t\t\t});\n\t\t\t\tif (content.length > 0) messages$1.push({\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\trole,\n\t\t\t\t\tcontent\n\t\t\t\t});\n\t\t\t\treturn messages$1;\n\t\t\t}\n\t\t\tconsole.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);\n\t\t\treturn [];\n\t\t});\n\t}\n\t/** @internal */\n\t_convertReasoningSummary(reasoning) {\n\t\tconst summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => {\n\t\t\tconst last = acc[acc.length - 1];\n\t\t\tif (last.index === curr.index) last.text += curr.text;\n\t\t\telse acc.push(curr);\n\t\t\treturn acc;\n\t\t}, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== \"index\")));\n\t\treturn {\n\t\t\t...reasoning,\n\t\t\tsummary\n\t\t};\n\t}\n\t/** @internal */\n\t_reduceChatOpenAITools(tools, fields) {\n\t\tconst reducedTools = [];\n\t\tfor (const tool of tools) if (isBuiltInTool(tool)) {\n\t\t\tif (tool.type === \"image_generation\" && fields?.stream) tool.partial_images = 1;\n\t\t\treducedTools.push(tool);\n\t\t} else if (isCustomTool(tool)) {\n\t\t\tconst customToolData = tool.metadata.customTool;\n\t\t\treducedTools.push({\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: customToolData.name,\n\t\t\t\tdescription: customToolData.description,\n\t\t\t\tformat: customToolData.format\n\t\t\t});\n\t\t} else if (isOpenAITool(tool)) reducedTools.push({\n\t\t\ttype: \"function\",\n\t\t\tname: tool.function.name,\n\t\t\tparameters: tool.function.parameters,\n\t\t\tdescription: tool.function.description,\n\t\t\tstrict: fields?.strict ?? null\n\t\t});\n\t\telse if (isOpenAICustomTool(tool)) reducedTools.push(convertCompletionsCustomTool(tool));\n\t\treturn reducedTools;\n\t}\n};\n\n//#endregion\nexport { ChatOpenAIResponses };\n//# sourceMappingURL=responses.js.map","import { isReasoningModel } from \"../utils/misc.js\";\nimport { formatToOpenAIToolChoice } from \"../utils/tools.js\";\nimport { handleMultiModalOutput } from \"../utils/output.js\";\nimport { BaseChatOpenAI } from \"./base.js\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport { _convertMessagesToOpenAIParams } from \"../utils/message_inputs.js\";\nimport { makeInvalidToolCall, parseToolCall } from \"@langchain/core/output_parsers/openai_tools\";\nimport { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessageChunk, HumanMessageChunk, SystemMessageChunk, ToolMessageChunk, isAIMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk } from \"@langchain/core/outputs\";\n\n//#region src/chat_models/completions.ts\n/**\n* OpenAI Completions API implementation.\n* @internal\n*/\nvar ChatOpenAICompletions = class extends BaseChatOpenAI {\n\t/** @internal */\n\tinvocationParams(options, extra) {\n\t\tlet strict;\n\t\tif (options?.strict !== void 0) strict = options.strict;\n\t\telse if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;\n\t\tlet streamOptionsConfig = {};\n\t\tif (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options };\n\t\telse if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } };\n\t\tconst params = {\n\t\t\tmodel: this.model,\n\t\t\ttemperature: this.temperature,\n\t\t\ttop_p: this.topP,\n\t\t\tfrequency_penalty: this.frequencyPenalty,\n\t\t\tpresence_penalty: this.presencePenalty,\n\t\t\tlogprobs: this.logprobs,\n\t\t\ttop_logprobs: this.topLogprobs,\n\t\t\tn: this.n,\n\t\t\tlogit_bias: this.logitBias,\n\t\t\tstop: options?.stop ?? this.stopSequences,\n\t\t\tuser: this.user,\n\t\t\tstream: this.streaming,\n\t\t\tfunctions: options?.functions,\n\t\t\tfunction_call: options?.function_call,\n\t\t\ttools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0,\n\t\t\ttool_choice: formatToOpenAIToolChoice(options?.tool_choice),\n\t\t\tresponse_format: this._getResponseFormat(options?.response_format),\n\t\t\tseed: options?.seed,\n\t\t\t...streamOptionsConfig,\n\t\t\tparallel_tool_calls: options?.parallel_tool_calls,\n\t\t\t...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {},\n\t\t\t...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {},\n\t\t\t...this.modelKwargs,\n\t\t\tprompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,\n\t\t\tverbosity: options?.verbosity ?? this.verbosity\n\t\t};\n\t\tif (options?.prediction !== void 0) params.prediction = options.prediction;\n\t\tif (this.service_tier !== void 0) params.service_tier = this.service_tier;\n\t\tif (options?.service_tier !== void 0) params.service_tier = options.service_tier;\n\t\tconst reasoning = this._getReasoningParams(options);\n\t\tif (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort;\n\t\tif (isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;\n\t\telse params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;\n\t\treturn params;\n\t}\n\tasync _generate(messages, options, runManager) {\n\t\tconst usageMetadata = {};\n\t\tconst params = this.invocationParams(options);\n\t\tconst messagesMapped = _convertMessagesToOpenAIParams(messages, this.model);\n\t\tif (params.stream) {\n\t\t\tconst stream = this._streamResponseChunks(messages, options, runManager);\n\t\t\tconst finalChunks = {};\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tchunk.message.response_metadata = {\n\t\t\t\t\t...chunk.generationInfo,\n\t\t\t\t\t...chunk.message.response_metadata\n\t\t\t\t};\n\t\t\t\tconst index = chunk.generationInfo?.completion ?? 0;\n\t\t\t\tif (finalChunks[index] === void 0) finalChunks[index] = chunk;\n\t\t\t\telse finalChunks[index] = finalChunks[index].concat(chunk);\n\t\t\t}\n\t\t\tconst generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value);\n\t\t\tconst { functions, function_call } = this.invocationParams(options);\n\t\t\tconst promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call);\n\t\t\tconst completionTokenUsage = await this._getNumTokensFromGenerations(generations);\n\t\t\tusageMetadata.input_tokens = promptTokenUsage;\n\t\t\tusageMetadata.output_tokens = completionTokenUsage;\n\t\t\tusageMetadata.total_tokens = promptTokenUsage + completionTokenUsage;\n\t\t\treturn {\n\t\t\t\tgenerations,\n\t\t\t\tllmOutput: { estimatedTokenUsage: {\n\t\t\t\t\tpromptTokens: usageMetadata.input_tokens,\n\t\t\t\t\tcompletionTokens: usageMetadata.output_tokens,\n\t\t\t\t\ttotalTokens: usageMetadata.total_tokens\n\t\t\t\t} }\n\t\t\t};\n\t\t} else {\n\t\t\tconst data = await this.completionWithRetry({\n\t\t\t\t...params,\n\t\t\t\tstream: false,\n\t\t\t\tmessages: messagesMapped\n\t\t\t}, {\n\t\t\t\tsignal: options?.signal,\n\t\t\t\t...options?.options\n\t\t\t});\n\t\t\tconst { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {};\n\t\t\tif (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens;\n\t\t\tif (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens;\n\t\t\tif (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens;\n\t\t\tif (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = {\n\t\t\t\t...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens },\n\t\t\t\t...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens }\n\t\t\t};\n\t\t\tif (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = {\n\t\t\t\t...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens },\n\t\t\t\t...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens }\n\t\t\t};\n\t\t\tconst generations = [];\n\t\t\tfor (const part of data?.choices ?? []) {\n\t\t\t\tconst text = part.message?.content ?? \"\";\n\t\t\t\tconst generation = {\n\t\t\t\t\ttext,\n\t\t\t\t\tmessage: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: \"assistant\" }, data)\n\t\t\t\t};\n\t\t\t\tgeneration.generationInfo = {\n\t\t\t\t\t...part.finish_reason ? { finish_reason: part.finish_reason } : {},\n\t\t\t\t\t...part.logprobs ? { logprobs: part.logprobs } : {}\n\t\t\t\t};\n\t\t\t\tif (isAIMessage(generation.message)) generation.message.usage_metadata = usageMetadata;\n\t\t\t\tgeneration.message = new AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith(\"lc_\"))));\n\t\t\t\tgenerations.push(generation);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tgenerations,\n\t\t\t\tllmOutput: { tokenUsage: {\n\t\t\t\t\tpromptTokens: usageMetadata.input_tokens,\n\t\t\t\t\tcompletionTokens: usageMetadata.output_tokens,\n\t\t\t\t\ttotalTokens: usageMetadata.total_tokens\n\t\t\t\t} }\n\t\t\t};\n\t\t}\n\t}\n\tasync *_streamResponseChunks(messages, options, runManager) {\n\t\tconst messagesMapped = _convertMessagesToOpenAIParams(messages, this.model);\n\t\tconst params = {\n\t\t\t...this.invocationParams(options, { streaming: true }),\n\t\t\tmessages: messagesMapped,\n\t\t\tstream: true\n\t\t};\n\t\tlet defaultRole;\n\t\tconst streamIterable = await this.completionWithRetry(params, options);\n\t\tlet usage;\n\t\tfor await (const data of streamIterable) {\n\t\t\tconst choice = data?.choices?.[0];\n\t\t\tif (data.usage) usage = data.usage;\n\t\t\tif (!choice) continue;\n\t\t\tconst { delta } = choice;\n\t\t\tif (!delta) continue;\n\t\t\tconst chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole);\n\t\t\tdefaultRole = delta.role ?? defaultRole;\n\t\t\tconst newTokenIndices = {\n\t\t\t\tprompt: options.promptIndex ?? 0,\n\t\t\t\tcompletion: choice.index ?? 0\n\t\t\t};\n\t\t\tif (typeof chunk.content !== \"string\") {\n\t\t\t\tconsole.log(\"[WARNING]: Received non-string content from OpenAI. This is currently not supported.\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst generationInfo = { ...newTokenIndices };\n\t\t\tif (choice.finish_reason != null) {\n\t\t\t\tgenerationInfo.finish_reason = choice.finish_reason;\n\t\t\t\tgenerationInfo.system_fingerprint = data.system_fingerprint;\n\t\t\t\tgenerationInfo.model_name = data.model;\n\t\t\t\tgenerationInfo.service_tier = data.service_tier;\n\t\t\t}\n\t\t\tif (this.logprobs) generationInfo.logprobs = choice.logprobs;\n\t\t\tconst generationChunk = new ChatGenerationChunk({\n\t\t\t\tmessage: chunk,\n\t\t\t\ttext: chunk.content,\n\t\t\t\tgenerationInfo\n\t\t\t});\n\t\t\tyield generationChunk;\n\t\t\tawait runManager?.handleLLMNewToken(generationChunk.text ?? \"\", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk });\n\t\t}\n\t\tif (usage) {\n\t\t\tconst inputTokenDetails = {\n\t\t\t\t...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens },\n\t\t\t\t...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens }\n\t\t\t};\n\t\t\tconst outputTokenDetails = {\n\t\t\t\t...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens },\n\t\t\t\t...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens }\n\t\t\t};\n\t\t\tconst generationChunk = new ChatGenerationChunk({\n\t\t\t\tmessage: new AIMessageChunk({\n\t\t\t\t\tcontent: \"\",\n\t\t\t\t\tresponse_metadata: { usage: { ...usage } },\n\t\t\t\t\tusage_metadata: {\n\t\t\t\t\t\tinput_tokens: usage.prompt_tokens,\n\t\t\t\t\t\toutput_tokens: usage.completion_tokens,\n\t\t\t\t\t\ttotal_tokens: usage.total_tokens,\n\t\t\t\t\t\t...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails },\n\t\t\t\t\t\t...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails }\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\ttext: \"\"\n\t\t\t});\n\t\t\tyield generationChunk;\n\t\t}\n\t\tif (options.signal?.aborted) throw new Error(\"AbortError\");\n\t}\n\tasync completionWithRetry(request, requestOptions) {\n\t\tconst clientOptions = this._getClientOptions(requestOptions);\n\t\tconst isParseableFormat = request.response_format && request.response_format.type === \"json_schema\";\n\t\treturn this.caller.call(async () => {\n\t\t\ttry {\n\t\t\t\tif (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions);\n\t\t\t\telse return await this.client.chat.completions.create(request, clientOptions);\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapOpenAIClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n\t/** @internal */\n\t_convertCompletionsMessageToBaseMessage(message, rawResponse) {\n\t\tconst rawToolCalls = message.tool_calls;\n\t\tswitch (message.role) {\n\t\t\tcase \"assistant\": {\n\t\t\t\tconst toolCalls = [];\n\t\t\t\tconst invalidToolCalls = [];\n\t\t\t\tfor (const rawToolCall of rawToolCalls ?? []) try {\n\t\t\t\t\ttoolCalls.push(parseToolCall(rawToolCall, { returnId: true }));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tinvalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message));\n\t\t\t\t}\n\t\t\t\tconst additional_kwargs = {\n\t\t\t\t\tfunction_call: message.function_call,\n\t\t\t\t\ttool_calls: rawToolCalls\n\t\t\t\t};\n\t\t\t\tif (this.__includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse;\n\t\t\t\tconst response_metadata = {\n\t\t\t\t\tmodel_provider: \"openai\",\n\t\t\t\t\tmodel_name: rawResponse.model,\n\t\t\t\t\t...rawResponse.system_fingerprint ? {\n\t\t\t\t\t\tusage: { ...rawResponse.usage },\n\t\t\t\t\t\tsystem_fingerprint: rawResponse.system_fingerprint\n\t\t\t\t\t} : {}\n\t\t\t\t};\n\t\t\t\tif (message.audio) additional_kwargs.audio = message.audio;\n\t\t\t\tconst content = handleMultiModalOutput(message.content || \"\", rawResponse.choices?.[0]?.message);\n\t\t\t\treturn new AIMessage({\n\t\t\t\t\tcontent,\n\t\t\t\t\ttool_calls: toolCalls,\n\t\t\t\t\tinvalid_tool_calls: invalidToolCalls,\n\t\t\t\t\tadditional_kwargs,\n\t\t\t\t\tresponse_metadata,\n\t\t\t\t\tid: rawResponse.id\n\t\t\t\t});\n\t\t\t}\n\t\t\tdefault: return new ChatMessage(message.content || \"\", message.role ?? \"unknown\");\n\t\t}\n\t}\n\t/** @internal */\n\t_convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) {\n\t\tconst role = delta.role ?? defaultRole;\n\t\tconst content = delta.content ?? \"\";\n\t\tlet additional_kwargs;\n\t\tif (delta.function_call) additional_kwargs = { function_call: delta.function_call };\n\t\telse if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls };\n\t\telse additional_kwargs = {};\n\t\tif (this.__includeRawResponse) additional_kwargs.__raw_response = rawResponse;\n\t\tif (delta.audio) additional_kwargs.audio = {\n\t\t\t...delta.audio,\n\t\t\tindex: rawResponse.choices[0].index\n\t\t};\n\t\tconst response_metadata = {\n\t\t\tmodel_provider: \"openai\",\n\t\t\tusage: { ...rawResponse.usage }\n\t\t};\n\t\tif (role === \"user\") return new HumanMessageChunk({\n\t\t\tcontent,\n\t\t\tresponse_metadata\n\t\t});\n\t\telse if (role === \"assistant\") {\n\t\t\tconst toolCallChunks = [];\n\t\t\tif (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({\n\t\t\t\tname: rawToolCall.function?.name,\n\t\t\t\targs: rawToolCall.function?.arguments,\n\t\t\t\tid: rawToolCall.id,\n\t\t\t\tindex: rawToolCall.index,\n\t\t\t\ttype: \"tool_call_chunk\"\n\t\t\t});\n\t\t\treturn new AIMessageChunk({\n\t\t\t\tcontent,\n\t\t\t\ttool_call_chunks: toolCallChunks,\n\t\t\t\tadditional_kwargs,\n\t\t\t\tid: rawResponse.id,\n\t\t\t\tresponse_metadata\n\t\t\t});\n\t\t} else if (role === \"system\") return new SystemMessageChunk({\n\t\t\tcontent,\n\t\t\tresponse_metadata\n\t\t});\n\t\telse if (role === \"developer\") return new SystemMessageChunk({\n\t\t\tcontent,\n\t\t\tresponse_metadata,\n\t\t\tadditional_kwargs: { __openai_role__: \"developer\" }\n\t\t});\n\t\telse if (role === \"function\") return new FunctionMessageChunk({\n\t\t\tcontent,\n\t\t\tadditional_kwargs,\n\t\t\tname: delta.name,\n\t\t\tresponse_metadata\n\t\t});\n\t\telse if (role === \"tool\") return new ToolMessageChunk({\n\t\t\tcontent,\n\t\t\tadditional_kwargs,\n\t\t\ttool_call_id: delta.tool_call_id,\n\t\t\tresponse_metadata\n\t\t});\n\t\telse return new ChatMessageChunk({\n\t\t\tcontent,\n\t\t\trole,\n\t\t\tresponse_metadata\n\t\t});\n\t}\n};\n\n//#endregion\nexport { ChatOpenAICompletions };\n//# sourceMappingURL=completions.js.map","import { isBuiltInTool, isCustomTool, isOpenAICustomTool } from \"../utils/tools.js\";\nimport { BaseChatOpenAI } from \"./base.js\";\nimport { ChatOpenAIResponses } from \"./responses.js\";\nimport { ChatOpenAICompletions } from \"./completions.js\";\n\n//#region src/chat_models/index.ts\n/**\n* OpenAI chat model integration.\n*\n* To use with Azure, import the `AzureChatOpenAI` class.\n*\n* Setup:\n* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.\n*\n* ```bash\n* npm install @langchain/openai\n* export OPENAI_API_KEY=\"your-api-key\"\n* ```\n*\n* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)\n*\n* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)\n*\n* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n*\n* ```typescript\n* // When calling `.withConfig`, call options should be passed via the first argument\n* const llmWithArgsBound = llm.withConfig({\n* stop: [\"\\n\"],\n* tools: [...],\n* });\n*\n* // When calling `.bindTools`, call options should be passed via the second argument\n* const llmWithTools = llm.bindTools(\n* [...],\n* {\n* tool_choice: \"auto\",\n* }\n* );\n* ```\n*\n* ## Examples\n*\n*
\n* Instantiate\n*\n* ```typescript\n* import { ChatOpenAI } from '@langchain/openai';\n*\n* const llm = new ChatOpenAI({\n* model: \"gpt-4o-mini\",\n* temperature: 0,\n* maxTokens: undefined,\n* timeout: undefined,\n* maxRetries: 2,\n* // apiKey: \"...\",\n* // configuration: {\n* // baseURL: \"...\",\n* // }\n* // organization: \"...\",\n* // other params...\n* });\n* ```\n*
\n*\n*
\n*\n*
\n* Invoking\n*\n* ```typescript\n* const input = `Translate \"I love programming\" into French.`;\n*\n* // Models also accept a list of chat messages or a formatted prompt\n* const result = await llm.invoke(input);\n* console.log(result);\n* ```\n*\n* ```txt\n* AIMessage {\n* \"id\": \"chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz\",\n* \"content\": \"J'adore la programmation.\",\n* \"response_metadata\": {\n* \"tokenUsage\": {\n* \"completionTokens\": 5,\n* \"promptTokens\": 28,\n* \"totalTokens\": 33\n* },\n* \"finish_reason\": \"stop\",\n* \"system_fingerprint\": \"fp_3aa7262c27\"\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 28,\n* \"output_tokens\": 5,\n* \"total_tokens\": 33\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Streaming Chunks\n*\n* ```typescript\n* for await (const chunk of await llm.stream(input)) {\n* console.log(chunk);\n* }\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"id\": \"chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs\",\n* \"content\": \"\"\n* }\n* AIMessageChunk {\n* \"content\": \"J\"\n* }\n* AIMessageChunk {\n* \"content\": \"'adore\"\n* }\n* AIMessageChunk {\n* \"content\": \" la\"\n* }\n* AIMessageChunk {\n* \"content\": \" programmation\",,\n* }\n* AIMessageChunk {\n* \"content\": \".\",,\n* }\n* AIMessageChunk {\n* \"content\": \"\",\n* \"response_metadata\": {\n* \"finish_reason\": \"stop\",\n* \"system_fingerprint\": \"fp_c9aa9c0491\"\n* },\n* }\n* AIMessageChunk {\n* \"content\": \"\",\n* \"usage_metadata\": {\n* \"input_tokens\": 28,\n* \"output_tokens\": 5,\n* \"total_tokens\": 33\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Aggregate Streamed Chunks\n*\n* ```typescript\n* import { AIMessageChunk } from '@langchain/core/messages';\n* import { concat } from '@langchain/core/utils/stream';\n*\n* const stream = await llm.stream(input);\n* let full: AIMessageChunk | undefined;\n* for await (const chunk of stream) {\n* full = !full ? chunk : concat(full, chunk);\n* }\n* console.log(full);\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"id\": \"chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu\",\n* \"content\": \"J'adore la programmation.\",\n* \"response_metadata\": {\n* \"prompt\": 0,\n* \"completion\": 0,\n* \"finish_reason\": \"stop\",\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 28,\n* \"output_tokens\": 5,\n* \"total_tokens\": 33\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Bind tools\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const GetWeather = {\n* name: \"GetWeather\",\n* description: \"Get the current weather in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const GetPopulation = {\n* name: \"GetPopulation\",\n* description: \"Get the current population in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const llmWithTools = llm.bindTools(\n* [GetWeather, GetPopulation],\n* {\n* // strict: true // enforce tool args schema is respected\n* }\n* );\n* const aiMsg = await llmWithTools.invoke(\n* \"Which city is hotter today and which is bigger: LA or NY?\"\n* );\n* console.log(aiMsg.tool_calls);\n* ```\n*\n* ```txt\n* [\n* {\n* name: 'GetWeather',\n* args: { location: 'Los Angeles, CA' },\n* type: 'tool_call',\n* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'\n* },\n* {\n* name: 'GetWeather',\n* args: { location: 'New York, NY' },\n* type: 'tool_call',\n* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'Los Angeles, CA' },\n* type: 'tool_call',\n* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'New York, NY' },\n* type: 'tool_call',\n* id: 'call_s9KQB1UWj45LLGaEnjz0179q'\n* }\n* ]\n* ```\n*
\n*\n*
\n*\n*
\n* Structured Output\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const Joke = z.object({\n* setup: z.string().describe(\"The setup of the joke\"),\n* punchline: z.string().describe(\"The punchline to the joke\"),\n* rating: z.number().nullable().describe(\"How funny the joke is, from 1 to 10\")\n* }).describe('Joke to tell user.');\n*\n* const structuredLlm = llm.withStructuredOutput(Joke, {\n* name: \"Joke\",\n* strict: true, // Optionally enable OpenAI structured outputs\n* });\n* const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n* console.log(jokeResult);\n* ```\n*\n* ```txt\n* {\n* setup: 'Why was the cat sitting on the computer?',\n* punchline: 'Because it wanted to keep an eye on the mouse!',\n* rating: 7\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* JSON Object Response Format\n*\n* ```typescript\n* const jsonLlm = llm.withConfig({ response_format: { type: \"json_object\" } });\n* const jsonLlmAiMsg = await jsonLlm.invoke(\n* \"Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]\"\n* );\n* console.log(jsonLlmAiMsg.content);\n* ```\n*\n* ```txt\n* {\n* \"randomInts\": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Multimodal\n*\n* ```typescript\n* import { HumanMessage } from '@langchain/core/messages';\n*\n* const imageUrl = \"https://example.com/image.jpg\";\n* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n* const base64Image = Buffer.from(imageData).toString('base64');\n*\n* const message = new HumanMessage({\n* content: [\n* { type: \"text\", text: \"describe the weather in this image\" },\n* {\n* type: \"image_url\",\n* image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n* },\n* ]\n* });\n*\n* const imageDescriptionAiMsg = await llm.invoke([message]);\n* console.log(imageDescriptionAiMsg.content);\n* ```\n*\n* ```txt\n* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.\n* ```\n*
\n*\n*
\n*\n*
\n* Usage Metadata\n*\n* ```typescript\n* const aiMsgForMetadata = await llm.invoke(input);\n* console.log(aiMsgForMetadata.usage_metadata);\n* ```\n*\n* ```txt\n* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }\n* ```\n*
\n*\n*
\n*\n*
\n* Logprobs\n*\n* ```typescript\n* const logprobsLlm = new ChatOpenAI({ model: \"gpt-4o-mini\", logprobs: true });\n* const aiMsgForLogprobs = await logprobsLlm.invoke(input);\n* console.log(aiMsgForLogprobs.response_metadata.logprobs);\n* ```\n*\n* ```txt\n* {\n* content: [\n* {\n* token: 'J',\n* logprob: -0.000050616763,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* {\n* token: \"'\",\n* logprob: -0.01868736,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* {\n* token: 'ad',\n* logprob: -0.0000030545007,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },\n* {\n* token: ' la',\n* logprob: -0.515404,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* {\n* token: ' programm',\n* logprob: -0.0000118755715,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },\n* {\n* token: '.',\n* logprob: -0.0000037697225,\n* bytes: [Array],\n* top_logprobs: []\n* }\n* ],\n* refusal: null\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Response Metadata\n*\n* ```typescript\n* const aiMsgForResponseMetadata = await llm.invoke(input);\n* console.log(aiMsgForResponseMetadata.response_metadata);\n* ```\n*\n* ```txt\n* {\n* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },\n* finish_reason: 'stop',\n* system_fingerprint: 'fp_3aa7262c27'\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* JSON Schema Structured Output\n*\n* ```typescript\n* const llmForJsonSchema = new ChatOpenAI({\n* model: \"gpt-4o-2024-08-06\",\n* }).withStructuredOutput(\n* z.object({\n* command: z.string().describe(\"The command to execute\"),\n* expectedOutput: z.string().describe(\"The expected output of the command\"),\n* options: z\n* .array(z.string())\n* .describe(\"The options you can pass to the command\"),\n* }),\n* {\n* method: \"jsonSchema\",\n* strict: true, // Optional when using the `jsonSchema` method\n* }\n* );\n*\n* const jsonSchemaRes = await llmForJsonSchema.invoke(\n* \"What is the command to list files in a directory?\"\n* );\n* console.log(jsonSchemaRes);\n* ```\n*\n* ```txt\n* {\n* command: 'ls',\n* expectedOutput: 'A list of files and subdirectories within the specified directory.',\n* options: [\n* '-a: include directory entries whose names begin with a dot (.).',\n* '-l: use a long listing format.',\n* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',\n* '-t: sort by time, newest first.',\n* '-r: reverse order while sorting.',\n* '-S: sort by file size, largest first.',\n* '-R: list subdirectories recursively.'\n* ]\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Audio Outputs\n*\n* ```typescript\n* import { ChatOpenAI } from \"@langchain/openai\";\n*\n* const modelWithAudioOutput = new ChatOpenAI({\n* model: \"gpt-4o-audio-preview\",\n* // You may also pass these fields to `.withConfig` as a call argument.\n* modalities: [\"text\", \"audio\"], // Specifies that the model should output audio.\n* audio: {\n* voice: \"alloy\",\n* format: \"wav\",\n* },\n* });\n*\n* const audioOutputResult = await modelWithAudioOutput.invoke(\"Tell me a joke about cats.\");\n* const castMessageContent = audioOutputResult.content[0] as Record;\n*\n* console.log({\n* ...castMessageContent,\n* data: castMessageContent.data.slice(0, 100) // Sliced for brevity\n* })\n* ```\n*\n* ```txt\n* {\n* id: 'audio_67117718c6008190a3afad3e3054b9b6',\n* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',\n* expires_at: 1729201448,\n* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Audio Outputs\n*\n* ```typescript\n* import { ChatOpenAI } from \"@langchain/openai\";\n*\n* const modelWithAudioOutput = new ChatOpenAI({\n* model: \"gpt-4o-audio-preview\",\n* // You may also pass these fields to `.withConfig` as a call argument.\n* modalities: [\"text\", \"audio\"], // Specifies that the model should output audio.\n* audio: {\n* voice: \"alloy\",\n* format: \"wav\",\n* },\n* });\n*\n* const audioOutputResult = await modelWithAudioOutput.invoke(\"Tell me a joke about cats.\");\n* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record;\n*\n* console.log({\n* ...castAudioContent,\n* data: castAudioContent.data.slice(0, 100) // Sliced for brevity\n* })\n* ```\n*\n* ```txt\n* {\n* id: 'audio_67117718c6008190a3afad3e3054b9b6',\n* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',\n* expires_at: 1729201448,\n* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'\n* }\n* ```\n*
\n*\n*
\n*/\nvar ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI {\n\t/**\n\t* Whether to use the responses API for all requests. If `false` the responses API will be used\n\t* only when required in order to fulfill the request.\n\t*/\n\tuseResponsesApi = false;\n\tresponses;\n\tcompletions;\n\tget lc_serializable_keys() {\n\t\treturn [...super.lc_serializable_keys, \"useResponsesApi\"];\n\t}\n\tget callKeys() {\n\t\treturn [...super.callKeys, \"useResponsesApi\"];\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.fields = fields;\n\t\tthis.useResponsesApi = fields?.useResponsesApi ?? false;\n\t\tthis.responses = fields?.responses ?? new ChatOpenAIResponses(fields);\n\t\tthis.completions = fields?.completions ?? new ChatOpenAICompletions(fields);\n\t}\n\t_useResponsesApi(options) {\n\t\tconst usesBuiltInTools = options?.tools?.some(isBuiltInTool);\n\t\tconst hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null;\n\t\tconst hasCustomTools = options?.tools?.some(isOpenAICustomTool) || options?.tools?.some(isCustomTool);\n\t\treturn this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools;\n\t}\n\tgetLsParams(options) {\n\t\tconst optionsWithDefaults = this._combineCallOptions(options);\n\t\tif (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults);\n\t\treturn this.completions.getLsParams(optionsWithDefaults);\n\t}\n\tinvocationParams(options) {\n\t\tconst optionsWithDefaults = this._combineCallOptions(options);\n\t\tif (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults);\n\t\treturn this.completions.invocationParams(optionsWithDefaults);\n\t}\n\t/** @ignore */\n\tasync _generate(messages, options, runManager) {\n\t\tif (this._useResponsesApi(options)) return this.responses._generate(messages, options);\n\t\treturn this.completions._generate(messages, options, runManager);\n\t}\n\tasync *_streamResponseChunks(messages, options, runManager) {\n\t\tif (this._useResponsesApi(options)) {\n\t\t\tyield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager);\n\t\t\treturn;\n\t\t}\n\t\tyield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager);\n\t}\n\twithConfig(config) {\n\t\tconst newModel = new ChatOpenAI(this.fields);\n\t\tnewModel.defaultOptions = {\n\t\t\t...this.defaultOptions,\n\t\t\t...config\n\t\t};\n\t\treturn newModel;\n\t}\n};\n\n//#endregion\nexport { ChatOpenAI };\n//# sourceMappingURL=index.js.map","import { getEndpoint, normalizeHeaders } from \"../../utils/azure.js\";\nimport { AzureOpenAI } from \"openai\";\nimport { getEnv, getEnvironmentVariable } from \"@langchain/core/utils/env\";\n\n//#region src/azure/chat_models/common.ts\nconst AZURE_ALIASES = {\n\topenAIApiKey: \"openai_api_key\",\n\topenAIApiVersion: \"openai_api_version\",\n\topenAIBasePath: \"openai_api_base\",\n\tdeploymentName: \"deployment_name\",\n\tazureOpenAIEndpoint: \"azure_endpoint\",\n\tazureOpenAIApiVersion: \"openai_api_version\",\n\tazureOpenAIBasePath: \"openai_api_base\",\n\tazureOpenAIApiDeploymentName: \"deployment_name\"\n};\nconst AZURE_SECRETS = { azureOpenAIApiKey: \"AZURE_OPENAI_API_KEY\" };\nconst AZURE_SERIALIZABLE_KEYS = [\n\t\"azureOpenAIApiKey\",\n\t\"azureOpenAIApiVersion\",\n\t\"azureOpenAIBasePath\",\n\t\"azureOpenAIEndpoint\",\n\t\"azureOpenAIApiInstanceName\",\n\t\"azureOpenAIApiDeploymentName\",\n\t\"deploymentName\",\n\t\"openAIApiKey\",\n\t\"openAIApiVersion\"\n];\nfunction _constructAzureFields(fields) {\n\tthis.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? fields?.openAIApiKey ?? fields?.apiKey ?? getEnvironmentVariable(\"AZURE_OPENAI_API_KEY\");\n\tthis.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable(\"AZURE_OPENAI_API_INSTANCE_NAME\");\n\tthis.azureOpenAIApiDeploymentName = fields?.azureOpenAIApiDeploymentName ?? fields?.deploymentName ?? getEnvironmentVariable(\"AZURE_OPENAI_API_DEPLOYMENT_NAME\");\n\tthis.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable(\"AZURE_OPENAI_API_VERSION\");\n\tthis.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable(\"AZURE_OPENAI_BASE_PATH\");\n\tthis.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\");\n\tthis.azureADTokenProvider = fields?.azureADTokenProvider;\n\tif (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error(\"Azure OpenAI API key or Token Provider not found\");\n}\nfunction _getAzureClientOptions(options) {\n\tif (!this.client) {\n\t\tconst openAIEndpointConfig = {\n\t\t\tazureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,\n\t\t\tazureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,\n\t\t\tazureOpenAIApiKey: this.azureOpenAIApiKey,\n\t\t\tazureOpenAIBasePath: this.azureOpenAIBasePath,\n\t\t\tazureADTokenProvider: this.azureADTokenProvider,\n\t\t\tbaseURL: this.clientConfig.baseURL,\n\t\t\tazureOpenAIEndpoint: this.azureOpenAIEndpoint\n\t\t};\n\t\tconst endpoint = getEndpoint(openAIEndpointConfig);\n\t\tconst params = {\n\t\t\t...this.clientConfig,\n\t\t\tbaseURL: endpoint,\n\t\t\ttimeout: this.timeout,\n\t\t\tmaxRetries: 0\n\t\t};\n\t\tif (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey;\n\t\tif (!params.baseURL) delete params.baseURL;\n\t\tlet env = getEnv();\n\t\tif (env === \"node\" || env === \"deno\") env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`;\n\t\tconst defaultHeaders = normalizeHeaders(params.defaultHeaders);\n\t\tparams.defaultHeaders = {\n\t\t\t...params.defaultHeaders,\n\t\t\t\"User-Agent\": defaultHeaders[\"User-Agent\"] ? `langchainjs-azure-openai/2.0.0 (${env})${defaultHeaders[\"User-Agent\"]}` : `langchainjs-azure-openai/2.0.0 (${env})`\n\t\t};\n\t\tthis.client = new AzureOpenAI({\n\t\t\tapiVersion: this.azureOpenAIApiVersion,\n\t\t\tazureADTokenProvider: this.azureADTokenProvider,\n\t\t\tdeployment: this.azureOpenAIApiDeploymentName,\n\t\t\t...params\n\t\t});\n\t}\n\tconst requestOptions = {\n\t\t...this.clientConfig,\n\t\t...options\n\t};\n\tif (this.azureOpenAIApiKey) {\n\t\trequestOptions.headers = {\n\t\t\t\"api-key\": this.azureOpenAIApiKey,\n\t\t\t...requestOptions.headers\n\t\t};\n\t\trequestOptions.query = {\n\t\t\t\"api-version\": this.azureOpenAIApiVersion,\n\t\t\t...requestOptions.query\n\t\t};\n\t}\n\treturn requestOptions;\n}\nfunction _serializeAzureChat(input) {\n\tconst json = input;\n\tfunction isRecord(obj) {\n\t\treturn typeof obj === \"object\" && obj != null;\n\t}\n\tif (isRecord(json) && isRecord(json.kwargs)) {\n\t\tdelete json.kwargs.azure_openai_base_path;\n\t\tdelete json.kwargs.azure_openai_api_deployment_name;\n\t\tdelete json.kwargs.azure_openai_api_key;\n\t\tdelete json.kwargs.azure_openai_api_version;\n\t\tdelete json.kwargs.azure_open_ai_base_path;\n\t\tif (!json.kwargs.azure_endpoint && this.azureOpenAIEndpoint) json.kwargs.azure_endpoint = this.azureOpenAIEndpoint;\n\t\tif (!json.kwargs.azure_endpoint && this.azureOpenAIBasePath) {\n\t\t\tconst parts = this.azureOpenAIBasePath.split(\"/openai/deployments/\");\n\t\t\tif (parts.length === 2 && parts[0].startsWith(\"http\")) {\n\t\t\t\tconst [endpoint] = parts;\n\t\t\t\tjson.kwargs.azure_endpoint = endpoint;\n\t\t\t}\n\t\t}\n\t\tif (!json.kwargs.azure_endpoint && this.azureOpenAIApiInstanceName) json.kwargs.azure_endpoint = `https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`;\n\t\tif (!json.kwargs.deployment_name && this.azureOpenAIApiDeploymentName) json.kwargs.deployment_name = this.azureOpenAIApiDeploymentName;\n\t\tif (!json.kwargs.deployment_name && this.azureOpenAIBasePath) {\n\t\t\tconst parts = this.azureOpenAIBasePath.split(\"/openai/deployments/\");\n\t\t\tif (parts.length === 2) {\n\t\t\t\tconst [, deployment] = parts;\n\t\t\t\tjson.kwargs.deployment_name = deployment;\n\t\t\t}\n\t\t}\n\t\tif (json.kwargs.azure_endpoint && json.kwargs.deployment_name && json.kwargs.openai_api_base) delete json.kwargs.openai_api_base;\n\t\tif (json.kwargs.azure_openai_api_instance_name && json.kwargs.azure_endpoint) delete json.kwargs.azure_openai_api_instance_name;\n\t}\n\treturn json;\n}\n\n//#endregion\nexport { AZURE_ALIASES, AZURE_SECRETS, AZURE_SERIALIZABLE_KEYS, _constructAzureFields, _getAzureClientOptions, _serializeAzureChat };\n//# sourceMappingURL=common.js.map","import { ChatOpenAICompletions } from \"../../chat_models/completions.js\";\nimport { AZURE_ALIASES, AZURE_SECRETS, AZURE_SERIALIZABLE_KEYS, _constructAzureFields, _getAzureClientOptions, _serializeAzureChat } from \"./common.js\";\n\n//#region src/azure/chat_models/completions.ts\nvar AzureChatOpenAICompletions = class extends ChatOpenAICompletions {\n\tazureOpenAIApiVersion;\n\tazureOpenAIApiKey;\n\tazureADTokenProvider;\n\tazureOpenAIApiInstanceName;\n\tazureOpenAIApiDeploymentName;\n\tazureOpenAIBasePath;\n\tazureOpenAIEndpoint;\n\t_llmType() {\n\t\treturn \"azure_openai\";\n\t}\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\t...AZURE_ALIASES\n\t\t};\n\t}\n\tget lc_secrets() {\n\t\treturn {\n\t\t\t...super.lc_secrets,\n\t\t\t...AZURE_SECRETS\n\t\t};\n\t}\n\tget lc_serializable_keys() {\n\t\treturn [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS];\n\t}\n\tgetLsParams(options) {\n\t\tconst params = super.getLsParams(options);\n\t\tparams.ls_provider = \"azure\";\n\t\treturn params;\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\t_constructAzureFields.call(this, fields);\n\t}\n\t_getClientOptions(options) {\n\t\treturn _getAzureClientOptions.call(this, options);\n\t}\n\ttoJSON() {\n\t\treturn _serializeAzureChat.call(this, super.toJSON());\n\t}\n};\n\n//#endregion\nexport { AzureChatOpenAICompletions };\n//# sourceMappingURL=completions.js.map","import { ChatOpenAIResponses } from \"../../chat_models/responses.js\";\nimport { AZURE_ALIASES, AZURE_SECRETS, AZURE_SERIALIZABLE_KEYS, _constructAzureFields, _getAzureClientOptions, _serializeAzureChat } from \"./common.js\";\n\n//#region src/azure/chat_models/responses.ts\nvar AzureChatOpenAIResponses = class extends ChatOpenAIResponses {\n\tazureOpenAIApiVersion;\n\tazureOpenAIApiKey;\n\tazureADTokenProvider;\n\tazureOpenAIApiInstanceName;\n\tazureOpenAIApiDeploymentName;\n\tazureOpenAIBasePath;\n\tazureOpenAIEndpoint;\n\t_llmType() {\n\t\treturn \"azure_openai\";\n\t}\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\t...AZURE_ALIASES\n\t\t};\n\t}\n\tget lc_secrets() {\n\t\treturn {\n\t\t\t...super.lc_secrets,\n\t\t\t...AZURE_SECRETS\n\t\t};\n\t}\n\tget lc_serializable_keys() {\n\t\treturn [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS];\n\t}\n\tgetLsParams(options) {\n\t\tconst params = super.getLsParams(options);\n\t\tparams.ls_provider = \"azure\";\n\t\treturn params;\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\t_constructAzureFields.call(this, fields);\n\t}\n\t_getClientOptions(options) {\n\t\treturn _getAzureClientOptions.call(this, options);\n\t}\n\ttoJSON() {\n\t\treturn _serializeAzureChat.call(this, super.toJSON());\n\t}\n};\n\n//#endregion\nexport { AzureChatOpenAIResponses };\n//# sourceMappingURL=responses.js.map","import { ChatOpenAI } from \"../../chat_models/index.js\";\nimport { AZURE_ALIASES, AZURE_SECRETS, AZURE_SERIALIZABLE_KEYS, _constructAzureFields, _serializeAzureChat } from \"./common.js\";\nimport { AzureChatOpenAICompletions } from \"./completions.js\";\nimport { AzureChatOpenAIResponses } from \"./responses.js\";\n\n//#region src/azure/chat_models/index.ts\n/**\n* Azure OpenAI chat model integration.\n*\n* Setup:\n* Install `@langchain/openai` and set the following environment variables:\n*\n* ```bash\n* npm install @langchain/openai\n* export AZURE_OPENAI_API_KEY=\"your-api-key\"\n* export AZURE_OPENAI_API_DEPLOYMENT_NAME=\"your-deployment-name\"\n* export AZURE_OPENAI_API_VERSION=\"your-version\"\n* export AZURE_OPENAI_BASE_PATH=\"your-base-path\"\n* ```\n*\n* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.AzureChatOpenAI.html#constructor)\n*\n* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)\n*\n* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n*\n* ```typescript\n* // When calling `.withConfig`, call options should be passed via the first argument\n* const llmWithArgsBound = llm.withConfig({\n* stop: [\"\\n\"],\n* tools: [...],\n* });\n*\n* // When calling `.bindTools`, call options should be passed via the second argument\n* const llmWithTools = llm.bindTools(\n* [...],\n* {\n* tool_choice: \"auto\",\n* }\n* );\n* ```\n*\n* ## Examples\n*\n*
\n* Instantiate\n*\n* ```typescript\n* import { AzureChatOpenAI } from '@langchain/openai';\n*\n* const llm = new AzureChatOpenAI({\n* azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY, // In Node.js defaults to process.env.AZURE_OPENAI_API_KEY\n* azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_INSTANCE_NAME\n* azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME\n* azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION, // In Node.js defaults to process.env.AZURE_OPENAI_API_VERSION\n* temperature: 0,\n* maxTokens: undefined,\n* timeout: undefined,\n* maxRetries: 2,\n* // apiKey: \"...\",\n* // baseUrl: \"...\",\n* // other params...\n* });\n* ```\n*
\n*\n*
\n*\n*
\n* Invoking\n*\n* ```typescript\n* const input = `Translate \"I love programming\" into French.`;\n*\n* // Models also accept a list of chat messages or a formatted prompt\n* const result = await llm.invoke(input);\n* console.log(result);\n* ```\n*\n* ```txt\n* AIMessage {\n* \"id\": \"chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz\",\n* \"content\": \"J'adore la programmation.\",\n* \"response_metadata\": {\n* \"tokenUsage\": {\n* \"completionTokens\": 5,\n* \"promptTokens\": 28,\n* \"totalTokens\": 33\n* },\n* \"finish_reason\": \"stop\",\n* \"system_fingerprint\": \"fp_3aa7262c27\"\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 28,\n* \"output_tokens\": 5,\n* \"total_tokens\": 33\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Streaming Chunks\n*\n* ```typescript\n* for await (const chunk of await llm.stream(input)) {\n* console.log(chunk);\n* }\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"id\": \"chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs\",\n* \"content\": \"\"\n* }\n* AIMessageChunk {\n* \"content\": \"J\"\n* }\n* AIMessageChunk {\n* \"content\": \"'adore\"\n* }\n* AIMessageChunk {\n* \"content\": \" la\"\n* }\n* AIMessageChunk {\n* \"content\": \" programmation\",,\n* }\n* AIMessageChunk {\n* \"content\": \".\",,\n* }\n* AIMessageChunk {\n* \"content\": \"\",\n* \"response_metadata\": {\n* \"finish_reason\": \"stop\",\n* \"system_fingerprint\": \"fp_c9aa9c0491\"\n* },\n* }\n* AIMessageChunk {\n* \"content\": \"\",\n* \"usage_metadata\": {\n* \"input_tokens\": 28,\n* \"output_tokens\": 5,\n* \"total_tokens\": 33\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Aggregate Streamed Chunks\n*\n* ```typescript\n* import { AIMessageChunk } from '@langchain/core/messages';\n* import { concat } from '@langchain/core/utils/stream';\n*\n* const stream = await llm.stream(input);\n* let full: AIMessageChunk | undefined;\n* for await (const chunk of stream) {\n* full = !full ? chunk : concat(full, chunk);\n* }\n* console.log(full);\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"id\": \"chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu\",\n* \"content\": \"J'adore la programmation.\",\n* \"response_metadata\": {\n* \"prompt\": 0,\n* \"completion\": 0,\n* \"finish_reason\": \"stop\",\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 28,\n* \"output_tokens\": 5,\n* \"total_tokens\": 33\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Bind tools\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const GetWeather = {\n* name: \"GetWeather\",\n* description: \"Get the current weather in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const GetPopulation = {\n* name: \"GetPopulation\",\n* description: \"Get the current population in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n* const aiMsg = await llmWithTools.invoke(\n* \"Which city is hotter today and which is bigger: LA or NY?\"\n* );\n* console.log(aiMsg.tool_calls);\n* ```\n*\n* ```txt\n* [\n* {\n* name: 'GetWeather',\n* args: { location: 'Los Angeles, CA' },\n* type: 'tool_call',\n* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'\n* },\n* {\n* name: 'GetWeather',\n* args: { location: 'New York, NY' },\n* type: 'tool_call',\n* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'Los Angeles, CA' },\n* type: 'tool_call',\n* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'New York, NY' },\n* type: 'tool_call',\n* id: 'call_s9KQB1UWj45LLGaEnjz0179q'\n* }\n* ]\n* ```\n*
\n*\n*
\n*\n*
\n* Structured Output\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const Joke = z.object({\n* setup: z.string().describe(\"The setup of the joke\"),\n* punchline: z.string().describe(\"The punchline to the joke\"),\n* rating: z.number().nullable().describe(\"How funny the joke is, from 1 to 10\")\n* }).describe('Joke to tell user.');\n*\n* const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n* const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n* console.log(jokeResult);\n* ```\n*\n* ```txt\n* {\n* setup: 'Why was the cat sitting on the computer?',\n* punchline: 'Because it wanted to keep an eye on the mouse!',\n* rating: 7\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* JSON Object Response Format\n*\n* ```typescript\n* const jsonLlm = llm.withConfig({ response_format: { type: \"json_object\" } });\n* const jsonLlmAiMsg = await jsonLlm.invoke(\n* \"Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]\"\n* );\n* console.log(jsonLlmAiMsg.content);\n* ```\n*\n* ```txt\n* {\n* \"randomInts\": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Multimodal\n*\n* ```typescript\n* import { HumanMessage } from '@langchain/core/messages';\n*\n* const imageUrl = \"https://example.com/image.jpg\";\n* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n* const base64Image = Buffer.from(imageData).toString('base64');\n*\n* const message = new HumanMessage({\n* content: [\n* { type: \"text\", text: \"describe the weather in this image\" },\n* {\n* type: \"image_url\",\n* image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n* },\n* ]\n* });\n*\n* const imageDescriptionAiMsg = await llm.invoke([message]);\n* console.log(imageDescriptionAiMsg.content);\n* ```\n*\n* ```txt\n* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.\n* ```\n*
\n*\n*
\n*\n*
\n* Usage Metadata\n*\n* ```typescript\n* const aiMsgForMetadata = await llm.invoke(input);\n* console.log(aiMsgForMetadata.usage_metadata);\n* ```\n*\n* ```txt\n* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }\n* ```\n*
\n*\n*
\n*\n*
\n* Logprobs\n*\n* ```typescript\n* const logprobsLlm = new ChatOpenAI({ model: \"gpt-4o-mini\", logprobs: true });\n* const aiMsgForLogprobs = await logprobsLlm.invoke(input);\n* console.log(aiMsgForLogprobs.response_metadata.logprobs);\n* ```\n*\n* ```txt\n* {\n* content: [\n* {\n* token: 'J',\n* logprob: -0.000050616763,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* {\n* token: \"'\",\n* logprob: -0.01868736,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* {\n* token: 'ad',\n* logprob: -0.0000030545007,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },\n* {\n* token: ' la',\n* logprob: -0.515404,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* {\n* token: ' programm',\n* logprob: -0.0000118755715,\n* bytes: [Array],\n* top_logprobs: []\n* },\n* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },\n* {\n* token: '.',\n* logprob: -0.0000037697225,\n* bytes: [Array],\n* top_logprobs: []\n* }\n* ],\n* refusal: null\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Response Metadata\n*\n* ```typescript\n* const aiMsgForResponseMetadata = await llm.invoke(input);\n* console.log(aiMsgForResponseMetadata.response_metadata);\n* ```\n*\n* ```txt\n* {\n* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },\n* finish_reason: 'stop',\n* system_fingerprint: 'fp_3aa7262c27'\n* }\n* ```\n*
\n*/\nvar AzureChatOpenAI = class extends ChatOpenAI {\n\tazureOpenAIApiVersion;\n\tazureOpenAIApiKey;\n\tazureADTokenProvider;\n\tazureOpenAIApiInstanceName;\n\tazureOpenAIApiDeploymentName;\n\tazureOpenAIBasePath;\n\tazureOpenAIEndpoint;\n\t_llmType() {\n\t\treturn \"azure_openai\";\n\t}\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\t...AZURE_ALIASES\n\t\t};\n\t}\n\tget lc_secrets() {\n\t\treturn {\n\t\t\t...super.lc_secrets,\n\t\t\t...AZURE_SECRETS\n\t\t};\n\t}\n\tget lc_serializable_keys() {\n\t\treturn [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS];\n\t}\n\tgetLsParams(options) {\n\t\tconst params = super.getLsParams(options);\n\t\tparams.ls_provider = \"azure\";\n\t\treturn params;\n\t}\n\tconstructor(fields) {\n\t\tsuper({\n\t\t\t...fields,\n\t\t\tcompletions: new AzureChatOpenAICompletions(fields),\n\t\t\tresponses: new AzureChatOpenAIResponses(fields)\n\t\t});\n\t\t_constructAzureFields.call(this, fields);\n\t}\n\t/** @internal */\n\t_getStructuredOutputMethod(config) {\n\t\tconst ensuredConfig = { ...config };\n\t\tif (this.model.startsWith(\"gpt-4o\")) {\n\t\t\tif (ensuredConfig?.method === void 0) return \"functionCalling\";\n\t\t}\n\t\treturn super._getStructuredOutputMethod(ensuredConfig);\n\t}\n\ttoJSON() {\n\t\treturn _serializeAzureChat.call(this, super.toJSON());\n\t}\n};\n\n//#endregion\nexport { AzureChatOpenAI };\n//# sourceMappingURL=index.js.map","import { getEndpoint } from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\nimport { OpenAI as OpenAI$1 } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { calculateMaxTokens } from \"@langchain/core/language_models/base\";\nimport { GenerationChunk } from \"@langchain/core/outputs\";\nimport { BaseLLM } from \"@langchain/core/language_models/llms\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\n\n//#region src/llms.ts\n/**\n* Wrapper around OpenAI large language models.\n*\n* To use you should have the `openai` package installed, with the\n* `OPENAI_API_KEY` environment variable set.\n*\n* To use with Azure, import the `AzureOpenAI` class.\n*\n* @remarks\n* Any parameters that are valid to be passed to {@link\n* https://platform.openai.com/docs/api-reference/completions/create |\n* `openai.createCompletion`} can be passed through {@link modelKwargs}, even\n* if not explicitly available on this class.\n* @example\n* ```typescript\n* const model = new OpenAI({\n* modelName: \"gpt-4\",\n* temperature: 0.7,\n* maxTokens: 1000,\n* maxRetries: 5,\n* });\n*\n* const res = await model.invoke(\n* \"Question: What would be a good company name for a company that makes colorful socks?\\nAnswer:\"\n* );\n* console.log({ res });\n* ```\n*/\nvar OpenAI$2 = class extends BaseLLM {\n\tstatic lc_name() {\n\t\treturn \"OpenAI\";\n\t}\n\tget callKeys() {\n\t\treturn [...super.callKeys, \"options\"];\n\t}\n\tlc_serializable = true;\n\tget lc_secrets() {\n\t\treturn {\n\t\t\topenAIApiKey: \"OPENAI_API_KEY\",\n\t\t\tapiKey: \"OPENAI_API_KEY\",\n\t\t\torganization: \"OPENAI_ORGANIZATION\"\n\t\t};\n\t}\n\tget lc_aliases() {\n\t\treturn {\n\t\t\tmodelName: \"model\",\n\t\t\topenAIApiKey: \"openai_api_key\",\n\t\t\tapiKey: \"openai_api_key\"\n\t\t};\n\t}\n\ttemperature;\n\tmaxTokens;\n\ttopP;\n\tfrequencyPenalty;\n\tpresencePenalty;\n\tn = 1;\n\tbestOf;\n\tlogitBias;\n\tmodel = \"gpt-3.5-turbo-instruct\";\n\t/** @deprecated Use \"model\" instead */\n\tmodelName;\n\tmodelKwargs;\n\tbatchSize = 20;\n\ttimeout;\n\tstop;\n\tstopSequences;\n\tuser;\n\tstreaming = false;\n\topenAIApiKey;\n\tapiKey;\n\torganization;\n\tclient;\n\tclientConfig;\n\tconstructor(fields) {\n\t\tsuper(fields ?? {});\n\t\tthis.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable(\"OPENAI_API_KEY\");\n\t\tthis.apiKey = this.openAIApiKey;\n\t\tthis.organization = fields?.configuration?.organization ?? getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\t\tthis.model = fields?.model ?? fields?.modelName ?? this.model;\n\t\tif ((this.model?.startsWith(\"gpt-3.5-turbo\") || this.model?.startsWith(\"gpt-4\") || this.model?.startsWith(\"o1\")) && !this.model?.includes(\"-instruct\")) throw new Error([\n\t\t\t`Your chosen OpenAI model, \"${this.model}\", is a chat model and not a text-in/text-out LLM.`,\n\t\t\t`Passing it into the \"OpenAI\" class is no longer supported.`,\n\t\t\t`Please use the \"ChatOpenAI\" class instead.`,\n\t\t\t\"\",\n\t\t\t`See this page for more information:`,\n\t\t\t\"|\",\n\t\t\t`└> https://js.langchain.com/docs/integrations/chat/openai`\n\t\t].join(\"\\n\"));\n\t\tthis.modelName = this.model;\n\t\tthis.modelKwargs = fields?.modelKwargs ?? {};\n\t\tthis.batchSize = fields?.batchSize ?? this.batchSize;\n\t\tthis.timeout = fields?.timeout;\n\t\tthis.temperature = fields?.temperature ?? this.temperature;\n\t\tthis.maxTokens = fields?.maxTokens ?? this.maxTokens;\n\t\tthis.topP = fields?.topP ?? this.topP;\n\t\tthis.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;\n\t\tthis.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;\n\t\tthis.n = fields?.n ?? this.n;\n\t\tthis.bestOf = fields?.bestOf ?? this.bestOf;\n\t\tthis.logitBias = fields?.logitBias;\n\t\tthis.stop = fields?.stopSequences ?? fields?.stop;\n\t\tthis.stopSequences = this.stop;\n\t\tthis.user = fields?.user;\n\t\tthis.streaming = fields?.streaming ?? false;\n\t\tif (this.streaming && this.bestOf && this.bestOf > 1) throw new Error(\"Cannot stream results when bestOf > 1\");\n\t\tthis.clientConfig = {\n\t\t\tapiKey: this.apiKey,\n\t\t\torganization: this.organization,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t...fields?.configuration\n\t\t};\n\t}\n\t/**\n\t* Get the parameters used to invoke the model\n\t*/\n\tinvocationParams(options) {\n\t\treturn {\n\t\t\tmodel: this.model,\n\t\t\ttemperature: this.temperature,\n\t\t\tmax_tokens: this.maxTokens,\n\t\t\ttop_p: this.topP,\n\t\t\tfrequency_penalty: this.frequencyPenalty,\n\t\t\tpresence_penalty: this.presencePenalty,\n\t\t\tn: this.n,\n\t\t\tbest_of: this.bestOf,\n\t\t\tlogit_bias: this.logitBias,\n\t\t\tstop: options?.stop ?? this.stopSequences,\n\t\t\tuser: this.user,\n\t\t\tstream: this.streaming,\n\t\t\t...this.modelKwargs\n\t\t};\n\t}\n\t/** @ignore */\n\t_identifyingParams() {\n\t\treturn {\n\t\t\tmodel_name: this.model,\n\t\t\t...this.invocationParams(),\n\t\t\t...this.clientConfig\n\t\t};\n\t}\n\t/**\n\t* Get the identifying parameters for the model\n\t*/\n\tidentifyingParams() {\n\t\treturn this._identifyingParams();\n\t}\n\t/**\n\t* Call out to OpenAI's endpoint with k unique prompts\n\t*\n\t* @param [prompts] - The prompts to pass into the model.\n\t* @param [options] - Optional list of stop words to use when generating.\n\t* @param [runManager] - Optional callback manager to use when generating.\n\t*\n\t* @returns The full LLM output.\n\t*\n\t* @example\n\t* ```ts\n\t* import { OpenAI } from \"langchain/llms/openai\";\n\t* const openai = new OpenAI();\n\t* const response = await openai.generate([\"Tell me a joke.\"]);\n\t* ```\n\t*/\n\tasync _generate(prompts, options, runManager) {\n\t\tconst subPrompts = chunkArray(prompts, this.batchSize);\n\t\tconst choices = [];\n\t\tconst tokenUsage = {};\n\t\tconst params = this.invocationParams(options);\n\t\tif (params.max_tokens === -1) {\n\t\t\tif (prompts.length !== 1) throw new Error(\"max_tokens set to -1 not supported for multiple inputs\");\n\t\t\tparams.max_tokens = await calculateMaxTokens({\n\t\t\t\tprompt: prompts[0],\n\t\t\t\tmodelName: this.model\n\t\t\t});\n\t\t}\n\t\tfor (let i = 0; i < subPrompts.length; i += 1) {\n\t\t\tconst data = params.stream ? await (async () => {\n\t\t\t\tconst choices$1 = [];\n\t\t\t\tlet response;\n\t\t\t\tconst stream = await this.completionWithRetry({\n\t\t\t\t\t...params,\n\t\t\t\t\tstream: true,\n\t\t\t\t\tprompt: subPrompts[i]\n\t\t\t\t}, options);\n\t\t\t\tfor await (const message of stream) {\n\t\t\t\t\tif (!response) response = {\n\t\t\t\t\t\tid: message.id,\n\t\t\t\t\t\tobject: message.object,\n\t\t\t\t\t\tcreated: message.created,\n\t\t\t\t\t\tmodel: message.model\n\t\t\t\t\t};\n\t\t\t\t\tfor (const part of message.choices) {\n\t\t\t\t\t\tif (!choices$1[part.index]) choices$1[part.index] = part;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst choice = choices$1[part.index];\n\t\t\t\t\t\t\tchoice.text += part.text;\n\t\t\t\t\t\t\tchoice.finish_reason = part.finish_reason;\n\t\t\t\t\t\t\tchoice.logprobs = part.logprobs;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trunManager?.handleLLMNewToken(part.text, {\n\t\t\t\t\t\t\tprompt: Math.floor(part.index / this.n),\n\t\t\t\t\t\t\tcompletion: part.index % this.n\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (options.signal?.aborted) throw new Error(\"AbortError\");\n\t\t\t\treturn {\n\t\t\t\t\t...response,\n\t\t\t\t\tchoices: choices$1\n\t\t\t\t};\n\t\t\t})() : await this.completionWithRetry({\n\t\t\t\t...params,\n\t\t\t\tstream: false,\n\t\t\t\tprompt: subPrompts[i]\n\t\t\t}, {\n\t\t\t\tsignal: options.signal,\n\t\t\t\t...options.options\n\t\t\t});\n\t\t\tchoices.push(...data.choices);\n\t\t\tconst { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data.usage ? data.usage : {\n\t\t\t\tcompletion_tokens: void 0,\n\t\t\t\tprompt_tokens: void 0,\n\t\t\t\ttotal_tokens: void 0\n\t\t\t};\n\t\t\tif (completionTokens) tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens;\n\t\t\tif (promptTokens) tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;\n\t\t\tif (totalTokens) tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;\n\t\t}\n\t\tconst generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({\n\t\t\ttext: choice.text ?? \"\",\n\t\t\tgenerationInfo: {\n\t\t\t\tfinishReason: choice.finish_reason,\n\t\t\t\tlogprobs: choice.logprobs\n\t\t\t}\n\t\t})));\n\t\treturn {\n\t\t\tgenerations,\n\t\t\tllmOutput: { tokenUsage }\n\t\t};\n\t}\n\tasync *_streamResponseChunks(input, options, runManager) {\n\t\tconst params = {\n\t\t\t...this.invocationParams(options),\n\t\t\tprompt: input,\n\t\t\tstream: true\n\t\t};\n\t\tconst stream = await this.completionWithRetry(params, options);\n\t\tfor await (const data of stream) {\n\t\t\tconst choice = data?.choices[0];\n\t\t\tif (!choice) continue;\n\t\t\tconst chunk = new GenerationChunk({\n\t\t\t\ttext: choice.text,\n\t\t\t\tgenerationInfo: { finishReason: choice.finish_reason }\n\t\t\t});\n\t\t\tyield chunk;\n\t\t\trunManager?.handleLLMNewToken(chunk.text ?? \"\");\n\t\t}\n\t\tif (options.signal?.aborted) throw new Error(\"AbortError\");\n\t}\n\tasync completionWithRetry(request, options) {\n\t\tconst requestOptions = this._getClientOptions(options);\n\t\treturn this.caller.call(async () => {\n\t\t\ttry {\n\t\t\t\tconst res = await this.client.completions.create(request, requestOptions);\n\t\t\t\treturn res;\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapOpenAIClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Calls the OpenAI API with retry logic in case of failures.\n\t* @param request The request to send to the OpenAI API.\n\t* @param options Optional configuration for the API call.\n\t* @returns The response from the OpenAI API.\n\t*/\n\t_getClientOptions(options) {\n\t\tif (!this.client) {\n\t\t\tconst openAIEndpointConfig = { baseURL: this.clientConfig.baseURL };\n\t\t\tconst endpoint = getEndpoint(openAIEndpointConfig);\n\t\t\tconst params = {\n\t\t\t\t...this.clientConfig,\n\t\t\t\tbaseURL: endpoint,\n\t\t\t\ttimeout: this.timeout,\n\t\t\t\tmaxRetries: 0\n\t\t\t};\n\t\t\tif (!params.baseURL) delete params.baseURL;\n\t\t\tthis.client = new OpenAI$1(params);\n\t\t}\n\t\tconst requestOptions = {\n\t\t\t...this.clientConfig,\n\t\t\t...options\n\t\t};\n\t\treturn requestOptions;\n\t}\n\t_llmType() {\n\t\treturn \"openai\";\n\t}\n};\n\n//#endregion\nexport { OpenAI$2 as OpenAI };\n//# sourceMappingURL=llms.js.map","import { getEndpoint, normalizeHeaders } from \"../utils/azure.js\";\nimport { OpenAI } from \"../llms.js\";\nimport { AzureOpenAI } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\n\n//#region src/azure/llms.ts\nvar AzureOpenAI$1 = class extends OpenAI {\n\tazureOpenAIApiVersion;\n\tazureOpenAIApiKey;\n\tazureADTokenProvider;\n\tazureOpenAIApiInstanceName;\n\tazureOpenAIApiDeploymentName;\n\tazureOpenAIBasePath;\n\tazureOpenAIEndpoint;\n\tget lc_aliases() {\n\t\treturn {\n\t\t\t...super.lc_aliases,\n\t\t\topenAIApiKey: \"openai_api_key\",\n\t\t\topenAIApiVersion: \"openai_api_version\",\n\t\t\topenAIBasePath: \"openai_api_base\",\n\t\t\tdeploymentName: \"deployment_name\",\n\t\t\tazureOpenAIEndpoint: \"azure_endpoint\",\n\t\t\tazureOpenAIApiVersion: \"openai_api_version\",\n\t\t\tazureOpenAIBasePath: \"openai_api_base\",\n\t\t\tazureOpenAIApiDeploymentName: \"deployment_name\"\n\t\t};\n\t}\n\tget lc_secrets() {\n\t\treturn {\n\t\t\t...super.lc_secrets,\n\t\t\tazureOpenAIApiKey: \"AZURE_OPENAI_API_KEY\"\n\t\t};\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiCompletionsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable(\"AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME\") || getEnvironmentVariable(\"AZURE_OPENAI_API_DEPLOYMENT_NAME\"));\n\t\tthis.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? fields?.openAIApiKey ?? fields?.apiKey ?? getEnvironmentVariable(\"AZURE_OPENAI_API_KEY\");\n\t\tthis.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable(\"AZURE_OPENAI_API_INSTANCE_NAME\");\n\t\tthis.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable(\"AZURE_OPENAI_API_VERSION\");\n\t\tthis.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable(\"AZURE_OPENAI_BASE_PATH\");\n\t\tthis.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\");\n\t\tthis.azureADTokenProvider = fields?.azureADTokenProvider;\n\t\tif (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error(\"Azure OpenAI API key or Token Provider not found\");\n\t}\n\t_getClientOptions(options) {\n\t\tif (!this.client) {\n\t\t\tconst openAIEndpointConfig = {\n\t\t\t\tazureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,\n\t\t\t\tazureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,\n\t\t\t\tazureOpenAIApiKey: this.azureOpenAIApiKey,\n\t\t\t\tazureOpenAIBasePath: this.azureOpenAIBasePath,\n\t\t\t\tazureADTokenProvider: this.azureADTokenProvider,\n\t\t\t\tbaseURL: this.clientConfig.baseURL\n\t\t\t};\n\t\t\tconst endpoint = getEndpoint(openAIEndpointConfig);\n\t\t\tconst params = {\n\t\t\t\t...this.clientConfig,\n\t\t\t\tbaseURL: endpoint,\n\t\t\t\ttimeout: this.timeout,\n\t\t\t\tmaxRetries: 0\n\t\t\t};\n\t\t\tif (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey;\n\t\t\tif (!params.baseURL) delete params.baseURL;\n\t\t\tconst defaultHeaders = normalizeHeaders(params.defaultHeaders);\n\t\t\tparams.defaultHeaders = {\n\t\t\t\t...params.defaultHeaders,\n\t\t\t\t\"User-Agent\": defaultHeaders[\"User-Agent\"] ? `${defaultHeaders[\"User-Agent\"]}: langchainjs-azure-openai-v2` : `langchainjs-azure-openai-v2`\n\t\t\t};\n\t\t\tthis.client = new AzureOpenAI({\n\t\t\t\tapiVersion: this.azureOpenAIApiVersion,\n\t\t\t\tazureADTokenProvider: this.azureADTokenProvider,\n\t\t\t\t...params\n\t\t\t});\n\t\t}\n\t\tconst requestOptions = {\n\t\t\t...this.clientConfig,\n\t\t\t...options\n\t\t};\n\t\tif (this.azureOpenAIApiKey) {\n\t\t\trequestOptions.headers = {\n\t\t\t\t\"api-key\": this.azureOpenAIApiKey,\n\t\t\t\t...requestOptions.headers\n\t\t\t};\n\t\t\trequestOptions.query = {\n\t\t\t\t\"api-version\": this.azureOpenAIApiVersion,\n\t\t\t\t...requestOptions.query\n\t\t\t};\n\t\t}\n\t\treturn requestOptions;\n\t}\n\ttoJSON() {\n\t\tconst json = super.toJSON();\n\t\tfunction isRecord(obj) {\n\t\t\treturn typeof obj === \"object\" && obj != null;\n\t\t}\n\t\tif (isRecord(json) && isRecord(json.kwargs)) {\n\t\t\tdelete json.kwargs.azure_openai_base_path;\n\t\t\tdelete json.kwargs.azure_openai_api_deployment_name;\n\t\t\tdelete json.kwargs.azure_openai_api_key;\n\t\t\tdelete json.kwargs.azure_openai_api_version;\n\t\t\tdelete json.kwargs.azure_open_ai_base_path;\n\t\t}\n\t\treturn json;\n\t}\n};\n\n//#endregion\nexport { AzureOpenAI$1 as AzureOpenAI };\n//# sourceMappingURL=llms.js.map","import { getEndpoint } from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\nimport { OpenAI as OpenAI$1 } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport { Embeddings } from \"@langchain/core/embeddings\";\n\n//#region src/embeddings.ts\n/**\n* Class for generating embeddings using the OpenAI API.\n*\n* To use with Azure, import the `AzureOpenAIEmbeddings` class.\n*\n* @example\n* ```typescript\n* // Embed a query using OpenAIEmbeddings to generate embeddings for a given text\n* const model = new OpenAIEmbeddings();\n* const res = await model.embedQuery(\n* \"What would be a good company name for a company that makes colorful socks?\",\n* );\n* console.log({ res });\n*\n* ```\n*/\nvar OpenAIEmbeddings = class extends Embeddings {\n\tmodel = \"text-embedding-ada-002\";\n\t/** @deprecated Use \"model\" instead */\n\tmodelName;\n\tbatchSize = 512;\n\tstripNewLines = true;\n\t/**\n\t* The number of dimensions the resulting output embeddings should have.\n\t* Only supported in `text-embedding-3` and later models.\n\t*/\n\tdimensions;\n\ttimeout;\n\torganization;\n\tencodingFormat;\n\tclient;\n\tclientConfig;\n\tconstructor(fields) {\n\t\tconst fieldsWithDefaults = {\n\t\t\tmaxConcurrency: 2,\n\t\t\t...fields\n\t\t};\n\t\tsuper(fieldsWithDefaults);\n\t\tconst apiKey = fieldsWithDefaults?.apiKey ?? fieldsWithDefaults?.openAIApiKey ?? getEnvironmentVariable(\"OPENAI_API_KEY\");\n\t\tthis.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\t\tthis.model = fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;\n\t\tthis.modelName = this.model;\n\t\tthis.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;\n\t\tthis.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;\n\t\tthis.timeout = fieldsWithDefaults?.timeout;\n\t\tthis.dimensions = fieldsWithDefaults?.dimensions;\n\t\tthis.encodingFormat = fieldsWithDefaults?.encodingFormat;\n\t\tthis.clientConfig = {\n\t\t\tapiKey,\n\t\t\torganization: this.organization,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\t...fields?.configuration\n\t\t};\n\t}\n\t/**\n\t* Method to generate embeddings for an array of documents. Splits the\n\t* documents into batches and makes requests to the OpenAI API to generate\n\t* embeddings.\n\t* @param texts Array of documents to generate embeddings for.\n\t* @returns Promise that resolves to a 2D array of embeddings for each document.\n\t*/\n\tasync embedDocuments(texts) {\n\t\tconst batches = chunkArray(this.stripNewLines ? texts.map((t) => t.replace(/\\n/g, \" \")) : texts, this.batchSize);\n\t\tconst batchRequests = batches.map((batch) => {\n\t\t\tconst params = {\n\t\t\t\tmodel: this.model,\n\t\t\t\tinput: batch\n\t\t\t};\n\t\t\tif (this.dimensions) params.dimensions = this.dimensions;\n\t\t\tif (this.encodingFormat) params.encoding_format = this.encodingFormat;\n\t\t\treturn this.embeddingWithRetry(params);\n\t\t});\n\t\tconst batchResponses = await Promise.all(batchRequests);\n\t\tconst embeddings = [];\n\t\tfor (let i = 0; i < batchResponses.length; i += 1) {\n\t\t\tconst batch = batches[i];\n\t\t\tconst { data: batchResponse } = batchResponses[i];\n\t\t\tfor (let j = 0; j < batch.length; j += 1) embeddings.push(batchResponse[j].embedding);\n\t\t}\n\t\treturn embeddings;\n\t}\n\t/**\n\t* Method to generate an embedding for a single document. Calls the\n\t* embeddingWithRetry method with the document as the input.\n\t* @param text Document to generate an embedding for.\n\t* @returns Promise that resolves to an embedding for the document.\n\t*/\n\tasync embedQuery(text) {\n\t\tconst params = {\n\t\t\tmodel: this.model,\n\t\t\tinput: this.stripNewLines ? text.replace(/\\n/g, \" \") : text\n\t\t};\n\t\tif (this.dimensions) params.dimensions = this.dimensions;\n\t\tif (this.encodingFormat) params.encoding_format = this.encodingFormat;\n\t\tconst { data } = await this.embeddingWithRetry(params);\n\t\treturn data[0].embedding;\n\t}\n\t/**\n\t* Private method to make a request to the OpenAI API to generate\n\t* embeddings. Handles the retry logic and returns the response from the\n\t* API.\n\t* @param request Request to send to the OpenAI API.\n\t* @returns Promise that resolves to the response from the API.\n\t*/\n\tasync embeddingWithRetry(request) {\n\t\tif (!this.client) {\n\t\t\tconst openAIEndpointConfig = { baseURL: this.clientConfig.baseURL };\n\t\t\tconst endpoint = getEndpoint(openAIEndpointConfig);\n\t\t\tconst params = {\n\t\t\t\t...this.clientConfig,\n\t\t\t\tbaseURL: endpoint,\n\t\t\t\ttimeout: this.timeout,\n\t\t\t\tmaxRetries: 0\n\t\t\t};\n\t\t\tif (!params.baseURL) delete params.baseURL;\n\t\t\tthis.client = new OpenAI$1(params);\n\t\t}\n\t\tconst requestOptions = {};\n\t\treturn this.caller.call(async () => {\n\t\t\ttry {\n\t\t\t\tconst res = await this.client.embeddings.create(request, requestOptions);\n\t\t\t\treturn res;\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapOpenAIClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n};\n\n//#endregion\nexport { OpenAIEmbeddings };\n//# sourceMappingURL=embeddings.js.map","import { getEndpoint, normalizeHeaders } from \"../utils/azure.js\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport { OpenAIEmbeddings } from \"../embeddings.js\";\nimport { AzureOpenAI } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\n\n//#region src/azure/embeddings.ts\nvar AzureOpenAIEmbeddings = class extends OpenAIEmbeddings {\n\tazureOpenAIApiVersion;\n\tazureOpenAIApiKey;\n\tazureADTokenProvider;\n\tazureOpenAIApiInstanceName;\n\tazureOpenAIApiDeploymentName;\n\tazureOpenAIBasePath;\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.batchSize = fields?.batchSize ?? 1;\n\t\tthis.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? fields?.apiKey ?? getEnvironmentVariable(\"AZURE_OPENAI_API_KEY\");\n\t\tthis.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable(\"AZURE_OPENAI_API_VERSION\");\n\t\tthis.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable(\"AZURE_OPENAI_BASE_PATH\");\n\t\tthis.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable(\"AZURE_OPENAI_API_INSTANCE_NAME\");\n\t\tthis.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiEmbeddingsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable(\"AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME\") || getEnvironmentVariable(\"AZURE_OPENAI_API_DEPLOYMENT_NAME\"));\n\t\tthis.azureADTokenProvider = fields?.azureADTokenProvider;\n\t}\n\tasync embeddingWithRetry(request) {\n\t\tif (!this.client) {\n\t\t\tconst openAIEndpointConfig = {\n\t\t\t\tazureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,\n\t\t\t\tazureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,\n\t\t\t\tazureOpenAIApiKey: this.azureOpenAIApiKey,\n\t\t\t\tazureOpenAIBasePath: this.azureOpenAIBasePath,\n\t\t\t\tazureADTokenProvider: this.azureADTokenProvider,\n\t\t\t\tbaseURL: this.clientConfig.baseURL\n\t\t\t};\n\t\t\tconst endpoint = getEndpoint(openAIEndpointConfig);\n\t\t\tconst params = {\n\t\t\t\t...this.clientConfig,\n\t\t\t\tbaseURL: endpoint,\n\t\t\t\ttimeout: this.timeout,\n\t\t\t\tmaxRetries: 0\n\t\t\t};\n\t\t\tif (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey;\n\t\t\tif (!params.baseURL) delete params.baseURL;\n\t\t\tconst defaultHeaders = normalizeHeaders(params.defaultHeaders);\n\t\t\tparams.defaultHeaders = {\n\t\t\t\t...params.defaultHeaders,\n\t\t\t\t\"User-Agent\": defaultHeaders[\"User-Agent\"] ? `${defaultHeaders[\"User-Agent\"]}: langchainjs-azure-openai-v2` : `langchainjs-azure-openai-v2`\n\t\t\t};\n\t\t\tthis.client = new AzureOpenAI({\n\t\t\t\tapiVersion: this.azureOpenAIApiVersion,\n\t\t\t\tazureADTokenProvider: this.azureADTokenProvider,\n\t\t\t\tdeployment: this.azureOpenAIApiDeploymentName,\n\t\t\t\t...params\n\t\t\t});\n\t\t}\n\t\tconst requestOptions = {};\n\t\tif (this.azureOpenAIApiKey) {\n\t\t\trequestOptions.headers = {\n\t\t\t\t\"api-key\": this.azureOpenAIApiKey,\n\t\t\t\t...requestOptions.headers\n\t\t\t};\n\t\t\trequestOptions.query = {\n\t\t\t\t\"api-version\": this.azureOpenAIApiVersion,\n\t\t\t\t...requestOptions.query\n\t\t\t};\n\t\t}\n\t\treturn this.caller.call(async () => {\n\t\t\ttry {\n\t\t\t\tconst res = await this.client.embeddings.create(request, requestOptions);\n\t\t\t\treturn res;\n\t\t\t} catch (e) {\n\t\t\t\tconst error = wrapOpenAIClientError(e);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n};\n\n//#endregion\nexport { AzureOpenAIEmbeddings };\n//# sourceMappingURL=embeddings.js.map","import { OpenAI as OpenAI$1 } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Tool } from \"@langchain/core/tools\";\n\n//#region src/tools/dalle.ts\n/**\n* A tool for generating images with Open AIs Dall-E 2 or 3 API.\n*/\nvar DallEAPIWrapper = class extends Tool {\n\tstatic lc_name() {\n\t\treturn \"DallEAPIWrapper\";\n\t}\n\tname = \"dalle_api_wrapper\";\n\tdescription = \"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.\";\n\tclient;\n\tstatic toolName = \"dalle_api_wrapper\";\n\tmodel = \"dall-e-3\";\n\tstyle = \"vivid\";\n\tquality = \"standard\";\n\tn = 1;\n\tsize = \"1024x1024\";\n\tdallEResponseFormat = \"url\";\n\tuser;\n\tconstructor(fields) {\n\t\tif (fields?.responseFormat !== void 0 && [\"url\", \"b64_json\"].includes(fields.responseFormat)) {\n\t\t\tfields.dallEResponseFormat = fields.responseFormat;\n\t\t\tfields.responseFormat = \"content\";\n\t\t}\n\t\tsuper(fields);\n\t\tconst openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable(\"OPENAI_API_KEY\");\n\t\tconst organization = fields?.organization ?? getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\t\tconst clientConfig = {\n\t\t\tapiKey: openAIApiKey,\n\t\t\torganization,\n\t\t\tdangerouslyAllowBrowser: true,\n\t\t\tbaseURL: fields?.baseUrl\n\t\t};\n\t\tthis.client = new OpenAI$1(clientConfig);\n\t\tthis.model = fields?.model ?? fields?.modelName ?? this.model;\n\t\tthis.style = fields?.style ?? this.style;\n\t\tthis.quality = fields?.quality ?? this.quality;\n\t\tthis.n = fields?.n ?? this.n;\n\t\tthis.size = fields?.size ?? this.size;\n\t\tthis.dallEResponseFormat = fields?.dallEResponseFormat ?? this.dallEResponseFormat;\n\t\tthis.user = fields?.user;\n\t}\n\t/**\n\t* Processes the API response if multiple images are generated.\n\t* Returns a list of MessageContentImageUrl objects. If the response\n\t* format is `url`, then the `image_url` field will contain the URL.\n\t* If it is `b64_json`, then the `image_url` field will contain an object\n\t* with a `url` field with the base64 encoded image.\n\t*\n\t* @param {OpenAIClient.Images.ImagesResponse[]} response The API response\n\t* @returns {MessageContentImageUrl[]}\n\t*/\n\tprocessMultipleGeneratedUrls(response) {\n\t\tif (this.dallEResponseFormat === \"url\") return response.flatMap((res) => {\n\t\t\tconst imageUrlContent = res.data?.flatMap((item) => {\n\t\t\t\tif (!item.url) return [];\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\timage_url: item.url\n\t\t\t\t};\n\t\t\t}).filter((item) => item !== void 0 && item.type === \"image_url\" && typeof item.image_url === \"string\" && item.image_url !== void 0) ?? [];\n\t\t\treturn imageUrlContent;\n\t\t});\n\t\telse return response.flatMap((res) => {\n\t\t\tconst b64Content = res.data?.flatMap((item) => {\n\t\t\t\tif (!item.b64_json) return [];\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\timage_url: { url: item.b64_json }\n\t\t\t\t};\n\t\t\t}).filter((item) => item !== void 0 && item.type === \"image_url\" && typeof item.image_url === \"object\" && \"url\" in item.image_url && typeof item.image_url.url === \"string\" && item.image_url.url !== void 0) ?? [];\n\t\t\treturn b64Content;\n\t\t});\n\t}\n\t/** @ignore */\n\tasync _call(input) {\n\t\tconst generateImageFields = {\n\t\t\tmodel: this.model,\n\t\t\tprompt: input,\n\t\t\tn: 1,\n\t\t\tsize: this.size,\n\t\t\tresponse_format: this.dallEResponseFormat,\n\t\t\tstyle: this.style,\n\t\t\tquality: this.quality,\n\t\t\tuser: this.user\n\t\t};\n\t\tif (this.n > 1) {\n\t\t\tconst results = await Promise.all(Array.from({ length: this.n }).map(() => this.client.images.generate(generateImageFields)));\n\t\t\treturn this.processMultipleGeneratedUrls(results);\n\t\t}\n\t\tconst response = await this.client.images.generate(generateImageFields);\n\t\tlet data = \"\";\n\t\tif (this.dallEResponseFormat === \"url\") [data] = response.data?.map((item) => item.url).filter((url) => url !== \"undefined\") ?? [];\n\t\telse [data] = response.data?.map((item) => item.b64_json).filter((b64_json) => b64_json !== \"undefined\") ?? [];\n\t\treturn data;\n\t}\n};\n\n//#endregion\nexport { DallEAPIWrapper };\n//# sourceMappingURL=dalle.js.map","import { DallEAPIWrapper } from \"./dalle.js\";\n","import { patchConfig, pickRunnableConfigKeys } from \"@langchain/core/runnables\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\n\n//#region src/tools/custom.ts\nfunction customTool(func, fields) {\n\treturn new DynamicTool({\n\t\t...fields,\n\t\tdescription: \"\",\n\t\tmetadata: { customTool: fields },\n\t\tfunc: async (input, runManager, config) => new Promise((resolve, reject) => {\n\t\t\tconst childConfig = patchConfig(config, { callbacks: runManager?.getChild() });\n\t\t\tAsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(func(input, childConfig));\n\t\t\t\t} catch (e) {\n\t\t\t\t\treject(e);\n\t\t\t\t}\n\t\t\t});\n\t\t})\n\t});\n}\n\n//#endregion\nexport { customTool };\n//# sourceMappingURL=custom.js.map","import { _convertMessagesToOpenAIParams } from \"./message_inputs.js\";\n\n//#region src/utils/prompts.ts\n/**\n* Convert a formatted LangChain prompt (e.g. pulled from the hub) into\n* a format expected by OpenAI's JS SDK.\n*\n* Requires the \"@langchain/openai\" package to be installed in addition\n* to the OpenAI SDK.\n*\n* @example\n* ```ts\n* import { convertPromptToOpenAI } from \"langsmith/utils/hub/openai\";\n* import { pull } from \"langchain/hub\";\n*\n* import OpenAI from 'openai';\n*\n* const prompt = await pull(\"jacob/joke-generator\");\n* const formattedPrompt = await prompt.invoke({\n* topic: \"cats\",\n* });\n*\n* const { messages } = convertPromptToOpenAI(formattedPrompt);\n*\n* const openAIClient = new OpenAI();\n*\n* const openaiResponse = await openAIClient.chat.completions.create({\n* model: \"gpt-4o-mini\",\n* messages,\n* });\n* ```\n* @param formattedPrompt\n* @returns A partial OpenAI payload.\n*/\nfunction convertPromptToOpenAI(formattedPrompt) {\n\tconst messages = formattedPrompt.toChatMessages();\n\treturn { messages: _convertMessagesToOpenAIParams(messages) };\n}\n\n//#endregion\nexport { convertPromptToOpenAI };\n//# sourceMappingURL=prompts.js.map","import { messageToOpenAIRole } from \"./utils/misc.js\";\nimport { getEndpoint, isHeaders, normalizeHeaders } from \"./utils/azure.js\";\nimport { BaseChatOpenAI } from \"./chat_models/base.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\nimport { _convertMessagesToOpenAIParams } from \"./utils/message_inputs.js\";\nimport { ChatOpenAIResponses } from \"./chat_models/responses.js\";\nimport { ChatOpenAICompletions } from \"./chat_models/completions.js\";\nimport { ChatOpenAI } from \"./chat_models/index.js\";\nimport { AzureChatOpenAICompletions } from \"./azure/chat_models/completions.js\";\nimport { AzureChatOpenAIResponses } from \"./azure/chat_models/responses.js\";\nimport { AzureChatOpenAI } from \"./azure/chat_models/index.js\";\nimport { OpenAI } from \"./llms.js\";\nimport { AzureOpenAI } from \"./azure/llms.js\";\nimport { OpenAIEmbeddings } from \"./embeddings.js\";\nimport { AzureOpenAIEmbeddings } from \"./azure/embeddings.js\";\nimport { DallEAPIWrapper } from \"./tools/dalle.js\";\nimport \"./tools/index.js\";\nimport { customTool } from \"./tools/custom.js\";\nimport { convertPromptToOpenAI } from \"./utils/prompts.js\";\nimport { OpenAI as OpenAIClient, toFile } from \"openai\";\n\nexport { AzureChatOpenAI, AzureChatOpenAICompletions, AzureChatOpenAIResponses, AzureOpenAI, AzureOpenAIEmbeddings, BaseChatOpenAI, ChatOpenAI, ChatOpenAICompletions, ChatOpenAIResponses, DallEAPIWrapper, OpenAI, OpenAIClient, OpenAIEmbeddings, _convertMessagesToOpenAIParams, convertPromptToOpenAI, customTool, getEndpoint, isHeaders, messageToOpenAIRole, normalizeHeaders, toFile, wrapOpenAIClientError };","import { ChatOpenAI } from '@langchain/openai';\nimport { BaseChatModel } from '@langchain/core/language_models/chat_models';\nimport { ILLMProvider, ProviderConfig } from './provider.interface.js';\n\n/**\n * OpenAI GPT provider implementation\n */\nexport class OpenAIProvider implements ILLMProvider {\n public readonly name = 'openai';\n private readonly apiKey: string;\n\n constructor(apiKey?: string) {\n this.apiKey = apiKey || process.env.OPENAI_API_KEY || '';\n }\n\n public isConfigured(): boolean {\n return !!this.apiKey;\n }\n\n public getDefaultModel(): string {\n return 'gpt-4-turbo-preview';\n }\n\n public getChatModel(config: ProviderConfig = {}): BaseChatModel {\n if (!this.isConfigured()) {\n throw new Error('OpenAI API key is not configured');\n }\n\n return new ChatOpenAI({\n openAIApiKey: this.apiKey,\n modelName: config.model || this.getDefaultModel(),\n temperature: config.temperature ?? 0.2,\n maxTokens: config.maxTokens ?? 4000,\n });\n }\n}\n\n","import { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\n\n//#region src/utils/zod_to_genai_parameters.ts\nfunction removeAdditionalProperties(obj) {\n\tif (typeof obj === \"object\" && obj !== null) {\n\t\tconst newObj = { ...obj };\n\t\tif (\"additionalProperties\" in newObj) delete newObj.additionalProperties;\n\t\tif (\"$schema\" in newObj) delete newObj.$schema;\n\t\tif (\"strict\" in newObj) delete newObj.strict;\n\t\tfor (const key in newObj) if (key in newObj) {\n\t\t\tif (Array.isArray(newObj[key])) newObj[key] = newObj[key].map(removeAdditionalProperties);\n\t\t\telse if (typeof newObj[key] === \"object\" && newObj[key] !== null) newObj[key] = removeAdditionalProperties(newObj[key]);\n\t\t}\n\t\treturn newObj;\n\t}\n\treturn obj;\n}\nfunction schemaToGenerativeAIParameters(schema) {\n\tconst jsonSchema = removeAdditionalProperties(isInteropZodSchema(schema) ? toJsonSchema(schema) : schema);\n\tconst { $schema,...rest } = jsonSchema;\n\treturn rest;\n}\nfunction jsonSchemaToGeminiParameters(schema) {\n\tconst jsonSchema = removeAdditionalProperties(schema);\n\tconst { $schema,...rest } = jsonSchema;\n\treturn rest;\n}\n\n//#endregion\nexport { jsonSchemaToGeminiParameters, removeAdditionalProperties, schemaToGenerativeAIParameters };\n//# sourceMappingURL=zod_to_genai_parameters.js.map","import { randomUUID } from 'crypto';\nexport default { randomUUID };\n","import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n","import { jsonSchemaToGeminiParameters, schemaToGenerativeAIParameters } from \"./zod_to_genai_parameters.js\";\nimport { AIMessage, AIMessageChunk, ChatMessage, convertToProviderContentBlock, isAIMessage, isBaseMessage, isDataContentBlock, isToolMessage, parseBase64DataUrl } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk } from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { v4 } from \"uuid\";\n\n//#region src/utils/common.ts\nfunction getMessageAuthor(message) {\n\tconst type = message._getType();\n\tif (ChatMessage.isInstance(message)) return message.role;\n\tif (type === \"tool\") return type;\n\treturn message.name ?? type;\n}\n/**\n* Maps a message type to a Google Generative AI chat author.\n* @param message The message to map.\n* @param model The model to use for mapping.\n* @returns The message type mapped to a Google Generative AI chat author.\n*/\nfunction convertAuthorToRole(author) {\n\tswitch (author) {\n\t\tcase \"supervisor\":\n\t\tcase \"ai\":\n\t\tcase \"model\": return \"model\";\n\t\tcase \"system\": return \"system\";\n\t\tcase \"human\": return \"user\";\n\t\tcase \"tool\":\n\t\tcase \"function\": return \"function\";\n\t\tdefault: throw new Error(`Unknown / unsupported author: ${author}`);\n\t}\n}\nfunction messageContentMedia(content) {\n\tif (\"mimeType\" in content && \"data\" in content) return { inlineData: {\n\t\tmimeType: content.mimeType,\n\t\tdata: content.data\n\t} };\n\tif (\"mimeType\" in content && \"fileUri\" in content) return { fileData: {\n\t\tmimeType: content.mimeType,\n\t\tfileUri: content.fileUri\n\t} };\n\tthrow new Error(\"Invalid media content\");\n}\nfunction inferToolNameFromPreviousMessages(message, previousMessages) {\n\treturn previousMessages.map((msg) => {\n\t\tif (isAIMessage(msg)) return msg.tool_calls ?? [];\n\t\treturn [];\n\t}).flat().find((toolCall) => {\n\t\treturn toolCall.id === message.tool_call_id;\n\t})?.name;\n}\nfunction _getStandardContentBlockConverter(isMultimodalModel) {\n\tconst standardContentBlockConverter = {\n\t\tproviderName: \"Google Gemini\",\n\t\tfromStandardTextBlock(block) {\n\t\t\treturn { text: block.text };\n\t\t},\n\t\tfromStandardImageBlock(block) {\n\t\t\tif (!isMultimodalModel) throw new Error(\"This model does not support images\");\n\t\t\tif (block.source_type === \"url\") {\n\t\t\t\tconst data = parseBase64DataUrl({ dataUrl: block.url });\n\t\t\t\tif (data) return { inlineData: {\n\t\t\t\t\tmimeType: data.mime_type,\n\t\t\t\t\tdata: data.data\n\t\t\t\t} };\n\t\t\t\telse return { fileData: {\n\t\t\t\t\tmimeType: block.mime_type ?? \"\",\n\t\t\t\t\tfileUri: block.url\n\t\t\t\t} };\n\t\t\t}\n\t\t\tif (block.source_type === \"base64\") return { inlineData: {\n\t\t\t\tmimeType: block.mime_type ?? \"\",\n\t\t\t\tdata: block.data\n\t\t\t} };\n\t\t\tthrow new Error(`Unsupported source type: ${block.source_type}`);\n\t\t},\n\t\tfromStandardAudioBlock(block) {\n\t\t\tif (!isMultimodalModel) throw new Error(\"This model does not support audio\");\n\t\t\tif (block.source_type === \"url\") {\n\t\t\t\tconst data = parseBase64DataUrl({ dataUrl: block.url });\n\t\t\t\tif (data) return { inlineData: {\n\t\t\t\t\tmimeType: data.mime_type,\n\t\t\t\t\tdata: data.data\n\t\t\t\t} };\n\t\t\t\telse return { fileData: {\n\t\t\t\t\tmimeType: block.mime_type ?? \"\",\n\t\t\t\t\tfileUri: block.url\n\t\t\t\t} };\n\t\t\t}\n\t\t\tif (block.source_type === \"base64\") return { inlineData: {\n\t\t\t\tmimeType: block.mime_type ?? \"\",\n\t\t\t\tdata: block.data\n\t\t\t} };\n\t\t\tthrow new Error(`Unsupported source type: ${block.source_type}`);\n\t\t},\n\t\tfromStandardFileBlock(block) {\n\t\t\tif (!isMultimodalModel) throw new Error(\"This model does not support files\");\n\t\t\tif (block.source_type === \"text\") return { text: block.text };\n\t\t\tif (block.source_type === \"url\") {\n\t\t\t\tconst data = parseBase64DataUrl({ dataUrl: block.url });\n\t\t\t\tif (data) return { inlineData: {\n\t\t\t\t\tmimeType: data.mime_type,\n\t\t\t\t\tdata: data.data\n\t\t\t\t} };\n\t\t\t\telse return { fileData: {\n\t\t\t\t\tmimeType: block.mime_type ?? \"\",\n\t\t\t\t\tfileUri: block.url\n\t\t\t\t} };\n\t\t\t}\n\t\t\tif (block.source_type === \"base64\") return { inlineData: {\n\t\t\t\tmimeType: block.mime_type ?? \"\",\n\t\t\t\tdata: block.data\n\t\t\t} };\n\t\t\tthrow new Error(`Unsupported source type: ${block.source_type}`);\n\t\t}\n\t};\n\treturn standardContentBlockConverter;\n}\nfunction _convertLangChainContentToPart(content, isMultimodalModel) {\n\tif (isDataContentBlock(content)) return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel));\n\tif (content.type === \"text\") return { text: content.text };\n\telse if (content.type === \"executableCode\") return { executableCode: content.executableCode };\n\telse if (content.type === \"codeExecutionResult\") return { codeExecutionResult: content.codeExecutionResult };\n\telse if (content.type === \"image_url\") {\n\t\tif (!isMultimodalModel) throw new Error(`This model does not support images`);\n\t\tlet source;\n\t\tif (typeof content.image_url === \"string\") source = content.image_url;\n\t\telse if (typeof content.image_url === \"object\" && \"url\" in content.image_url) source = content.image_url.url;\n\t\telse throw new Error(\"Please provide image as base64 encoded data URL\");\n\t\tconst [dm, data] = source.split(\",\");\n\t\tif (!dm.startsWith(\"data:\")) throw new Error(\"Please provide image as base64 encoded data URL\");\n\t\tconst [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n\t\tif (encoding !== \"base64\") throw new Error(\"Please provide image as base64 encoded data URL\");\n\t\treturn { inlineData: {\n\t\t\tdata,\n\t\t\tmimeType\n\t\t} };\n\t} else if (content.type === \"media\") return messageContentMedia(content);\n\telse if (content.type === \"tool_use\") return { functionCall: {\n\t\tname: content.name,\n\t\targs: content.input\n\t} };\n\telse if (content.type?.includes(\"/\") && content.type.split(\"/\").length === 2 && \"data\" in content && typeof content.data === \"string\") return { inlineData: {\n\t\tmimeType: content.type,\n\t\tdata: content.data\n\t} };\n\telse if (\"functionCall\" in content) return void 0;\n\telse if (\"type\" in content) throw new Error(`Unknown content type ${content.type}`);\n\telse throw new Error(`Unknown content ${JSON.stringify(content)}`);\n}\nfunction convertMessageContentToParts(message, isMultimodalModel, previousMessages) {\n\tif (isToolMessage(message)) {\n\t\tconst messageName = message.name ?? inferToolNameFromPreviousMessages(message, previousMessages);\n\t\tif (messageName === void 0) throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`);\n\t\tconst result = Array.isArray(message.content) ? message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0) : message.content;\n\t\tif (message.status === \"error\") return [{ functionResponse: {\n\t\t\tname: messageName,\n\t\t\tresponse: { error: { details: result } }\n\t\t} }];\n\t\treturn [{ functionResponse: {\n\t\t\tname: messageName,\n\t\t\tresponse: { result }\n\t\t} }];\n\t}\n\tlet functionCalls = [];\n\tconst messageParts = [];\n\tif (typeof message.content === \"string\" && message.content) messageParts.push({ text: message.content });\n\tif (Array.isArray(message.content)) messageParts.push(...message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0));\n\tif (isAIMessage(message) && message.tool_calls?.length) functionCalls = message.tool_calls.map((tc) => {\n\t\treturn { functionCall: {\n\t\t\tname: tc.name,\n\t\t\targs: tc.args\n\t\t} };\n\t});\n\treturn [...messageParts, ...functionCalls];\n}\nfunction convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false) {\n\treturn messages.reduce((acc, message, index) => {\n\t\tif (!isBaseMessage(message)) throw new Error(\"Unsupported message input\");\n\t\tconst author = getMessageAuthor(message);\n\t\tif (author === \"system\" && index !== 0) throw new Error(\"System message should be the first one\");\n\t\tconst role = convertAuthorToRole(author);\n\t\tconst prevContent = acc.content[acc.content.length];\n\t\tif (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error(\"Google Generative AI requires alternate messages between authors\");\n\t\tconst parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index));\n\t\tif (acc.mergeWithPreviousContent) {\n\t\t\tconst prevContent$1 = acc.content[acc.content.length - 1];\n\t\t\tif (!prevContent$1) throw new Error(\"There was a problem parsing your system message. Please try a prompt without one.\");\n\t\t\tprevContent$1.parts.push(...parts);\n\t\t\treturn {\n\t\t\t\tmergeWithPreviousContent: false,\n\t\t\t\tcontent: acc.content\n\t\t\t};\n\t\t}\n\t\tlet actualRole = role;\n\t\tif (actualRole === \"function\" || actualRole === \"system\" && !convertSystemMessageToHumanContent) actualRole = \"user\";\n\t\tconst content = {\n\t\t\trole: actualRole,\n\t\t\tparts\n\t\t};\n\t\treturn {\n\t\t\tmergeWithPreviousContent: author === \"system\" && !convertSystemMessageToHumanContent,\n\t\t\tcontent: [...acc.content, content]\n\t\t};\n\t}, {\n\t\tcontent: [],\n\t\tmergeWithPreviousContent: false\n\t}).content;\n}\nfunction mapGenerateContentResultToChatResult(response, extra) {\n\tif (!response.candidates || response.candidates.length === 0 || !response.candidates[0]) return {\n\t\tgenerations: [],\n\t\tllmOutput: { filters: response.promptFeedback }\n\t};\n\tconst functionCalls = response.functionCalls();\n\tconst [candidate] = response.candidates;\n\tconst { content: candidateContent,...generationInfo } = candidate;\n\tlet content;\n\tif (Array.isArray(candidateContent?.parts) && candidateContent.parts.length === 1 && candidateContent.parts[0].text) content = candidateContent.parts[0].text;\n\telse if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length > 0) content = candidateContent.parts.map((p) => {\n\t\tif (\"text\" in p) return {\n\t\t\ttype: \"text\",\n\t\t\ttext: p.text\n\t\t};\n\t\telse if (\"inlineData\" in p) return {\n\t\t\ttype: \"inlineData\",\n\t\t\tinlineData: p.inlineData\n\t\t};\n\t\telse if (\"functionCall\" in p) return {\n\t\t\ttype: \"functionCall\",\n\t\t\tfunctionCall: p.functionCall\n\t\t};\n\t\telse if (\"functionResponse\" in p) return {\n\t\t\ttype: \"functionResponse\",\n\t\t\tfunctionResponse: p.functionResponse\n\t\t};\n\t\telse if (\"fileData\" in p) return {\n\t\t\ttype: \"fileData\",\n\t\t\tfileData: p.fileData\n\t\t};\n\t\telse if (\"executableCode\" in p) return {\n\t\t\ttype: \"executableCode\",\n\t\t\texecutableCode: p.executableCode\n\t\t};\n\t\telse if (\"codeExecutionResult\" in p) return {\n\t\t\ttype: \"codeExecutionResult\",\n\t\t\tcodeExecutionResult: p.codeExecutionResult\n\t\t};\n\t\treturn p;\n\t});\n\telse content = [];\n\tlet text = \"\";\n\tif (typeof content === \"string\") text = content;\n\telse if (Array.isArray(content) && content.length > 0) {\n\t\tconst block = content.find((b) => \"text\" in b);\n\t\ttext = block?.text ?? text;\n\t}\n\tconst generation = {\n\t\ttext,\n\t\tmessage: new AIMessage({\n\t\t\tcontent: content ?? \"\",\n\t\t\ttool_calls: functionCalls?.map((fc) => {\n\t\t\t\treturn {\n\t\t\t\t\t...fc,\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tid: \"id\" in fc && typeof fc.id === \"string\" ? fc.id : v4()\n\t\t\t\t};\n\t\t\t}),\n\t\t\tadditional_kwargs: { ...generationInfo },\n\t\t\tusage_metadata: extra?.usageMetadata\n\t\t}),\n\t\tgenerationInfo\n\t};\n\treturn {\n\t\tgenerations: [generation],\n\t\tllmOutput: { tokenUsage: {\n\t\t\tpromptTokens: extra?.usageMetadata?.input_tokens,\n\t\t\tcompletionTokens: extra?.usageMetadata?.output_tokens,\n\t\t\ttotalTokens: extra?.usageMetadata?.total_tokens\n\t\t} }\n\t};\n}\nfunction convertResponseContentToChatGenerationChunk(response, extra) {\n\tif (!response.candidates || response.candidates.length === 0) return null;\n\tconst functionCalls = response.functionCalls();\n\tconst [candidate] = response.candidates;\n\tconst { content: candidateContent,...generationInfo } = candidate;\n\tlet content;\n\tif (Array.isArray(candidateContent?.parts) && candidateContent.parts.every((p) => \"text\" in p)) content = candidateContent.parts.map((p) => p.text).join(\"\");\n\telse if (Array.isArray(candidateContent?.parts)) content = candidateContent.parts.map((p) => {\n\t\tif (\"text\" in p) return {\n\t\t\ttype: \"text\",\n\t\t\ttext: p.text\n\t\t};\n\t\telse if (\"inlineData\" in p) return {\n\t\t\ttype: \"inlineData\",\n\t\t\tinlineData: p.inlineData\n\t\t};\n\t\telse if (\"functionCall\" in p) return {\n\t\t\ttype: \"functionCall\",\n\t\t\tfunctionCall: p.functionCall\n\t\t};\n\t\telse if (\"functionResponse\" in p) return {\n\t\t\ttype: \"functionResponse\",\n\t\t\tfunctionResponse: p.functionResponse\n\t\t};\n\t\telse if (\"fileData\" in p) return {\n\t\t\ttype: \"fileData\",\n\t\t\tfileData: p.fileData\n\t\t};\n\t\telse if (\"executableCode\" in p) return {\n\t\t\ttype: \"executableCode\",\n\t\t\texecutableCode: p.executableCode\n\t\t};\n\t\telse if (\"codeExecutionResult\" in p) return {\n\t\t\ttype: \"codeExecutionResult\",\n\t\t\tcodeExecutionResult: p.codeExecutionResult\n\t\t};\n\t\treturn p;\n\t});\n\telse content = [];\n\tlet text = \"\";\n\tif (content && typeof content === \"string\") text = content;\n\telse if (Array.isArray(content)) {\n\t\tconst block = content.find((b) => \"text\" in b);\n\t\ttext = block?.text ?? \"\";\n\t}\n\tconst toolCallChunks = [];\n\tif (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({\n\t\t...fc,\n\t\targs: JSON.stringify(fc.args),\n\t\tindex: extra.index,\n\t\ttype: \"tool_call_chunk\",\n\t\tid: \"id\" in fc && typeof fc.id === \"string\" ? fc.id : v4()\n\t})));\n\treturn new ChatGenerationChunk({\n\t\ttext,\n\t\tmessage: new AIMessageChunk({\n\t\t\tcontent: content || \"\",\n\t\t\tname: !candidateContent ? void 0 : candidateContent.role,\n\t\t\ttool_call_chunks: toolCallChunks,\n\t\t\tadditional_kwargs: {},\n\t\t\tresponse_metadata: { model_provider: \"google-genai\" },\n\t\t\tusage_metadata: extra.usageMetadata\n\t\t}),\n\t\tgenerationInfo\n\t});\n}\nfunction convertToGenerativeAITools(tools) {\n\tif (tools.every((tool) => \"functionDeclarations\" in tool && Array.isArray(tool.functionDeclarations))) return tools;\n\treturn [{ functionDeclarations: tools.map((tool) => {\n\t\tif (isLangChainTool(tool)) {\n\t\t\tconst jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n\t\t\tif (jsonSchema.type === \"object\" && \"properties\" in jsonSchema && Object.keys(jsonSchema.properties).length === 0) return {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: jsonSchema\n\t\t\t};\n\t\t}\n\t\tif (isOpenAITool(tool)) return {\n\t\t\tname: tool.function.name,\n\t\t\tdescription: tool.function.description ?? `A function available to call.`,\n\t\t\tparameters: jsonSchemaToGeminiParameters(tool.function.parameters)\n\t\t};\n\t\treturn tool;\n\t}) }];\n}\n\n//#endregion\nexport { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, convertToGenerativeAITools, mapGenerateContentResultToChatResult };\n//# sourceMappingURL=common.js.map","import { interopSafeParseAsync } from \"@langchain/core/utils/types\";\nimport { BaseLLMOutputParser, OutputParserException } from \"@langchain/core/output_parsers\";\n\n//#region src/output_parsers.ts\nvar GoogleGenerativeAIToolsOutputParser = class extends BaseLLMOutputParser {\n\tstatic lc_name() {\n\t\treturn \"GoogleGenerativeAIToolsOutputParser\";\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"google_genai\",\n\t\t\"output_parsers\"\n\t];\n\treturnId = false;\n\t/** The type of tool calls to return. */\n\tkeyName;\n\t/** Whether to return only the first tool call. */\n\treturnSingle = false;\n\tzodSchema;\n\tconstructor(params) {\n\t\tsuper(params);\n\t\tthis.keyName = params.keyName;\n\t\tthis.returnSingle = params.returnSingle ?? this.returnSingle;\n\t\tthis.zodSchema = params.zodSchema;\n\t}\n\tasync _validateResult(result) {\n\t\tif (this.zodSchema === void 0) return result;\n\t\tconst zodParsedResult = await interopSafeParseAsync(this.zodSchema, result);\n\t\tif (zodParsedResult.success) return zodParsedResult.data;\n\t\telse throw new OutputParserException(`Failed to parse. Text: \"${JSON.stringify(result, null, 2)}\". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(result, null, 2));\n\t}\n\tasync parseResult(generations) {\n\t\tconst tools = generations.flatMap((generation) => {\n\t\t\tconst { message } = generation;\n\t\t\tif (!(\"tool_calls\" in message) || !Array.isArray(message.tool_calls)) return [];\n\t\t\treturn message.tool_calls;\n\t\t});\n\t\tif (tools[0] === void 0) throw new Error(\"No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.\");\n\t\tconst [tool] = tools;\n\t\tconst validatedResult = await this._validateResult(tool.args);\n\t\treturn validatedResult;\n\t}\n};\n\n//#endregion\nexport { GoogleGenerativeAIToolsOutputParser };\n//# sourceMappingURL=output_parsers.js.map","/**\n * Contains the list of OpenAPI data types\n * as defined by https://swagger.io/docs/specification/data-models/data-types/\n * @public\n */\nvar SchemaType;\n(function (SchemaType) {\n /** String type. */\n SchemaType[\"STRING\"] = \"string\";\n /** Number type. */\n SchemaType[\"NUMBER\"] = \"number\";\n /** Integer type. */\n SchemaType[\"INTEGER\"] = \"integer\";\n /** Boolean type. */\n SchemaType[\"BOOLEAN\"] = \"boolean\";\n /** Array type. */\n SchemaType[\"ARRAY\"] = \"array\";\n /** Object type. */\n SchemaType[\"OBJECT\"] = \"object\";\n})(SchemaType || (SchemaType = {}));\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @public\n */\nvar ExecutableCodeLanguage;\n(function (ExecutableCodeLanguage) {\n ExecutableCodeLanguage[\"LANGUAGE_UNSPECIFIED\"] = \"language_unspecified\";\n ExecutableCodeLanguage[\"PYTHON\"] = \"python\";\n})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));\n/**\n * Possible outcomes of code execution.\n * @public\n */\nvar Outcome;\n(function (Outcome) {\n /**\n * Unspecified status. This value should not be used.\n */\n Outcome[\"OUTCOME_UNSPECIFIED\"] = \"outcome_unspecified\";\n /**\n * Code execution completed successfully.\n */\n Outcome[\"OUTCOME_OK\"] = \"outcome_ok\";\n /**\n * Code execution finished but with a failure. `stderr` should contain the\n * reason.\n */\n Outcome[\"OUTCOME_FAILED\"] = \"outcome_failed\";\n /**\n * Code execution ran for too long, and was cancelled. There may or may not\n * be a partial output present.\n */\n Outcome[\"OUTCOME_DEADLINE_EXCEEDED\"] = \"outcome_deadline_exceeded\";\n})(Outcome || (Outcome = {}));\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Possible roles.\n * @public\n */\nconst POSSIBLE_ROLES = [\"user\", \"model\", \"function\", \"system\"];\n/**\n * Harm categories that would cause prompts or candidates to be blocked.\n * @public\n */\nvar HarmCategory;\n(function (HarmCategory) {\n HarmCategory[\"HARM_CATEGORY_UNSPECIFIED\"] = \"HARM_CATEGORY_UNSPECIFIED\";\n HarmCategory[\"HARM_CATEGORY_HATE_SPEECH\"] = \"HARM_CATEGORY_HATE_SPEECH\";\n HarmCategory[\"HARM_CATEGORY_SEXUALLY_EXPLICIT\"] = \"HARM_CATEGORY_SEXUALLY_EXPLICIT\";\n HarmCategory[\"HARM_CATEGORY_HARASSMENT\"] = \"HARM_CATEGORY_HARASSMENT\";\n HarmCategory[\"HARM_CATEGORY_DANGEROUS_CONTENT\"] = \"HARM_CATEGORY_DANGEROUS_CONTENT\";\n HarmCategory[\"HARM_CATEGORY_CIVIC_INTEGRITY\"] = \"HARM_CATEGORY_CIVIC_INTEGRITY\";\n})(HarmCategory || (HarmCategory = {}));\n/**\n * Threshold above which a prompt or candidate will be blocked.\n * @public\n */\nvar HarmBlockThreshold;\n(function (HarmBlockThreshold) {\n /** Threshold is unspecified. */\n HarmBlockThreshold[\"HARM_BLOCK_THRESHOLD_UNSPECIFIED\"] = \"HARM_BLOCK_THRESHOLD_UNSPECIFIED\";\n /** Content with NEGLIGIBLE will be allowed. */\n HarmBlockThreshold[\"BLOCK_LOW_AND_ABOVE\"] = \"BLOCK_LOW_AND_ABOVE\";\n /** Content with NEGLIGIBLE and LOW will be allowed. */\n HarmBlockThreshold[\"BLOCK_MEDIUM_AND_ABOVE\"] = \"BLOCK_MEDIUM_AND_ABOVE\";\n /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */\n HarmBlockThreshold[\"BLOCK_ONLY_HIGH\"] = \"BLOCK_ONLY_HIGH\";\n /** All content will be allowed. */\n HarmBlockThreshold[\"BLOCK_NONE\"] = \"BLOCK_NONE\";\n})(HarmBlockThreshold || (HarmBlockThreshold = {}));\n/**\n * Probability that a prompt or candidate matches a harm category.\n * @public\n */\nvar HarmProbability;\n(function (HarmProbability) {\n /** Probability is unspecified. */\n HarmProbability[\"HARM_PROBABILITY_UNSPECIFIED\"] = \"HARM_PROBABILITY_UNSPECIFIED\";\n /** Content has a negligible chance of being unsafe. */\n HarmProbability[\"NEGLIGIBLE\"] = \"NEGLIGIBLE\";\n /** Content has a low chance of being unsafe. */\n HarmProbability[\"LOW\"] = \"LOW\";\n /** Content has a medium chance of being unsafe. */\n HarmProbability[\"MEDIUM\"] = \"MEDIUM\";\n /** Content has a high chance of being unsafe. */\n HarmProbability[\"HIGH\"] = \"HIGH\";\n})(HarmProbability || (HarmProbability = {}));\n/**\n * Reason that a prompt was blocked.\n * @public\n */\nvar BlockReason;\n(function (BlockReason) {\n // A blocked reason was not specified.\n BlockReason[\"BLOCKED_REASON_UNSPECIFIED\"] = \"BLOCKED_REASON_UNSPECIFIED\";\n // Content was blocked by safety settings.\n BlockReason[\"SAFETY\"] = \"SAFETY\";\n // Content was blocked, but the reason is uncategorized.\n BlockReason[\"OTHER\"] = \"OTHER\";\n})(BlockReason || (BlockReason = {}));\n/**\n * Reason that a candidate finished.\n * @public\n */\nvar FinishReason;\n(function (FinishReason) {\n // Default value. This value is unused.\n FinishReason[\"FINISH_REASON_UNSPECIFIED\"] = \"FINISH_REASON_UNSPECIFIED\";\n // Natural stop point of the model or provided stop sequence.\n FinishReason[\"STOP\"] = \"STOP\";\n // The maximum number of tokens as specified in the request was reached.\n FinishReason[\"MAX_TOKENS\"] = \"MAX_TOKENS\";\n // The candidate content was flagged for safety reasons.\n FinishReason[\"SAFETY\"] = \"SAFETY\";\n // The candidate content was flagged for recitation reasons.\n FinishReason[\"RECITATION\"] = \"RECITATION\";\n // The candidate content was flagged for using an unsupported language.\n FinishReason[\"LANGUAGE\"] = \"LANGUAGE\";\n // Token generation stopped because the content contains forbidden terms.\n FinishReason[\"BLOCKLIST\"] = \"BLOCKLIST\";\n // Token generation stopped for potentially containing prohibited content.\n FinishReason[\"PROHIBITED_CONTENT\"] = \"PROHIBITED_CONTENT\";\n // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n FinishReason[\"SPII\"] = \"SPII\";\n // The function call generated by the model is invalid.\n FinishReason[\"MALFORMED_FUNCTION_CALL\"] = \"MALFORMED_FUNCTION_CALL\";\n // Unknown reason.\n FinishReason[\"OTHER\"] = \"OTHER\";\n})(FinishReason || (FinishReason = {}));\n/**\n * Task type for embedding content.\n * @public\n */\nvar TaskType;\n(function (TaskType) {\n TaskType[\"TASK_TYPE_UNSPECIFIED\"] = \"TASK_TYPE_UNSPECIFIED\";\n TaskType[\"RETRIEVAL_QUERY\"] = \"RETRIEVAL_QUERY\";\n TaskType[\"RETRIEVAL_DOCUMENT\"] = \"RETRIEVAL_DOCUMENT\";\n TaskType[\"SEMANTIC_SIMILARITY\"] = \"SEMANTIC_SIMILARITY\";\n TaskType[\"CLASSIFICATION\"] = \"CLASSIFICATION\";\n TaskType[\"CLUSTERING\"] = \"CLUSTERING\";\n})(TaskType || (TaskType = {}));\n/**\n * @public\n */\nvar FunctionCallingMode;\n(function (FunctionCallingMode) {\n // Unspecified function calling mode. This value should not be used.\n FunctionCallingMode[\"MODE_UNSPECIFIED\"] = \"MODE_UNSPECIFIED\";\n // Default model behavior, model decides to predict either a function call\n // or a natural language repspose.\n FunctionCallingMode[\"AUTO\"] = \"AUTO\";\n // Model is constrained to always predicting a function call only.\n // If \"allowed_function_names\" are set, the predicted function call will be\n // limited to any one of \"allowed_function_names\", else the predicted\n // function call will be any one of the provided \"function_declarations\".\n FunctionCallingMode[\"ANY\"] = \"ANY\";\n // Model will not predict any function call. Model behavior is same as when\n // not passing any function declarations.\n FunctionCallingMode[\"NONE\"] = \"NONE\";\n})(FunctionCallingMode || (FunctionCallingMode = {}));\n/**\n * The mode of the predictor to be used in dynamic retrieval.\n * @public\n */\nvar DynamicRetrievalMode;\n(function (DynamicRetrievalMode) {\n // Unspecified function calling mode. This value should not be used.\n DynamicRetrievalMode[\"MODE_UNSPECIFIED\"] = \"MODE_UNSPECIFIED\";\n // Run retrieval only when system decides it is necessary.\n DynamicRetrievalMode[\"MODE_DYNAMIC\"] = \"MODE_DYNAMIC\";\n})(DynamicRetrievalMode || (DynamicRetrievalMode = {}));\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Basic error type for this SDK.\n * @public\n */\nclass GoogleGenerativeAIError extends Error {\n constructor(message) {\n super(`[GoogleGenerativeAI Error]: ${message}`);\n }\n}\n/**\n * Errors in the contents of a response from the model. This includes parsing\n * errors, or responses including a safety block reason.\n * @public\n */\nclass GoogleGenerativeAIResponseError extends GoogleGenerativeAIError {\n constructor(message, response) {\n super(message);\n this.response = response;\n }\n}\n/**\n * Error class covering HTTP errors when calling the server. Includes HTTP\n * status, statusText, and optional details, if provided in the server response.\n * @public\n */\nclass GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {\n constructor(message, status, statusText, errorDetails) {\n super(message);\n this.status = status;\n this.statusText = statusText;\n this.errorDetails = errorDetails;\n }\n}\n/**\n * Errors in the contents of a request originating from user input.\n * @public\n */\nclass GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {\n}\n/**\n * Error thrown when a request is aborted, either due to a timeout or\n * intentional cancellation by the user.\n * @public\n */\nclass GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com\";\nconst DEFAULT_API_VERSION = \"v1beta\";\n/**\n * We can't `require` package.json if this runs on web. We will use rollup to\n * swap in the version number here at build time.\n */\nconst PACKAGE_VERSION = \"0.24.1\";\nconst PACKAGE_LOG_HEADER = \"genai-js\";\nvar Task;\n(function (Task) {\n Task[\"GENERATE_CONTENT\"] = \"generateContent\";\n Task[\"STREAM_GENERATE_CONTENT\"] = \"streamGenerateContent\";\n Task[\"COUNT_TOKENS\"] = \"countTokens\";\n Task[\"EMBED_CONTENT\"] = \"embedContent\";\n Task[\"BATCH_EMBED_CONTENTS\"] = \"batchEmbedContents\";\n})(Task || (Task = {}));\nclass RequestUrl {\n constructor(model, task, apiKey, stream, requestOptions) {\n this.model = model;\n this.task = task;\n this.apiKey = apiKey;\n this.stream = stream;\n this.requestOptions = requestOptions;\n }\n toString() {\n var _a, _b;\n const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;\n const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;\n let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;\n if (this.stream) {\n url += \"?alt=sse\";\n }\n return url;\n }\n}\n/**\n * Simple, but may become more complex if we add more versions to log.\n */\nfunction getClientHeaders(requestOptions) {\n const clientHeaders = [];\n if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {\n clientHeaders.push(requestOptions.apiClient);\n }\n clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);\n return clientHeaders.join(\" \");\n}\nasync function getHeaders(url) {\n var _a;\n const headers = new Headers();\n headers.append(\"Content-Type\", \"application/json\");\n headers.append(\"x-goog-api-client\", getClientHeaders(url.requestOptions));\n headers.append(\"x-goog-api-key\", url.apiKey);\n let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;\n if (customHeaders) {\n if (!(customHeaders instanceof Headers)) {\n try {\n customHeaders = new Headers(customHeaders);\n }\n catch (e) {\n throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);\n }\n }\n for (const [headerName, headerValue] of customHeaders.entries()) {\n if (headerName === \"x-goog-api-key\") {\n throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);\n }\n else if (headerName === \"x-goog-api-client\") {\n throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);\n }\n headers.append(headerName, headerValue);\n }\n }\n return headers;\n}\nasync function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {\n const url = new RequestUrl(model, task, apiKey, stream, requestOptions);\n return {\n url: url.toString(),\n fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: \"POST\", headers: await getHeaders(url), body }),\n };\n}\nasync function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, \n// Allows this to be stubbed for tests\nfetchFn = fetch) {\n const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);\n return makeRequest(url, fetchOptions, fetchFn);\n}\nasync function makeRequest(url, fetchOptions, fetchFn = fetch) {\n let response;\n try {\n response = await fetchFn(url, fetchOptions);\n }\n catch (e) {\n handleResponseError(e, url);\n }\n if (!response.ok) {\n await handleResponseNotOk(response, url);\n }\n return response;\n}\nfunction handleResponseError(e, url) {\n let err = e;\n if (err.name === \"AbortError\") {\n err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);\n err.stack = e.stack;\n }\n else if (!(e instanceof GoogleGenerativeAIFetchError ||\n e instanceof GoogleGenerativeAIRequestInputError)) {\n err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);\n err.stack = e.stack;\n }\n throw err;\n}\nasync function handleResponseNotOk(response, url) {\n let message = \"\";\n let errorDetails;\n try {\n const json = await response.json();\n message = json.error.message;\n if (json.error.details) {\n message += ` ${JSON.stringify(json.error.details)}`;\n errorDetails = json.error.details;\n }\n }\n catch (e) {\n // ignored\n }\n throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);\n}\n/**\n * Generates the request options to be passed to the fetch API.\n * @param requestOptions - The user-defined request options.\n * @returns The generated request options.\n */\nfunction buildFetchOptions(requestOptions) {\n const fetchOptions = {};\n if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {\n const controller = new AbortController();\n if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {\n setTimeout(() => controller.abort(), requestOptions.timeout);\n }\n if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {\n requestOptions.signal.addEventListener(\"abort\", () => {\n controller.abort();\n });\n }\n fetchOptions.signal = controller.signal;\n }\n return fetchOptions;\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Adds convenience helper methods to a response object, including stream\n * chunks (as long as each chunk is a complete GenerateContentResponse JSON).\n */\nfunction addHelpers(response) {\n response.text = () => {\n if (response.candidates && response.candidates.length > 0) {\n if (response.candidates.length > 1) {\n console.warn(`This response had ${response.candidates.length} ` +\n `candidates. Returning text from the first candidate only. ` +\n `Access response.candidates directly to use the other candidates.`);\n }\n if (hadBadFinishReason(response.candidates[0])) {\n throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);\n }\n return getText(response);\n }\n else if (response.promptFeedback) {\n throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);\n }\n return \"\";\n };\n /**\n * TODO: remove at next major version\n */\n response.functionCall = () => {\n if (response.candidates && response.candidates.length > 0) {\n if (response.candidates.length > 1) {\n console.warn(`This response had ${response.candidates.length} ` +\n `candidates. Returning function calls from the first candidate only. ` +\n `Access response.candidates directly to use the other candidates.`);\n }\n if (hadBadFinishReason(response.candidates[0])) {\n throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);\n }\n console.warn(`response.functionCall() is deprecated. ` +\n `Use response.functionCalls() instead.`);\n return getFunctionCalls(response)[0];\n }\n else if (response.promptFeedback) {\n throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);\n }\n return undefined;\n };\n response.functionCalls = () => {\n if (response.candidates && response.candidates.length > 0) {\n if (response.candidates.length > 1) {\n console.warn(`This response had ${response.candidates.length} ` +\n `candidates. Returning function calls from the first candidate only. ` +\n `Access response.candidates directly to use the other candidates.`);\n }\n if (hadBadFinishReason(response.candidates[0])) {\n throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);\n }\n return getFunctionCalls(response);\n }\n else if (response.promptFeedback) {\n throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);\n }\n return undefined;\n };\n return response;\n}\n/**\n * Returns all text found in all parts of first candidate.\n */\nfunction getText(response) {\n var _a, _b, _c, _d;\n const textStrings = [];\n if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {\n for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {\n if (part.text) {\n textStrings.push(part.text);\n }\n if (part.executableCode) {\n textStrings.push(\"\\n```\" +\n part.executableCode.language +\n \"\\n\" +\n part.executableCode.code +\n \"\\n```\\n\");\n }\n if (part.codeExecutionResult) {\n textStrings.push(\"\\n```\\n\" + part.codeExecutionResult.output + \"\\n```\\n\");\n }\n }\n }\n if (textStrings.length > 0) {\n return textStrings.join(\"\");\n }\n else {\n return \"\";\n }\n}\n/**\n * Returns functionCall of first candidate.\n */\nfunction getFunctionCalls(response) {\n var _a, _b, _c, _d;\n const functionCalls = [];\n if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {\n for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {\n if (part.functionCall) {\n functionCalls.push(part.functionCall);\n }\n }\n }\n if (functionCalls.length > 0) {\n return functionCalls;\n }\n else {\n return undefined;\n }\n}\nconst badFinishReasons = [\n FinishReason.RECITATION,\n FinishReason.SAFETY,\n FinishReason.LANGUAGE,\n];\nfunction hadBadFinishReason(candidate) {\n return (!!candidate.finishReason &&\n badFinishReasons.includes(candidate.finishReason));\n}\nfunction formatBlockErrorMessage(response) {\n var _a, _b, _c;\n let message = \"\";\n if ((!response.candidates || response.candidates.length === 0) &&\n response.promptFeedback) {\n message += \"Response was blocked\";\n if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {\n message += ` due to ${response.promptFeedback.blockReason}`;\n }\n if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {\n message += `: ${response.promptFeedback.blockReasonMessage}`;\n }\n }\n else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {\n const firstCandidate = response.candidates[0];\n if (hadBadFinishReason(firstCandidate)) {\n message += `Candidate was blocked due to ${firstCandidate.finishReason}`;\n if (firstCandidate.finishMessage) {\n message += `: ${firstCandidate.finishMessage}`;\n }\n }\n }\n return message;\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\n\r\nfunction __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nfunction __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst responseLineRE = /^data\\: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n/**\n * Process a response.body stream from the backend and return an\n * iterator that provides one complete GenerateContentResponse at a time\n * and a promise that resolves with a single aggregated\n * GenerateContentResponse.\n *\n * @param response - Response from a fetch call\n */\nfunction processStream(response) {\n const inputStream = response.body.pipeThrough(new TextDecoderStream(\"utf8\", { fatal: true }));\n const responseStream = getResponseStream(inputStream);\n const [stream1, stream2] = responseStream.tee();\n return {\n stream: generateResponseSequence(stream1),\n response: getResponsePromise(stream2),\n };\n}\nasync function getResponsePromise(stream) {\n const allResponses = [];\n const reader = stream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return addHelpers(aggregateResponses(allResponses));\n }\n allResponses.push(value);\n }\n}\nfunction generateResponseSequence(stream) {\n return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {\n const reader = stream.getReader();\n while (true) {\n const { value, done } = yield __await(reader.read());\n if (done) {\n break;\n }\n yield yield __await(addHelpers(value));\n }\n });\n}\n/**\n * Reads a raw stream from the fetch response and join incomplete\n * chunks, returning a new stream that provides a single complete\n * GenerateContentResponse in each iteration.\n */\nfunction getResponseStream(inputStream) {\n const reader = inputStream.getReader();\n const stream = new ReadableStream({\n start(controller) {\n let currentText = \"\";\n return pump();\n function pump() {\n return reader\n .read()\n .then(({ value, done }) => {\n if (done) {\n if (currentText.trim()) {\n controller.error(new GoogleGenerativeAIError(\"Failed to parse stream\"));\n return;\n }\n controller.close();\n return;\n }\n currentText += value;\n let match = currentText.match(responseLineRE);\n let parsedResponse;\n while (match) {\n try {\n parsedResponse = JSON.parse(match[1]);\n }\n catch (e) {\n controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: \"${match[1]}\"`));\n return;\n }\n controller.enqueue(parsedResponse);\n currentText = currentText.substring(match[0].length);\n match = currentText.match(responseLineRE);\n }\n return pump();\n })\n .catch((e) => {\n let err = e;\n err.stack = e.stack;\n if (err.name === \"AbortError\") {\n err = new GoogleGenerativeAIAbortError(\"Request aborted when reading from the stream\");\n }\n else {\n err = new GoogleGenerativeAIError(\"Error reading from the stream\");\n }\n throw err;\n });\n }\n },\n });\n return stream;\n}\n/**\n * Aggregates an array of `GenerateContentResponse`s into a single\n * GenerateContentResponse.\n */\nfunction aggregateResponses(responses) {\n const lastResponse = responses[responses.length - 1];\n const aggregatedResponse = {\n promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback,\n };\n for (const response of responses) {\n if (response.candidates) {\n let candidateIndex = 0;\n for (const candidate of response.candidates) {\n if (!aggregatedResponse.candidates) {\n aggregatedResponse.candidates = [];\n }\n if (!aggregatedResponse.candidates[candidateIndex]) {\n aggregatedResponse.candidates[candidateIndex] = {\n index: candidateIndex,\n };\n }\n // Keep overwriting, the last one will be final\n aggregatedResponse.candidates[candidateIndex].citationMetadata =\n candidate.citationMetadata;\n aggregatedResponse.candidates[candidateIndex].groundingMetadata =\n candidate.groundingMetadata;\n aggregatedResponse.candidates[candidateIndex].finishReason =\n candidate.finishReason;\n aggregatedResponse.candidates[candidateIndex].finishMessage =\n candidate.finishMessage;\n aggregatedResponse.candidates[candidateIndex].safetyRatings =\n candidate.safetyRatings;\n /**\n * Candidates should always have content and parts, but this handles\n * possible malformed responses.\n */\n if (candidate.content && candidate.content.parts) {\n if (!aggregatedResponse.candidates[candidateIndex].content) {\n aggregatedResponse.candidates[candidateIndex].content = {\n role: candidate.content.role || \"user\",\n parts: [],\n };\n }\n const newPart = {};\n for (const part of candidate.content.parts) {\n if (part.text) {\n newPart.text = part.text;\n }\n if (part.functionCall) {\n newPart.functionCall = part.functionCall;\n }\n if (part.executableCode) {\n newPart.executableCode = part.executableCode;\n }\n if (part.codeExecutionResult) {\n newPart.codeExecutionResult = part.codeExecutionResult;\n }\n if (Object.keys(newPart).length === 0) {\n newPart.text = \"\";\n }\n aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart);\n }\n }\n }\n candidateIndex++;\n }\n if (response.usageMetadata) {\n aggregatedResponse.usageMetadata = response.usageMetadata;\n }\n }\n return aggregatedResponse;\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function generateContentStream(apiKey, model, params, requestOptions) {\n const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, \n /* stream */ true, JSON.stringify(params), requestOptions);\n return processStream(response);\n}\nasync function generateContent(apiKey, model, params, requestOptions) {\n const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, \n /* stream */ false, JSON.stringify(params), requestOptions);\n const responseJson = await response.json();\n const enhancedResponse = addHelpers(responseJson);\n return {\n response: enhancedResponse,\n };\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction formatSystemInstruction(input) {\n // null or undefined\n if (input == null) {\n return undefined;\n }\n else if (typeof input === \"string\") {\n return { role: \"system\", parts: [{ text: input }] };\n }\n else if (input.text) {\n return { role: \"system\", parts: [input] };\n }\n else if (input.parts) {\n if (!input.role) {\n return { role: \"system\", parts: input.parts };\n }\n else {\n return input;\n }\n }\n}\nfunction formatNewContent(request) {\n let newParts = [];\n if (typeof request === \"string\") {\n newParts = [{ text: request }];\n }\n else {\n for (const partOrString of request) {\n if (typeof partOrString === \"string\") {\n newParts.push({ text: partOrString });\n }\n else {\n newParts.push(partOrString);\n }\n }\n }\n return assignRoleToPartsAndValidateSendMessageRequest(newParts);\n}\n/**\n * When multiple Part types (i.e. FunctionResponsePart and TextPart) are\n * passed in a single Part array, we may need to assign different roles to each\n * part. Currently only FunctionResponsePart requires a role other than 'user'.\n * @private\n * @param parts Array of parts to pass to the model\n * @returns Array of content items\n */\nfunction assignRoleToPartsAndValidateSendMessageRequest(parts) {\n const userContent = { role: \"user\", parts: [] };\n const functionContent = { role: \"function\", parts: [] };\n let hasUserContent = false;\n let hasFunctionContent = false;\n for (const part of parts) {\n if (\"functionResponse\" in part) {\n functionContent.parts.push(part);\n hasFunctionContent = true;\n }\n else {\n userContent.parts.push(part);\n hasUserContent = true;\n }\n }\n if (hasUserContent && hasFunctionContent) {\n throw new GoogleGenerativeAIError(\"Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.\");\n }\n if (!hasUserContent && !hasFunctionContent) {\n throw new GoogleGenerativeAIError(\"No content is provided for sending chat message.\");\n }\n if (hasUserContent) {\n return userContent;\n }\n return functionContent;\n}\nfunction formatCountTokensInput(params, modelParams) {\n var _a;\n let formattedGenerateContentRequest = {\n model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,\n generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,\n safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,\n tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,\n toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,\n systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,\n cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name,\n contents: [],\n };\n const containsGenerateContentRequest = params.generateContentRequest != null;\n if (params.contents) {\n if (containsGenerateContentRequest) {\n throw new GoogleGenerativeAIRequestInputError(\"CountTokensRequest must have one of contents or generateContentRequest, not both.\");\n }\n formattedGenerateContentRequest.contents = params.contents;\n }\n else if (containsGenerateContentRequest) {\n formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);\n }\n else {\n // Array or string\n const content = formatNewContent(params);\n formattedGenerateContentRequest.contents = [content];\n }\n return { generateContentRequest: formattedGenerateContentRequest };\n}\nfunction formatGenerateContentInput(params) {\n let formattedRequest;\n if (params.contents) {\n formattedRequest = params;\n }\n else {\n // Array or string\n const content = formatNewContent(params);\n formattedRequest = { contents: [content] };\n }\n if (params.systemInstruction) {\n formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);\n }\n return formattedRequest;\n}\nfunction formatEmbedContentInput(params) {\n if (typeof params === \"string\" || Array.isArray(params)) {\n const content = formatNewContent(params);\n return { content };\n }\n return params;\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// https://ai.google.dev/api/rest/v1beta/Content#part\nconst VALID_PART_FIELDS = [\n \"text\",\n \"inlineData\",\n \"functionCall\",\n \"functionResponse\",\n \"executableCode\",\n \"codeExecutionResult\",\n];\nconst VALID_PARTS_PER_ROLE = {\n user: [\"text\", \"inlineData\"],\n function: [\"functionResponse\"],\n model: [\"text\", \"functionCall\", \"executableCode\", \"codeExecutionResult\"],\n // System instructions shouldn't be in history anyway.\n system: [\"text\"],\n};\nfunction validateChatHistory(history) {\n let prevContent = false;\n for (const currContent of history) {\n const { role, parts } = currContent;\n if (!prevContent && role !== \"user\") {\n throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);\n }\n if (!POSSIBLE_ROLES.includes(role)) {\n throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);\n }\n if (!Array.isArray(parts)) {\n throw new GoogleGenerativeAIError(\"Content should have 'parts' property with an array of Parts\");\n }\n if (parts.length === 0) {\n throw new GoogleGenerativeAIError(\"Each Content should have at least one part\");\n }\n const countFields = {\n text: 0,\n inlineData: 0,\n functionCall: 0,\n functionResponse: 0,\n fileData: 0,\n executableCode: 0,\n codeExecutionResult: 0,\n };\n for (const part of parts) {\n for (const key of VALID_PART_FIELDS) {\n if (key in part) {\n countFields[key] += 1;\n }\n }\n }\n const validParts = VALID_PARTS_PER_ROLE[role];\n for (const key of VALID_PART_FIELDS) {\n if (!validParts.includes(key) && countFields[key] > 0) {\n throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);\n }\n }\n prevContent = true;\n }\n}\n/**\n * Returns true if the response is valid (could be appended to the history), flase otherwise.\n */\nfunction isValidResponse(response) {\n var _a;\n if (response.candidates === undefined || response.candidates.length === 0) {\n return false;\n }\n const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content;\n if (content === undefined) {\n return false;\n }\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (part.text !== undefined && part.text === \"\") {\n return false;\n }\n }\n return true;\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Do not log a message for this error.\n */\nconst SILENT_ERROR = \"SILENT_ERROR\";\n/**\n * ChatSession class that enables sending chat messages and stores\n * history of sent and received messages so far.\n *\n * @public\n */\nclass ChatSession {\n constructor(apiKey, model, params, _requestOptions = {}) {\n this.model = model;\n this.params = params;\n this._requestOptions = _requestOptions;\n this._history = [];\n this._sendPromise = Promise.resolve();\n this._apiKey = apiKey;\n if (params === null || params === void 0 ? void 0 : params.history) {\n validateChatHistory(params.history);\n this._history = params.history;\n }\n }\n /**\n * Gets the chat history so far. Blocked prompts are not added to history.\n * Blocked candidates are not added to history, nor are the prompts that\n * generated them.\n */\n async getHistory() {\n await this._sendPromise;\n return this._history;\n }\n /**\n * Sends a chat message and receives a non-streaming\n * {@link GenerateContentResult}.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async sendMessage(request, requestOptions = {}) {\n var _a, _b, _c, _d, _e, _f;\n await this._sendPromise;\n const newContent = formatNewContent(request);\n const generateContentRequest = {\n safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,\n generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,\n tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,\n toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,\n systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,\n cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,\n contents: [...this._history, newContent],\n };\n const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n let finalResult;\n // Add onto the chain.\n this._sendPromise = this._sendPromise\n .then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions))\n .then((result) => {\n var _a;\n if (isValidResponse(result.response)) {\n this._history.push(newContent);\n const responseContent = Object.assign({ parts: [], \n // Response seems to come back without a role set.\n role: \"model\" }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content);\n this._history.push(responseContent);\n }\n else {\n const blockErrorMessage = formatBlockErrorMessage(result.response);\n if (blockErrorMessage) {\n console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);\n }\n }\n finalResult = result;\n })\n .catch((e) => {\n // Resets _sendPromise to avoid subsequent calls failing and throw error.\n this._sendPromise = Promise.resolve();\n throw e;\n });\n await this._sendPromise;\n return finalResult;\n }\n /**\n * Sends a chat message and receives the response as a\n * {@link GenerateContentStreamResult} containing an iterable stream\n * and a response promise.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async sendMessageStream(request, requestOptions = {}) {\n var _a, _b, _c, _d, _e, _f;\n await this._sendPromise;\n const newContent = formatNewContent(request);\n const generateContentRequest = {\n safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,\n generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,\n tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,\n toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,\n systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,\n cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,\n contents: [...this._history, newContent],\n };\n const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);\n // Add onto the chain.\n this._sendPromise = this._sendPromise\n .then(() => streamPromise)\n // This must be handled to avoid unhandled rejection, but jump\n // to the final catch block with a label to not log this error.\n .catch((_ignored) => {\n throw new Error(SILENT_ERROR);\n })\n .then((streamResult) => streamResult.response)\n .then((response) => {\n if (isValidResponse(response)) {\n this._history.push(newContent);\n const responseContent = Object.assign({}, response.candidates[0].content);\n // Response seems to come back without a role set.\n if (!responseContent.role) {\n responseContent.role = \"model\";\n }\n this._history.push(responseContent);\n }\n else {\n const blockErrorMessage = formatBlockErrorMessage(response);\n if (blockErrorMessage) {\n console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);\n }\n }\n })\n .catch((e) => {\n // Errors in streamPromise are already catchable by the user as\n // streamPromise is returned.\n // Avoid duplicating the error message in logs.\n if (e.message !== SILENT_ERROR) {\n // Users do not have access to _sendPromise to catch errors\n // downstream from streamPromise, so they should not throw.\n console.error(e);\n }\n });\n return streamPromise;\n }\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function countTokens(apiKey, model, params, singleRequestOptions) {\n const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);\n return response.json();\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function embedContent(apiKey, model, params, requestOptions) {\n const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);\n return response.json();\n}\nasync function batchEmbedContents(apiKey, model, params, requestOptions) {\n const requestsWithModel = params.requests.map((request) => {\n return Object.assign(Object.assign({}, request), { model });\n });\n const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions);\n return response.json();\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Class for generative model APIs.\n * @public\n */\nclass GenerativeModel {\n constructor(apiKey, modelParams, _requestOptions = {}) {\n this.apiKey = apiKey;\n this._requestOptions = _requestOptions;\n if (modelParams.model.includes(\"/\")) {\n // Models may be named \"models/model-name\" or \"tunedModels/model-name\"\n this.model = modelParams.model;\n }\n else {\n // If path is not included, assume it's a non-tuned model.\n this.model = `models/${modelParams.model}`;\n }\n this.generationConfig = modelParams.generationConfig || {};\n this.safetySettings = modelParams.safetySettings || [];\n this.tools = modelParams.tools;\n this.toolConfig = modelParams.toolConfig;\n this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);\n this.cachedContent = modelParams.cachedContent;\n }\n /**\n * Makes a single non-streaming call to the model\n * and returns an object containing a single {@link GenerateContentResponse}.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async generateContent(request, requestOptions = {}) {\n var _a;\n const formattedParams = formatGenerateContentInput(request);\n const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);\n }\n /**\n * Makes a single streaming call to the model and returns an object\n * containing an iterable stream that iterates over all chunks in the\n * streaming response as well as a promise that returns the final\n * aggregated response.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async generateContentStream(request, requestOptions = {}) {\n var _a;\n const formattedParams = formatGenerateContentInput(request);\n const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);\n }\n /**\n * Gets a new {@link ChatSession} instance which can be used for\n * multi-turn chats.\n */\n startChat(startChatParams) {\n var _a;\n return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions);\n }\n /**\n * Counts the tokens in the provided request.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async countTokens(request, requestOptions = {}) {\n const formattedParams = formatCountTokensInput(request, {\n model: this.model,\n generationConfig: this.generationConfig,\n safetySettings: this.safetySettings,\n tools: this.tools,\n toolConfig: this.toolConfig,\n systemInstruction: this.systemInstruction,\n cachedContent: this.cachedContent,\n });\n const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);\n }\n /**\n * Embeds the provided content.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async embedContent(request, requestOptions = {}) {\n const formattedParams = formatEmbedContentInput(request);\n const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);\n }\n /**\n * Embeds an array of {@link EmbedContentRequest}s.\n *\n * Fields set in the optional {@link SingleRequestOptions} parameter will\n * take precedence over the {@link RequestOptions} values provided to\n * {@link GoogleGenerativeAI.getGenerativeModel }.\n */\n async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {\n const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);\n }\n}\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Top-level class for this SDK\n * @public\n */\nclass GoogleGenerativeAI {\n constructor(apiKey) {\n this.apiKey = apiKey;\n }\n /**\n * Gets a {@link GenerativeModel} instance for the provided model name.\n */\n getGenerativeModel(modelParams, requestOptions) {\n if (!modelParams.model) {\n throw new GoogleGenerativeAIError(`Must provide a model name. ` +\n `Example: genai.getGenerativeModel({ model: 'my-model-name' })`);\n }\n return new GenerativeModel(this.apiKey, modelParams, requestOptions);\n }\n /**\n * Creates a {@link GenerativeModel} instance from provided content cache.\n */\n getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {\n if (!cachedContent.name) {\n throw new GoogleGenerativeAIRequestInputError(\"Cached content must contain a `name` field.\");\n }\n if (!cachedContent.model) {\n throw new GoogleGenerativeAIRequestInputError(\"Cached content must contain a `model` field.\");\n }\n /**\n * Not checking tools and toolConfig for now as it would require a deep\n * equality comparison and isn't likely to be a common case.\n */\n const disallowedDuplicates = [\"model\", \"systemInstruction\"];\n for (const key of disallowedDuplicates) {\n if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) &&\n cachedContent[key] &&\n (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {\n if (key === \"model\") {\n const modelParamsComp = modelParams.model.startsWith(\"models/\")\n ? modelParams.model.replace(\"models/\", \"\")\n : modelParams.model;\n const cachedContentComp = cachedContent.model.startsWith(\"models/\")\n ? cachedContent.model.replace(\"models/\", \"\")\n : cachedContent.model;\n if (modelParamsComp === cachedContentComp) {\n continue;\n }\n }\n throw new GoogleGenerativeAIRequestInputError(`Different value for \"${key}\" specified in modelParams` +\n ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);\n }\n }\n const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent });\n return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);\n }\n}\n\nexport { BlockReason, ChatSession, DynamicRetrievalMode, ExecutableCodeLanguage, FinishReason, FunctionCallingMode, GenerativeModel, GoogleGenerativeAI, GoogleGenerativeAIAbortError, GoogleGenerativeAIError, GoogleGenerativeAIFetchError, GoogleGenerativeAIRequestInputError, GoogleGenerativeAIResponseError, HarmBlockThreshold, HarmCategory, HarmProbability, Outcome, POSSIBLE_ROLES, SchemaType, TaskType };\n//# sourceMappingURL=index.mjs.map\n","import { removeAdditionalProperties } from \"./zod_to_genai_parameters.js\";\nimport { convertToGenerativeAITools } from \"./common.js\";\nimport { FunctionCallingMode } from \"@google/generative-ai\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\n\n//#region src/utils/tools.ts\nfunction convertToolsToGenAI(tools, extra) {\n\tconst genAITools = processTools(tools);\n\tconst toolConfig = createToolConfig(genAITools, extra);\n\treturn {\n\t\ttools: genAITools,\n\t\ttoolConfig\n\t};\n}\nfunction processTools(tools) {\n\tlet functionDeclarationTools = [];\n\tconst genAITools = [];\n\ttools.forEach((tool) => {\n\t\tif (isLangChainTool(tool)) {\n\t\t\tconst [convertedTool] = convertToGenerativeAITools([tool]);\n\t\t\tif (convertedTool.functionDeclarations) functionDeclarationTools.push(...convertedTool.functionDeclarations);\n\t\t} else if (isOpenAITool(tool)) {\n\t\t\tconst { functionDeclarations } = convertOpenAIToolToGenAI(tool);\n\t\t\tif (functionDeclarations) functionDeclarationTools.push(...functionDeclarations);\n\t\t\telse throw new Error(\"Failed to convert OpenAI structured tool to GenerativeAI tool\");\n\t\t} else genAITools.push(tool);\n\t});\n\tconst genAIFunctionDeclaration = genAITools.find((t) => \"functionDeclarations\" in t);\n\tif (genAIFunctionDeclaration) return genAITools.map((tool) => {\n\t\tif (functionDeclarationTools?.length > 0 && \"functionDeclarations\" in tool) {\n\t\t\tconst newTool = { functionDeclarations: [...tool.functionDeclarations || [], ...functionDeclarationTools] };\n\t\t\tfunctionDeclarationTools = [];\n\t\t\treturn newTool;\n\t\t}\n\t\treturn tool;\n\t});\n\treturn [...genAITools, ...functionDeclarationTools.length > 0 ? [{ functionDeclarations: functionDeclarationTools }] : []];\n}\nfunction convertOpenAIToolToGenAI(tool) {\n\treturn { functionDeclarations: [{\n\t\tname: tool.function.name,\n\t\tdescription: tool.function.description,\n\t\tparameters: removeAdditionalProperties(tool.function.parameters)\n\t}] };\n}\nfunction createToolConfig(genAITools, extra) {\n\tif (!genAITools.length || !extra) return void 0;\n\tconst { toolChoice, allowedFunctionNames } = extra;\n\tconst modeMap = {\n\t\tany: FunctionCallingMode.ANY,\n\t\tauto: FunctionCallingMode.AUTO,\n\t\tnone: FunctionCallingMode.NONE\n\t};\n\tif (toolChoice && [\n\t\t\"any\",\n\t\t\"auto\",\n\t\t\"none\"\n\t].includes(toolChoice)) return { functionCallingConfig: {\n\t\tmode: modeMap[toolChoice] ?? \"MODE_UNSPECIFIED\",\n\t\tallowedFunctionNames\n\t} };\n\tif (typeof toolChoice === \"string\" || allowedFunctionNames) return { functionCallingConfig: {\n\t\tmode: FunctionCallingMode.ANY,\n\t\tallowedFunctionNames: [...allowedFunctionNames ?? [], ...toolChoice && typeof toolChoice === \"string\" ? [toolChoice] : []]\n\t} };\n\treturn void 0;\n}\n\n//#endregion\nexport { convertToolsToGenAI };\n//# sourceMappingURL=tools.js.map","import { removeAdditionalProperties, schemaToGenerativeAIParameters } from \"./utils/zod_to_genai_parameters.js\";\nimport { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, mapGenerateContentResultToChatResult } from \"./utils/common.js\";\nimport { GoogleGenerativeAIToolsOutputParser } from \"./output_parsers.js\";\nimport { convertToolsToGenAI } from \"./utils/tools.js\";\nimport { GoogleGenerativeAI } from \"@google/generative-ai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport { RunnablePassthrough, RunnableSequence } from \"@langchain/core/runnables\";\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { JsonOutputParser } from \"@langchain/core/output_parsers\";\n\n//#region src/chat_models.ts\n/**\n* Google Generative AI chat model integration.\n*\n* Setup:\n* Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`.\n*\n* ```bash\n* npm install @langchain/google-genai\n* export GOOGLE_API_KEY=\"your-api-key\"\n* ```\n*\n* ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor)\n*\n* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html)\n*\n* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n*\n* ```typescript\n* // When calling `.withConfig`, call options should be passed via the first argument\n* const llmWithArgsBound = llm.withConfig({\n* stop: [\"\\n\"],\n* });\n*\n* // When calling `.bindTools`, call options should be passed via the second argument\n* const llmWithTools = llm.bindTools(\n* [...],\n* {\n* stop: [\"\\n\"],\n* }\n* );\n* ```\n*\n* ## Examples\n*\n*
\n* Instantiate\n*\n* ```typescript\n* import { ChatGoogleGenerativeAI } from '@langchain/google-genai';\n*\n* const llm = new ChatGoogleGenerativeAI({\n* model: \"gemini-1.5-flash\",\n* temperature: 0,\n* maxRetries: 2,\n* // apiKey: \"...\",\n* // other params...\n* });\n* ```\n*
\n*\n*
\n*\n*
\n* Invoking\n*\n* ```typescript\n* const input = `Translate \"I love programming\" into French.`;\n*\n* // Models also accept a list of chat messages or a formatted prompt\n* const result = await llm.invoke(input);\n* console.log(result);\n* ```\n*\n* ```txt\n* AIMessage {\n* \"content\": \"There are a few ways to translate \\\"I love programming\\\" into French, depending on the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and your intended audience. \\n\",\n* \"response_metadata\": {\n* \"finishReason\": \"STOP\",\n* \"index\": 0,\n* \"safetyRatings\": [\n* {\n* \"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n* \"probability\": \"NEGLIGIBLE\"\n* },\n* {\n* \"category\": \"HARM_CATEGORY_HATE_SPEECH\",\n* \"probability\": \"NEGLIGIBLE\"\n* },\n* {\n* \"category\": \"HARM_CATEGORY_HARASSMENT\",\n* \"probability\": \"NEGLIGIBLE\"\n* },\n* {\n* \"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\n* \"probability\": \"NEGLIGIBLE\"\n* }\n* ]\n* },\n* \"usage_metadata\": {\n* \"input_tokens\": 10,\n* \"output_tokens\": 149,\n* \"total_tokens\": 159\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Streaming Chunks\n*\n* ```typescript\n* for await (const chunk of await llm.stream(input)) {\n* console.log(chunk);\n* }\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"content\": \"There\",\n* \"response_metadata\": {\n* \"index\": 0\n* }\n* \"usage_metadata\": {\n* \"input_tokens\": 10,\n* \"output_tokens\": 1,\n* \"total_tokens\": 11\n* }\n* }\n* AIMessageChunk {\n* \"content\": \" are a few ways to translate \\\"I love programming\\\" into French, depending on\",\n* }\n* AIMessageChunk {\n* \"content\": \" the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n\",\n* }\n* AIMessageChunk {\n* \"content\": \"* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This\",\n* }\n* AIMessageChunk {\n* \"content\": \" is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More\",\n* }\n* AIMessageChunk {\n* \"content\": \" specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and\",\n* }\n* AIMessageChunk {\n* \"content\": \" your intended audience. \\n\",\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Aggregate Streamed Chunks\n*\n* ```typescript\n* import { AIMessageChunk } from '@langchain/core/messages';\n* import { concat } from '@langchain/core/utils/stream';\n*\n* const stream = await llm.stream(input);\n* let full: AIMessageChunk | undefined;\n* for await (const chunk of stream) {\n* full = !full ? chunk : concat(full, chunk);\n* }\n* console.log(full);\n* ```\n*\n* ```txt\n* AIMessageChunk {\n* \"content\": \"There are a few ways to translate \\\"I love programming\\\" into French, depending on the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and your intended audience. \\n\",\n* \"usage_metadata\": {\n* \"input_tokens\": 10,\n* \"output_tokens\": 277,\n* \"total_tokens\": 287\n* }\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Bind tools\n*\n* ```typescript\n* import { z } from 'zod';\n*\n* const GetWeather = {\n* name: \"GetWeather\",\n* description: \"Get the current weather in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const GetPopulation = {\n* name: \"GetPopulation\",\n* description: \"Get the current population in a given location\",\n* schema: z.object({\n* location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n* }),\n* }\n*\n* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n* const aiMsg = await llmWithTools.invoke(\n* \"Which city is hotter today and which is bigger: LA or NY?\"\n* );\n* console.log(aiMsg.tool_calls);\n* ```\n*\n* ```txt\n* [\n* {\n* name: 'GetWeather',\n* args: { location: 'Los Angeles, CA' },\n* type: 'tool_call'\n* },\n* {\n* name: 'GetWeather',\n* args: { location: 'New York, NY' },\n* type: 'tool_call'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'Los Angeles, CA' },\n* type: 'tool_call'\n* },\n* {\n* name: 'GetPopulation',\n* args: { location: 'New York, NY' },\n* type: 'tool_call'\n* }\n* ]\n* ```\n*
\n*\n*
\n*\n*
\n* Structured Output\n*\n* ```typescript\n* const Joke = z.object({\n* setup: z.string().describe(\"The setup of the joke\"),\n* punchline: z.string().describe(\"The punchline to the joke\"),\n* rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n* }).describe('Joke to tell user.');\n*\n* const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n* const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n* console.log(jokeResult);\n* ```\n*\n* ```txt\n* {\n* setup: \"Why don\\\\'t cats play poker?\",\n* punchline: \"Why don\\\\'t cats play poker? Because they always have an ace up their sleeve!\"\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Multimodal\n*\n* ```typescript\n* import { HumanMessage } from '@langchain/core/messages';\n*\n* const imageUrl = \"https://example.com/image.jpg\";\n* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n* const base64Image = Buffer.from(imageData).toString('base64');\n*\n* const message = new HumanMessage({\n* content: [\n* { type: \"text\", text: \"describe the weather in this image\" },\n* {\n* type: \"image_url\",\n* image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n* },\n* ]\n* });\n*\n* const imageDescriptionAiMsg = await llm.invoke([message]);\n* console.log(imageDescriptionAiMsg.content);\n* ```\n*\n* ```txt\n* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.\n* ```\n*
\n*\n*
\n*\n*
\n* Usage Metadata\n*\n* ```typescript\n* const aiMsgForMetadata = await llm.invoke(input);\n* console.log(aiMsgForMetadata.usage_metadata);\n* ```\n*\n* ```txt\n* { input_tokens: 10, output_tokens: 149, total_tokens: 159 }\n* ```\n*
\n*\n*
\n*\n*
\n* Response Metadata\n*\n* ```typescript\n* const aiMsgForResponseMetadata = await llm.invoke(input);\n* console.log(aiMsgForResponseMetadata.response_metadata);\n* ```\n*\n* ```txt\n* {\n* finishReason: 'STOP',\n* index: 0,\n* safetyRatings: [\n* {\n* category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n* probability: 'NEGLIGIBLE'\n* },\n* {\n* category: 'HARM_CATEGORY_HATE_SPEECH',\n* probability: 'NEGLIGIBLE'\n* },\n* { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },\n* {\n* category: 'HARM_CATEGORY_DANGEROUS_CONTENT',\n* probability: 'NEGLIGIBLE'\n* }\n* ]\n* }\n* ```\n*
\n*\n*
\n*\n*
\n* Document Messages\n*\n* This example will show you how to pass documents such as PDFs to Google\n* Generative AI through messages.\n*\n* ```typescript\n* const pdfPath = \"/Users/my_user/Downloads/invoice.pdf\";\n* const pdfBase64 = await fs.readFile(pdfPath, \"base64\");\n*\n* const response = await llm.invoke([\n* [\"system\", \"Use the provided documents to answer the question\"],\n* [\n* \"user\",\n* [\n* {\n* type: \"application/pdf\", // If the `type` field includes a single slash (`/`), it will be treated as inline data.\n* data: pdfBase64,\n* },\n* {\n* type: \"text\",\n* text: \"Summarize the contents of this PDF\",\n* },\n* ],\n* ],\n* ]);\n*\n* console.log(response.content);\n* ```\n*\n* ```txt\n* This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025,\n* and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC).\n* The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022,\n* expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is\n* X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply.\n* ```\n*
\n*\n*
\n*/\nvar ChatGoogleGenerativeAI = class extends BaseChatModel {\n\tstatic lc_name() {\n\t\treturn \"ChatGoogleGenerativeAI\";\n\t}\n\tlc_serializable = true;\n\tget lc_secrets() {\n\t\treturn { apiKey: \"GOOGLE_API_KEY\" };\n\t}\n\tlc_namespace = [\n\t\t\"langchain\",\n\t\t\"chat_models\",\n\t\t\"google_genai\"\n\t];\n\tget lc_aliases() {\n\t\treturn { apiKey: \"google_api_key\" };\n\t}\n\tmodel;\n\ttemperature;\n\tmaxOutputTokens;\n\ttopP;\n\ttopK;\n\tstopSequences = [];\n\tsafetySettings;\n\tapiKey;\n\tstreaming = false;\n\tjson;\n\tstreamUsage = true;\n\tconvertSystemMessageToHumanContent;\n\tclient;\n\tget _isMultimodalModel() {\n\t\treturn this.model.includes(\"vision\") || this.model.startsWith(\"gemini-1.5\") || this.model.startsWith(\"gemini-2\") || this.model.startsWith(\"gemma-3-\") && !this.model.startsWith(\"gemma-3-1b\");\n\t}\n\tconstructor(fields) {\n\t\tsuper(fields);\n\t\tthis.model = fields.model.replace(/^models\\//, \"\");\n\t\tthis.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;\n\t\tif (this.maxOutputTokens && this.maxOutputTokens < 0) throw new Error(\"`maxOutputTokens` must be a positive integer\");\n\t\tthis.temperature = fields.temperature ?? this.temperature;\n\t\tif (this.temperature && (this.temperature < 0 || this.temperature > 2)) throw new Error(\"`temperature` must be in the range of [0.0,2.0]\");\n\t\tthis.topP = fields.topP ?? this.topP;\n\t\tif (this.topP && this.topP < 0) throw new Error(\"`topP` must be a positive integer\");\n\t\tif (this.topP && this.topP > 1) throw new Error(\"`topP` must be below 1.\");\n\t\tthis.topK = fields.topK ?? this.topK;\n\t\tif (this.topK && this.topK < 0) throw new Error(\"`topK` must be a positive integer\");\n\t\tthis.stopSequences = fields.stopSequences ?? this.stopSequences;\n\t\tthis.apiKey = fields.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n\t\tif (!this.apiKey) throw new Error(\"Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor\");\n\t\tthis.safetySettings = fields.safetySettings ?? this.safetySettings;\n\t\tif (this.safetySettings && this.safetySettings.length > 0) {\n\t\t\tconst safetySettingsSet = new Set(this.safetySettings.map((s) => s.category));\n\t\t\tif (safetySettingsSet.size !== this.safetySettings.length) throw new Error(\"The categories in `safetySettings` array must be unique\");\n\t\t}\n\t\tthis.streaming = fields.streaming ?? this.streaming;\n\t\tthis.json = fields.json;\n\t\tthis.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({\n\t\t\tmodel: this.model,\n\t\t\tsafetySettings: this.safetySettings,\n\t\t\tgenerationConfig: {\n\t\t\t\tstopSequences: this.stopSequences,\n\t\t\t\tmaxOutputTokens: this.maxOutputTokens,\n\t\t\t\ttemperature: this.temperature,\n\t\t\t\ttopP: this.topP,\n\t\t\t\ttopK: this.topK,\n\t\t\t\t...this.json ? { responseMimeType: \"application/json\" } : {}\n\t\t\t}\n\t\t}, {\n\t\t\tapiVersion: fields.apiVersion,\n\t\t\tbaseUrl: fields.baseUrl\n\t\t});\n\t\tthis.streamUsage = fields.streamUsage ?? this.streamUsage;\n\t}\n\tuseCachedContent(cachedContent, modelParams, requestOptions) {\n\t\tif (!this.apiKey) return;\n\t\tthis.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions);\n\t}\n\tget useSystemInstruction() {\n\t\treturn typeof this.convertSystemMessageToHumanContent === \"boolean\" ? !this.convertSystemMessageToHumanContent : this.computeUseSystemInstruction;\n\t}\n\tget computeUseSystemInstruction() {\n\t\tif (this.model === \"gemini-1.0-pro-001\") return false;\n\t\telse if (this.model.startsWith(\"gemini-pro-vision\")) return false;\n\t\telse if (this.model.startsWith(\"gemini-1.0-pro-vision\")) return false;\n\t\telse if (this.model === \"gemini-pro\") return false;\n\t\treturn true;\n\t}\n\tgetLsParams(options) {\n\t\treturn {\n\t\t\tls_provider: \"google_genai\",\n\t\t\tls_model_name: this.model,\n\t\t\tls_model_type: \"chat\",\n\t\t\tls_temperature: this.client.generationConfig.temperature,\n\t\t\tls_max_tokens: this.client.generationConfig.maxOutputTokens,\n\t\t\tls_stop: options.stop\n\t\t};\n\t}\n\t_combineLLMOutput() {\n\t\treturn [];\n\t}\n\t_llmType() {\n\t\treturn \"googlegenerativeai\";\n\t}\n\tbindTools(tools, kwargs) {\n\t\treturn this.withConfig({\n\t\t\ttools: convertToolsToGenAI(tools)?.tools,\n\t\t\t...kwargs\n\t\t});\n\t}\n\tinvocationParams(options) {\n\t\tconst toolsAndConfig = options?.tools?.length ? convertToolsToGenAI(options.tools, {\n\t\t\ttoolChoice: options.tool_choice,\n\t\t\tallowedFunctionNames: options.allowedFunctionNames\n\t\t}) : void 0;\n\t\tif (options?.responseSchema) {\n\t\t\tthis.client.generationConfig.responseSchema = options.responseSchema;\n\t\t\tthis.client.generationConfig.responseMimeType = \"application/json\";\n\t\t} else {\n\t\t\tthis.client.generationConfig.responseSchema = void 0;\n\t\t\tthis.client.generationConfig.responseMimeType = this.json ? \"application/json\" : void 0;\n\t\t}\n\t\treturn {\n\t\t\t...toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {},\n\t\t\t...toolsAndConfig?.toolConfig ? { toolConfig: toolsAndConfig.toolConfig } : {}\n\t\t};\n\t}\n\tasync _generate(messages, options, runManager) {\n\t\tconst prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);\n\t\tlet actualPrompt = prompt;\n\t\tif (prompt[0].role === \"system\") {\n\t\t\tconst [systemInstruction] = prompt;\n\t\t\tthis.client.systemInstruction = systemInstruction;\n\t\t\tactualPrompt = prompt.slice(1);\n\t\t}\n\t\tconst parameters = this.invocationParams(options);\n\t\tif (this.streaming) {\n\t\t\tconst tokenUsage = {};\n\t\t\tconst stream = this._streamResponseChunks(messages, options, runManager);\n\t\t\tconst finalChunks = {};\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tconst index = chunk.generationInfo?.completion ?? 0;\n\t\t\t\tif (finalChunks[index] === void 0) finalChunks[index] = chunk;\n\t\t\t\telse finalChunks[index] = finalChunks[index].concat(chunk);\n\t\t\t}\n\t\t\tconst generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value);\n\t\t\treturn {\n\t\t\t\tgenerations,\n\t\t\t\tllmOutput: { estimatedTokenUsage: tokenUsage }\n\t\t\t};\n\t\t}\n\t\tconst res = await this.completionWithRetry({\n\t\t\t...parameters,\n\t\t\tcontents: actualPrompt\n\t\t});\n\t\tlet usageMetadata;\n\t\tif (\"usageMetadata\" in res.response) {\n\t\t\tconst genAIUsageMetadata = res.response.usageMetadata;\n\t\t\tusageMetadata = {\n\t\t\t\tinput_tokens: genAIUsageMetadata.promptTokenCount ?? 0,\n\t\t\t\toutput_tokens: genAIUsageMetadata.candidatesTokenCount ?? 0,\n\t\t\t\ttotal_tokens: genAIUsageMetadata.totalTokenCount ?? 0\n\t\t\t};\n\t\t}\n\t\tconst generationResult = mapGenerateContentResultToChatResult(res.response, { usageMetadata });\n\t\tif (generationResult.generations?.length > 0) await runManager?.handleLLMNewToken(generationResult.generations[0]?.text ?? \"\");\n\t\treturn generationResult;\n\t}\n\tasync *_streamResponseChunks(messages, options, runManager) {\n\t\tconst prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);\n\t\tlet actualPrompt = prompt;\n\t\tif (prompt[0].role === \"system\") {\n\t\t\tconst [systemInstruction] = prompt;\n\t\t\tthis.client.systemInstruction = systemInstruction;\n\t\t\tactualPrompt = prompt.slice(1);\n\t\t}\n\t\tconst parameters = this.invocationParams(options);\n\t\tconst request = {\n\t\t\t...parameters,\n\t\t\tcontents: actualPrompt\n\t\t};\n\t\tconst stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => {\n\t\t\tconst { stream: stream$1 } = await this.client.generateContentStream(request);\n\t\t\treturn stream$1;\n\t\t});\n\t\tlet usageMetadata;\n\t\tlet prevPromptTokenCount = 0;\n\t\tlet prevCandidatesTokenCount = 0;\n\t\tlet prevTotalTokenCount = 0;\n\t\tlet index = 0;\n\t\tfor await (const response of stream) {\n\t\t\tif (\"usageMetadata\" in response && response.usageMetadata !== void 0 && this.streamUsage !== false && options.streamUsage !== false) {\n\t\t\t\tusageMetadata = {\n\t\t\t\t\tinput_tokens: response.usageMetadata.promptTokenCount ?? 0,\n\t\t\t\t\toutput_tokens: response.usageMetadata.candidatesTokenCount ?? 0,\n\t\t\t\t\ttotal_tokens: response.usageMetadata.totalTokenCount ?? 0\n\t\t\t\t};\n\t\t\t\tconst newPromptTokenCount = response.usageMetadata.promptTokenCount ?? 0;\n\t\t\t\tusageMetadata.input_tokens = Math.max(0, newPromptTokenCount - prevPromptTokenCount);\n\t\t\t\tprevPromptTokenCount = newPromptTokenCount;\n\t\t\t\tconst newCandidatesTokenCount = response.usageMetadata.candidatesTokenCount ?? 0;\n\t\t\t\tusageMetadata.output_tokens = Math.max(0, newCandidatesTokenCount - prevCandidatesTokenCount);\n\t\t\t\tprevCandidatesTokenCount = newCandidatesTokenCount;\n\t\t\t\tconst newTotalTokenCount = response.usageMetadata.totalTokenCount ?? 0;\n\t\t\t\tusageMetadata.total_tokens = Math.max(0, newTotalTokenCount - prevTotalTokenCount);\n\t\t\t\tprevTotalTokenCount = newTotalTokenCount;\n\t\t\t}\n\t\t\tconst chunk = convertResponseContentToChatGenerationChunk(response, {\n\t\t\t\tusageMetadata,\n\t\t\t\tindex\n\t\t\t});\n\t\t\tindex += 1;\n\t\t\tif (!chunk) continue;\n\t\t\tyield chunk;\n\t\t\tawait runManager?.handleLLMNewToken(chunk.text ?? \"\");\n\t\t}\n\t}\n\tasync completionWithRetry(request, options) {\n\t\treturn this.caller.callWithOptions({ signal: options?.signal }, async () => {\n\t\t\ttry {\n\t\t\t\treturn await this.client.generateContent(request);\n\t\t\t} catch (e) {\n\t\t\t\tif (e.message?.includes(\"400 Bad Request\")) e.status = 400;\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t});\n\t}\n\twithStructuredOutput(outputSchema, config) {\n\t\tconst schema = outputSchema;\n\t\tconst name = config?.name;\n\t\tconst method = config?.method;\n\t\tconst includeRaw = config?.includeRaw;\n\t\tif (method === \"jsonMode\") throw new Error(`ChatGoogleGenerativeAI only supports \"jsonSchema\" or \"functionCalling\" as a method.`);\n\t\tlet llm;\n\t\tlet outputParser;\n\t\tif (method === \"functionCalling\") {\n\t\t\tlet functionName = name ?? \"extract\";\n\t\t\tlet tools;\n\t\t\tif (isInteropZodSchema(schema)) {\n\t\t\t\tconst jsonSchema = schemaToGenerativeAIParameters(schema);\n\t\t\t\ttools = [{ functionDeclarations: [{\n\t\t\t\t\tname: functionName,\n\t\t\t\t\tdescription: jsonSchema.description ?? \"A function available to call.\",\n\t\t\t\t\tparameters: jsonSchema\n\t\t\t\t}] }];\n\t\t\t\toutputParser = new GoogleGenerativeAIToolsOutputParser({\n\t\t\t\t\treturnSingle: true,\n\t\t\t\t\tkeyName: functionName,\n\t\t\t\t\tzodSchema: schema\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlet geminiFunctionDefinition;\n\t\t\t\tif (typeof schema.name === \"string\" && typeof schema.parameters === \"object\" && schema.parameters != null) {\n\t\t\t\t\tgeminiFunctionDefinition = schema;\n\t\t\t\t\tgeminiFunctionDefinition.parameters = removeAdditionalProperties(schema.parameters);\n\t\t\t\t\tfunctionName = schema.name;\n\t\t\t\t} else geminiFunctionDefinition = {\n\t\t\t\t\tname: functionName,\n\t\t\t\t\tdescription: schema.description ?? \"\",\n\t\t\t\t\tparameters: removeAdditionalProperties(schema)\n\t\t\t\t};\n\t\t\t\ttools = [{ functionDeclarations: [geminiFunctionDefinition] }];\n\t\t\t\toutputParser = new GoogleGenerativeAIToolsOutputParser({\n\t\t\t\t\treturnSingle: true,\n\t\t\t\t\tkeyName: functionName\n\t\t\t\t});\n\t\t\t}\n\t\t\tllm = this.bindTools(tools).withConfig({ allowedFunctionNames: [functionName] });\n\t\t} else {\n\t\t\tconst jsonSchema = schemaToGenerativeAIParameters(schema);\n\t\t\tllm = this.withConfig({ responseSchema: jsonSchema });\n\t\t\toutputParser = new JsonOutputParser();\n\t\t}\n\t\tif (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: \"ChatGoogleGenerativeAIStructuredOutput\" });\n\t\tconst parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });\n\t\tconst parserNone = RunnablePassthrough.assign({ parsed: () => null });\n\t\tconst parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });\n\t\treturn RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: \"StructuredOutputRunnable\" });\n\t}\n};\n\n//#endregion\nexport { ChatGoogleGenerativeAI };\n//# sourceMappingURL=chat_models.js.map","import { GoogleGenerativeAI } from \"@google/generative-ai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Embeddings } from \"@langchain/core/embeddings\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\n\n//#region src/embeddings.ts\n/**\n* Class that extends the Embeddings class and provides methods for\n* generating embeddings using the Google Palm API.\n* @example\n* ```typescript\n* const model = new GoogleGenerativeAIEmbeddings({\n* apiKey: \"\",\n* modelName: \"embedding-001\",\n* });\n*\n* // Embed a single query\n* const res = await model.embedQuery(\n* \"What would be a good company name for a company that makes colorful socks?\"\n* );\n* console.log({ res });\n*\n* // Embed multiple documents\n* const documentRes = await model.embedDocuments([\"Hello world\", \"Bye bye\"]);\n* console.log({ documentRes });\n* ```\n*/\nvar GoogleGenerativeAIEmbeddings = class extends Embeddings {\n\tapiKey;\n\tmodelName = \"embedding-001\";\n\tmodel = \"embedding-001\";\n\ttaskType;\n\ttitle;\n\tstripNewLines = true;\n\tmaxBatchSize = 100;\n\tclient;\n\tconstructor(fields) {\n\t\tsuper(fields ?? {});\n\t\tthis.modelName = fields?.model?.replace(/^models\\//, \"\") ?? fields?.modelName?.replace(/^models\\//, \"\") ?? this.modelName;\n\t\tthis.model = this.modelName;\n\t\tthis.taskType = fields?.taskType ?? this.taskType;\n\t\tthis.title = fields?.title ?? this.title;\n\t\tif (this.title && this.taskType !== \"RETRIEVAL_DOCUMENT\") throw new Error(\"title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT\");\n\t\tthis.apiKey = fields?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n\t\tif (!this.apiKey) throw new Error(\"Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor\");\n\t\tthis.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ model: this.model }, { baseUrl: fields?.baseUrl });\n\t}\n\t_convertToContent(text) {\n\t\tconst cleanedText = this.stripNewLines ? text.replace(/\\n/g, \" \") : text;\n\t\treturn {\n\t\t\tcontent: {\n\t\t\t\trole: \"user\",\n\t\t\t\tparts: [{ text: cleanedText }]\n\t\t\t},\n\t\t\ttaskType: this.taskType,\n\t\t\ttitle: this.title\n\t\t};\n\t}\n\tasync _embedQueryContent(text) {\n\t\tconst req = this._convertToContent(text);\n\t\tconst res = await this.client.embedContent(req);\n\t\treturn res.embedding.values ?? [];\n\t}\n\tasync _embedDocumentsContent(documents) {\n\t\tconst batchEmbedChunks = chunkArray(documents, this.maxBatchSize);\n\t\tconst batchEmbedRequests = batchEmbedChunks.map((chunk) => ({ requests: chunk.map((doc) => this._convertToContent(doc)) }));\n\t\tconst responses = await Promise.allSettled(batchEmbedRequests.map((req) => this.client.batchEmbedContents(req)));\n\t\tconst embeddings = responses.flatMap((res, idx) => {\n\t\t\tif (res.status === \"fulfilled\") return res.value.embeddings.map((e) => e.values || []);\n\t\t\telse return Array(batchEmbedChunks[idx].length).fill([]);\n\t\t});\n\t\treturn embeddings;\n\t}\n\t/**\n\t* Method that takes a document as input and returns a promise that\n\t* resolves to an embedding for the document. It calls the _embedText\n\t* method with the document as the input.\n\t* @param document Document for which to generate an embedding.\n\t* @returns Promise that resolves to an embedding for the input document.\n\t*/\n\tembedQuery(document) {\n\t\treturn this.caller.call(this._embedQueryContent.bind(this), document);\n\t}\n\t/**\n\t* Method that takes an array of documents as input and returns a promise\n\t* that resolves to a 2D array of embeddings for each document. It calls\n\t* the _embedText method for each document in the array.\n\t* @param documents Array of documents for which to generate embeddings.\n\t* @returns Promise that resolves to a 2D array of embeddings for each input document.\n\t*/\n\tembedDocuments(documents) {\n\t\treturn this.caller.call(this._embedDocumentsContent.bind(this), documents);\n\t}\n};\n\n//#endregion\nexport { GoogleGenerativeAIEmbeddings };\n//# sourceMappingURL=embeddings.js.map","import { ChatGoogleGenerativeAI } from \"./chat_models.js\";\nimport { GoogleGenerativeAIEmbeddings } from \"./embeddings.js\";\n\nexport { ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings };","import { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { BaseChatModel } from '@langchain/core/language_models/chat_models';\nimport { ILLMProvider, ProviderConfig } from './provider.interface.js';\n\n/**\n * Google Gemini provider implementation\n */\nexport class GoogleProvider implements ILLMProvider {\n public readonly name = 'google';\n private readonly apiKey: string;\n\n constructor(apiKey?: string) {\n this.apiKey = apiKey || process.env.GOOGLE_API_KEY || '';\n }\n\n public isConfigured(): boolean {\n return !!this.apiKey;\n }\n\n public getDefaultModel(): string {\n return 'gemini-pro';\n }\n\n public getChatModel(config: ProviderConfig = {}): BaseChatModel {\n if (!this.isConfigured()) {\n throw new Error('Google API key is not configured');\n }\n\n return new ChatGoogleGenerativeAI({\n apiKey: this.apiKey,\n model: config.model || this.getDefaultModel(),\n temperature: config.temperature ?? 0.2,\n maxOutputTokens: config.maxTokens ?? 4000,\n });\n }\n}\n","import { ILLMProvider, ProviderConfig } from './provider.interface.js';\nimport { AnthropicProvider } from './anthropic.provider.js';\nimport { OpenAIProvider } from './openai.provider.js';\nimport { GoogleProvider } from './google.provider.js';\nimport { BaseChatModel } from '@langchain/core/language_models/chat_models';\n\nexport type SupportedProvider = 'anthropic' | 'openai' | 'google';\n\nexport interface ProviderOptions {\n provider?: SupportedProvider;\n apiKey?: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n}\n\n/**\n * Factory for creating LLM providers\n */\nexport class ProviderFactory {\n private static providers: Map = new Map();\n\n /**\n * Get or create a provider instance\n */\n public static getProvider(\n providerName: SupportedProvider,\n apiKey?: string\n ): ILLMProvider {\n // Normalize provider names\n const normalizedName = this.normalizeProviderName(providerName);\n \n // Check if we already have an instance (unless a specific API key is provided)\n if (!apiKey && this.providers.has(normalizedName)) {\n return this.providers.get(normalizedName)!;\n }\n\n // Create new provider instance\n let provider: ILLMProvider;\n \n switch (normalizedName) {\n case 'anthropic':\n provider = new AnthropicProvider(apiKey);\n break;\n case 'openai':\n provider = new OpenAIProvider(apiKey);\n break;\n case 'google':\n provider = new GoogleProvider(apiKey);\n break;\n default:\n throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`);\n }\n\n // Cache the provider if no specific API key was provided\n if (!apiKey) {\n this.providers.set(normalizedName, provider);\n }\n\n return provider;\n }\n\n /**\n * Create a chat model with the specified options\n */\n public static createChatModel(options: ProviderOptions = {}): BaseChatModel {\n const providerName = options.provider || 'anthropic';\n const provider = this.getProvider(providerName, options.apiKey);\n\n if (!provider.isConfigured()) {\n throw new Error(\n `Provider ${providerName} is not configured. Please set the API key.`\n );\n }\n\n const config: ProviderConfig = {\n model: options.model,\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n };\n\n return provider.getChatModel(config);\n }\n\n /**\n * Get the default model for a provider\n */\n public static getDefaultModel(providerName: SupportedProvider): string {\n const provider = this.getProvider(providerName);\n return provider.getDefaultModel();\n }\n\n /**\n * Check if a provider is configured\n */\n public static isProviderConfigured(providerName: SupportedProvider): boolean {\n try {\n const provider = this.getProvider(providerName);\n return provider.isConfigured();\n } catch {\n return false;\n }\n }\n\n /**\n * Normalize provider name (handle aliases)\n */\n private static normalizeProviderName(name: SupportedProvider): string {\n const normalized = name.toLowerCase();\n if (normalized === 'claude') return 'anthropic';\n if (normalized === 'gemini') return 'google';\n return normalized;\n }\n\n /**\n * Get list of available providers\n */\n public static getAvailableProviders(): SupportedProvider[] {\n return ['anthropic', 'openai', 'google'];\n }\n}\n\n","export * from './provider.interface.js';\nexport * from './provider.factory.js';\nexport * from './anthropic.provider.js';\nexport * from './openai.provider.js';\nexport * from './google.provider.js';\n\n","/**\n * PR Analyzer Agent\n * LangChain-based agent for intelligent PR analysis\n */\n\nimport { BasePRAgentWorkflow } from './base-pr-agent-workflow.js';\nimport { AgentContext, AgentResult, AgentMetadata, AnalysisMode } from '../types/agent.types.js';\nimport { parseDiff } from '../tools/pr-analysis-tools.js';\nimport { ProviderFactory, ProviderOptions } from '../providers/index.js';\nimport { parseAllArchDocs, archDocsExists } from '../utils/arch-docs-parser.js';\nimport { buildArchDocsContext } from '../utils/arch-docs-rag.js';\n\n/**\n * PR Analysis Agent using LangChain and LangGraph\n */\nexport class PRAnalyzerAgent extends BasePRAgentWorkflow {\n constructor(options: ProviderOptions = {}) {\n const model = ProviderFactory.createChatModel({\n provider: options.provider || 'anthropic',\n apiKey: options.apiKey,\n model: options.model,\n temperature: options.temperature ?? 0.2,\n maxTokens: options.maxTokens ?? 4000,\n });\n \n super(model);\n }\n\n /**\n * Get agent metadata\n */\n getMetadata(): AgentMetadata {\n return {\n name: 'pr-analyzer',\n version: '1.0.0',\n description: 'AI-powered pull request analyzer using LangChain agent workflow',\n capabilities: [\n 'file-level analysis',\n 'risk detection',\n 'complexity scoring',\n 'intelligent recommendations',\n 'self-refinement workflow',\n ],\n };\n }\n\n /**\n * Analyze a PR with full agent workflow\n */\n async analyze(\n diff: string,\n title?: string,\n mode?: AnalysisMode,\n options?: { useArchDocs?: boolean; repoPath?: string }\n ): Promise {\n // Parse diff into files\n const files = parseDiff(diff);\n\n // Build arch-docs context if enabled\n let archDocsContext = undefined;\n if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) {\n const docs = parseAllArchDocs(options?.repoPath);\n archDocsContext = buildArchDocsContext(docs, { title, files, diff });\n }\n\n // Create context\n const context: AgentContext = {\n diff,\n title,\n files,\n tokenBudget: 100000,\n maxCost: 5.0,\n mode: mode || { summary: true, risks: true, complexity: true },\n archDocs: archDocsContext,\n };\n\n // Execute workflow\n const result = await this.execute(context, {\n skipSelfRefinement: files.length < 5 || diff.length < 10000, // Skip for small PRs\n });\n\n return result;\n }\n\n /**\n * Quick analysis without refinement\n */\n async quickAnalyze(diff: string, title?: string, options?: { useArchDocs?: boolean; repoPath?: string }): Promise {\n const files = parseDiff(diff);\n\n // Build arch-docs context if enabled\n let archDocsContext = undefined;\n if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) {\n const docs = parseAllArchDocs(options?.repoPath);\n archDocsContext = buildArchDocsContext(docs, { title, files, diff });\n }\n\n const context: AgentContext = {\n diff,\n title,\n files,\n tokenBudget: 50000,\n maxCost: 2.0,\n mode: { summary: true, risks: true, complexity: true },\n archDocs: archDocsContext,\n };\n\n return this.execute(context, {\n skipSelfRefinement: true,\n });\n }\n\n /**\n * Analyze specific files only\n */\n async analyzeFiles(diff: string, filePaths: string[], options?: { useArchDocs?: boolean; repoPath?: string }): Promise {\n const allFiles = parseDiff(diff);\n const files = allFiles.filter(f => filePaths.includes(f.path));\n\n // Build arch-docs context if enabled\n let archDocsContext = undefined;\n if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) {\n const docs = parseAllArchDocs(options?.repoPath);\n archDocsContext = buildArchDocsContext(docs, { files, diff });\n }\n\n const context: AgentContext = {\n diff,\n files,\n tokenBudget: 50000,\n maxCost: 2.0,\n mode: { summary: true, risks: true, complexity: true },\n archDocs: archDocsContext,\n };\n\n return this.execute(context, {\n skipSelfRefinement: true,\n });\n }\n\n /**\n * Check if agent can execute with given context\n */\n async canExecute(context: AgentContext): Promise {\n return context.files.length > 0 && context.diff.length > 0;\n }\n\n /**\n * Estimate tokens for this analysis\n */\n async estimateTokens(context: AgentContext): Promise {\n const baseTokens = 2000;\n const diffTokens = Math.ceil(context.diff.length / 4); // ~4 chars per token\n const filesTokens = context.files.length * 100;\n \n return baseTokens + diffTokens + filesTokens;\n }\n}\n\n/**\n * Factory function to create PR analyzer agent\n */\nexport function createPRAnalyzerAgent(options: ProviderOptions = {}): PRAnalyzerAgent {\n return new PRAnalyzerAgent(options);\n}\n\n/**\n * Legacy factory function for backward compatibility\n * @deprecated Use PRAnalyzerAgent constructor with ProviderOptions instead\n */\nexport function createPRAnalyzerAgentLegacy(apiKey: string, modelName?: string): PRAnalyzerAgent {\n return new PRAnalyzerAgent({ \n apiKey, \n model: modelName,\n provider: 'anthropic'\n });\n}\n\n","import * as core from '@actions/core';\nimport * as github from '@actions/github';\nimport { PRAnalyzerAgent } from './agents/pr-analyzer-agent.js';\n\nasync function run() {\n try {\n // Get provider configuration from environment\n const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase() as 'anthropic' | 'openai' | 'google';\n const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY;\n const model = process.env.AI_MODEL;\n const ghToken = process.env.GITHUB_TOKEN;\n\n if (!apiKey) {\n core.setFailed('AI provider API key is required (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)');\n return;\n }\n\n if (!ghToken) {\n core.setFailed('GITHUB_TOKEN environment variable is required');\n return;\n }\n \n core.info(`Using AI provider: ${provider}${model ? ` with model: ${model}` : ''}`);\n\n const { context } = github;\n const { pull_request: pr, repository } = context.payload;\n\n if (!pr) {\n core.setFailed('This action can only be run on pull request events');\n return;\n }\n\n core.info(`Analyzing PR #${pr.number} in ${repository?.full_name}`);\n\n // Get PR diffs\n const diff = await getPRDiffs(context, ghToken);\n\n if (!diff) {\n core.warning('No changes found in the pull request');\n return;\n }\n \n core.info(`Diff size: ${diff.length} characters`);\n \n if (!repository) {\n core.setFailed('Repository information not available');\n return;\n }\n\n // Use LangChain PRAnalyzerAgent\n core.info('Running LangChain agent analysis...');\n const agent = new PRAnalyzerAgent({\n provider,\n apiKey,\n model,\n });\n\n // Analyze with the LangChain agent\n core.info('Parsing diff and analyzing...');\n const result = await agent.analyze(diff, pr.title);\n \n core.info(`Analysis complete: ${result.fileAnalyses.size} files analyzed`);\n\n // Format the summary\n let summary = '';\n \n if (result.summary) {\n summary += `### Summary\\n${result.summary}\\n\\n`;\n }\n \n if (result.overallRisks.length > 0) {\n summary += `### Potential Risks\\n`;\n result.overallRisks.forEach((risk: any) => {\n if (typeof risk === 'string') {\n summary += `- ${risk}\\n`;\n } else if (typeof risk === 'object' && risk.description) {\n summary += `- **${risk.description}**\\n`;\n if (risk.archDocsReference) {\n summary += ` - 📚 *From ${risk.archDocsReference.source}*: \"${risk.archDocsReference.excerpt}\"\\n`;\n summary += ` - *Reason*: ${risk.archDocsReference.reason}\\n`;\n }\n }\n });\n summary += '\\n';\n } else {\n summary += `### Potential Risks\\nNone\\n\\n`;\n }\n \n summary += `### Complexity: ${result.overallComplexity}/5\\n`;\n \n if (result.recommendations && result.recommendations.length > 0) {\n summary += `\\n### Recommendations\\n`;\n result.recommendations.forEach((rec: string) => {\n summary += `- ${rec}\\n`;\n });\n }\n\n // Post comment\n await postComment(pr.number, summary, repository, ghToken);\n\n core.info('Analysis complete!');\n\n } catch (error) {\n core.setFailed(`Action failed with error: ${error}`);\n }\n}\n\nasync function getPRDiffs(context: any, ghToken: string): Promise {\n try {\n const { pull_request: pr, repository } = context.payload;\n\n const octokit = github.getOctokit(ghToken);\n\n const { data: files } = await octokit.rest.pulls.listFiles({\n owner: repository.owner.login,\n repo: repository.name,\n pull_number: pr.number\n });\n\n // Format as proper git diff that parseDiff expects\n return files.map((f: any) => {\n const status = f.status === 'added' ? 'new file mode 100644' : \n f.status === 'removed' ? 'deleted file mode 100644' : '';\n const patch = f.patch || '';\n \n return `diff --git a/${f.filename} b/${f.filename}\n${status ? status + '\\n' : ''}--- ${f.status === 'added' ? '/dev/null' : 'a/' + f.filename}\n+++ ${f.status === 'removed' ? '/dev/null' : 'b/' + f.filename}\n${patch}`;\n }).join('\\n');\n } catch (error) {\n core.error('Error fetching PR diff:');\n core.error(String(error));\n throw new Error('Failed to fetch PR diff');\n }\n}\n\nasync function postComment(prNumber: number, summary: string, repository: any, ghToken: string) {\n try {\n const octokit = github.getOctokit(ghToken);\n\n await octokit.rest.issues.createComment({\n owner: repository.owner.login,\n repo: repository.name,\n issue_number: prNumber,\n body: `## 🤖 AI Analysis (PR Agent by TechDebtGPT)\\n\\n${summary}`\n });\n } catch (error) {\n core.error('Error posting comment:');\n core.error(String(error));\n throw new Error('Failed to post comment');\n }\n}\n\nrun();\n"],"names":[],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/providers/anthropic.provider.d.ts b/dist/providers/anthropic.provider.d.ts new file mode 100644 index 0000000..a3f13ad --- /dev/null +++ b/dist/providers/anthropic.provider.d.ts @@ -0,0 +1,13 @@ +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { ILLMProvider, ProviderConfig } from './provider.interface.js'; +/** + * Anthropic Claude provider implementation + */ +export declare class AnthropicProvider implements ILLMProvider { + readonly name = "anthropic"; + private readonly apiKey; + constructor(apiKey?: string); + isConfigured(): boolean; + getDefaultModel(): string; + getChatModel(config?: ProviderConfig): BaseChatModel; +} diff --git a/dist/providers/anthropic.provider.js b/dist/providers/anthropic.provider.js new file mode 100644 index 0000000..d4fac9e --- /dev/null +++ b/dist/providers/anthropic.provider.js @@ -0,0 +1,29 @@ +import { ChatAnthropic } from '@langchain/anthropic'; +/** + * Anthropic Claude provider implementation + */ +export class AnthropicProvider { + name = 'anthropic'; + apiKey; + constructor(apiKey) { + this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + return 'claude-sonnet-4-5-20250929'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('Anthropic API key is not configured'); + } + return new ChatAnthropic({ + apiKey: this.apiKey, + modelName: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxTokens: config.maxTokens ?? 4000, + }); + } +} +//# sourceMappingURL=anthropic.provider.js.map \ No newline at end of file diff --git a/dist/providers/anthropic.provider.js.map b/dist/providers/anthropic.provider.js.map new file mode 100644 index 0000000..4aa0528 --- /dev/null +++ b/dist/providers/anthropic.provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"anthropic.provider.js","sourceRoot":"","sources":["../../src/providers/anthropic.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIrD;;GAEG;AACH,MAAM,OAAO,iBAAiB;IACZ,IAAI,GAAG,WAAW,CAAC;IAClB,MAAM,CAAS;IAEhC,YAAY,MAAe;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,EAAE,CAAC;IAC9D,CAAC;IAEM,YAAY;QACjB,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAEM,eAAe;QACpB,OAAO,4BAA4B,CAAC;IACtC,CAAC;IAEM,YAAY,CAAC,SAAyB,EAAE;QAC7C,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;QACzD,CAAC;QAED,OAAO,IAAI,aAAa,CAAC;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,SAAS,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC,eAAe,EAAE;YACjD,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG;YACtC,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,IAAI;SACpC,CAAC,CAAC;IACL,CAAC;CACF"} \ No newline at end of file diff --git a/dist/providers/google.provider.d.ts b/dist/providers/google.provider.d.ts new file mode 100644 index 0000000..445ce8c --- /dev/null +++ b/dist/providers/google.provider.d.ts @@ -0,0 +1,13 @@ +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { ILLMProvider, ProviderConfig } from './provider.interface.js'; +/** + * Google Gemini provider implementation + */ +export declare class GoogleProvider implements ILLMProvider { + readonly name = "google"; + private readonly apiKey; + constructor(apiKey?: string); + isConfigured(): boolean; + getDefaultModel(): string; + getChatModel(config?: ProviderConfig): BaseChatModel; +} diff --git a/dist/providers/google.provider.js b/dist/providers/google.provider.js new file mode 100644 index 0000000..600320b --- /dev/null +++ b/dist/providers/google.provider.js @@ -0,0 +1,29 @@ +import { ChatGoogleGenerativeAI } from '@langchain/google-genai'; +/** + * Google Gemini provider implementation + */ +export class GoogleProvider { + name = 'google'; + apiKey; + constructor(apiKey) { + this.apiKey = apiKey || process.env.GOOGLE_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + return 'gemini-pro'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('Google API key is not configured'); + } + return new ChatGoogleGenerativeAI({ + apiKey: this.apiKey, + model: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxOutputTokens: config.maxTokens ?? 4000, + }); + } +} +//# sourceMappingURL=google.provider.js.map \ No newline at end of file diff --git a/dist/providers/google.provider.js.map b/dist/providers/google.provider.js.map new file mode 100644 index 0000000..b7685f9 --- /dev/null +++ b/dist/providers/google.provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"google.provider.js","sourceRoot":"","sources":["../../src/providers/google.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAIjE;;GAEG;AACH,MAAM,OAAO,cAAc;IACT,IAAI,GAAG,QAAQ,CAAC;IACf,MAAM,CAAS;IAEhC,YAAY,MAAe;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,EAAE,CAAC;IAC3D,CAAC;IAEM,YAAY;QACjB,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAEM,eAAe;QACpB,OAAO,YAAY,CAAC;IACtB,CAAC;IAEM,YAAY,CAAC,SAAyB,EAAE;QAC7C,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACtD,CAAC;QAED,OAAO,IAAI,sBAAsB,CAAC;YAChC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC,eAAe,EAAE;YAC7C,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG;YACtC,eAAe,EAAE,MAAM,CAAC,SAAS,IAAI,IAAI;SAC1C,CAAC,CAAC;IACL,CAAC;CACF"} \ No newline at end of file diff --git a/dist/providers/openai.provider.d.ts b/dist/providers/openai.provider.d.ts new file mode 100644 index 0000000..64ab757 --- /dev/null +++ b/dist/providers/openai.provider.d.ts @@ -0,0 +1,13 @@ +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { ILLMProvider, ProviderConfig } from './provider.interface.js'; +/** + * OpenAI GPT provider implementation + */ +export declare class OpenAIProvider implements ILLMProvider { + readonly name = "openai"; + private readonly apiKey; + constructor(apiKey?: string); + isConfigured(): boolean; + getDefaultModel(): string; + getChatModel(config?: ProviderConfig): BaseChatModel; +} diff --git a/dist/providers/openai.provider.js b/dist/providers/openai.provider.js new file mode 100644 index 0000000..42ca225 --- /dev/null +++ b/dist/providers/openai.provider.js @@ -0,0 +1,29 @@ +import { ChatOpenAI } from '@langchain/openai'; +/** + * OpenAI GPT provider implementation + */ +export class OpenAIProvider { + name = 'openai'; + apiKey; + constructor(apiKey) { + this.apiKey = apiKey || process.env.OPENAI_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + return 'gpt-4-turbo-preview'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('OpenAI API key is not configured'); + } + return new ChatOpenAI({ + apiKey: this.apiKey, + modelName: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxTokens: config.maxTokens ?? 4000, + }); + } +} +//# sourceMappingURL=openai.provider.js.map \ No newline at end of file diff --git a/dist/providers/openai.provider.js.map b/dist/providers/openai.provider.js.map new file mode 100644 index 0000000..7b50a6c --- /dev/null +++ b/dist/providers/openai.provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"openai.provider.js","sourceRoot":"","sources":["../../src/providers/openai.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAI/C;;GAEG;AACH,MAAM,OAAO,cAAc;IACT,IAAI,GAAG,QAAQ,CAAC;IACf,MAAM,CAAS;IAEhC,YAAY,MAAe;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,EAAE,CAAC;IAC3D,CAAC;IAEM,YAAY;QACjB,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAEM,eAAe;QACpB,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAEM,YAAY,CAAC,SAAyB,EAAE;QAC7C,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACtD,CAAC;QAED,OAAO,IAAI,UAAU,CAAC;YACpB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,SAAS,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC,eAAe,EAAE;YACjD,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG;YACtC,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,IAAI;SACpC,CAAC,CAAC;IACL,CAAC;CACF"} \ No newline at end of file diff --git a/dist/providers/provider.factory.d.ts b/dist/providers/provider.factory.d.ts new file mode 100644 index 0000000..ca4916a --- /dev/null +++ b/dist/providers/provider.factory.d.ts @@ -0,0 +1,40 @@ +import { ILLMProvider } from './provider.interface.js'; +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +export type SupportedProvider = 'anthropic' | 'openai' | 'google'; +export interface ProviderOptions { + provider?: SupportedProvider; + apiKey?: string; + model?: string; + temperature?: number; + maxTokens?: number; +} +/** + * Factory for creating LLM providers + */ +export declare class ProviderFactory { + private static providers; + /** + * Get or create a provider instance + */ + static getProvider(providerName: SupportedProvider, apiKey?: string): ILLMProvider; + /** + * Create a chat model with the specified options + */ + static createChatModel(options?: ProviderOptions): BaseChatModel; + /** + * Get the default model for a provider + */ + static getDefaultModel(providerName: SupportedProvider): string; + /** + * Check if a provider is configured + */ + static isProviderConfigured(providerName: SupportedProvider): boolean; + /** + * Normalize provider name (handle aliases) + */ + private static normalizeProviderName; + /** + * Get list of available providers + */ + static getAvailableProviders(): SupportedProvider[]; +} diff --git a/dist/providers/provider.factory.js b/dist/providers/provider.factory.js new file mode 100644 index 0000000..dd2fde9 --- /dev/null +++ b/dist/providers/provider.factory.js @@ -0,0 +1,93 @@ +import { AnthropicProvider } from './anthropic.provider.js'; +import { OpenAIProvider } from './openai.provider.js'; +import { GoogleProvider } from './google.provider.js'; +/** + * Factory for creating LLM providers + */ +export class ProviderFactory { + static providers = new Map(); + /** + * Get or create a provider instance + */ + static getProvider(providerName, apiKey) { + // Normalize provider names + const normalizedName = this.normalizeProviderName(providerName); + // Check if we already have an instance (unless a specific API key is provided) + if (!apiKey && this.providers.has(normalizedName)) { + return this.providers.get(normalizedName); + } + // Create new provider instance + let provider; + switch (normalizedName) { + case 'anthropic': + provider = new AnthropicProvider(apiKey); + break; + case 'openai': + provider = new OpenAIProvider(apiKey); + break; + case 'google': + provider = new GoogleProvider(apiKey); + break; + default: + throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`); + } + // Cache the provider if no specific API key was provided + if (!apiKey) { + this.providers.set(normalizedName, provider); + } + return provider; + } + /** + * Create a chat model with the specified options + */ + static createChatModel(options = {}) { + const providerName = options.provider || 'anthropic'; + const provider = this.getProvider(providerName, options.apiKey); + if (!provider.isConfigured()) { + throw new Error(`Provider ${providerName} is not configured. Please set the API key.`); + } + const config = { + model: options.model, + temperature: options.temperature, + maxTokens: options.maxTokens, + }; + return provider.getChatModel(config); + } + /** + * Get the default model for a provider + */ + static getDefaultModel(providerName) { + const provider = this.getProvider(providerName); + return provider.getDefaultModel(); + } + /** + * Check if a provider is configured + */ + static isProviderConfigured(providerName) { + try { + const provider = this.getProvider(providerName); + return provider.isConfigured(); + } + catch { + return false; + } + } + /** + * Normalize provider name (handle aliases) + */ + static normalizeProviderName(name) { + const normalized = name.toLowerCase(); + if (normalized === 'claude') + return 'anthropic'; + if (normalized === 'gemini') + return 'google'; + return normalized; + } + /** + * Get list of available providers + */ + static getAvailableProviders() { + return ['anthropic', 'openai', 'google']; + } +} +//# sourceMappingURL=provider.factory.js.map \ No newline at end of file diff --git a/dist/providers/provider.factory.js.map b/dist/providers/provider.factory.js.map new file mode 100644 index 0000000..2926111 --- /dev/null +++ b/dist/providers/provider.factory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.factory.js","sourceRoot":"","sources":["../../src/providers/provider.factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAatD;;GAEG;AACH,MAAM,OAAO,eAAe;IAClB,MAAM,CAAC,SAAS,GAA8B,IAAI,GAAG,EAAE,CAAC;IAEhE;;OAEG;IACI,MAAM,CAAC,WAAW,CACvB,YAA+B,EAC/B,MAAe;QAEf,2BAA2B;QAC3B,MAAM,cAAc,GAAG,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;QAEhE,+EAA+E;QAC/E,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;QAC7C,CAAC;QAED,+BAA+B;QAC/B,IAAI,QAAsB,CAAC;QAE3B,QAAQ,cAAc,EAAE,CAAC;YACvB,KAAK,WAAW;gBACd,QAAQ,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAC;gBACzC,MAAM;YACR,KAAK,QAAQ;gBACX,QAAQ,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,CAAC;gBACtC,MAAM;YACR,KAAK,QAAQ;gBACX,QAAQ,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,CAAC;gBACtC,MAAM;YACR;gBACE,MAAM,IAAI,KAAK,CAAC,yBAAyB,YAAY,wCAAwC,CAAC,CAAC;QACnG,CAAC;QAED,yDAAyD;QACzD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;QAC/C,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,eAAe,CAAC,UAA2B,EAAE;QACzD,MAAM,YAAY,GAAG,OAAO,CAAC,QAAQ,IAAI,WAAW,CAAC;QACrD,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAEhE,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CACb,YAAY,YAAY,6CAA6C,CACtE,CAAC;QACJ,CAAC;QAED,MAAM,MAAM,GAAmB;YAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,SAAS,EAAE,OAAO,CAAC,SAAS;SAC7B,CAAC;QAEF,OAAO,QAAQ,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,eAAe,CAAC,YAA+B;QAC3D,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;QAChD,OAAO,QAAQ,CAAC,eAAe,EAAE,CAAC;IACpC,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,oBAAoB,CAAC,YAA+B;QAChE,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;YAChD,OAAO,QAAQ,CAAC,YAAY,EAAE,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACK,MAAM,CAAC,qBAAqB,CAAC,IAAuB;QAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACtC,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,WAAW,CAAC;QAChD,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC7C,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,qBAAqB;QACjC,OAAO,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC3C,CAAC"} \ No newline at end of file diff --git a/dist/providers/provider.interface.d.ts b/dist/providers/provider.interface.d.ts new file mode 100644 index 0000000..5493c19 --- /dev/null +++ b/dist/providers/provider.interface.d.ts @@ -0,0 +1,22 @@ +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +/** + * LLM Provider configuration options + */ +export interface ProviderConfig { + model?: string; + temperature?: number; + maxTokens?: number; +} +/** + * Base interface for LLM providers + */ +export interface ILLMProvider { + /** Provider name */ + readonly name: string; + /** Get chat model instance */ + getChatModel(config: ProviderConfig): BaseChatModel; + /** Get default model for this provider */ + getDefaultModel(): string; + /** Check if provider is configured (has API key) */ + isConfigured(): boolean; +} diff --git a/dist/providers/provider.interface.js b/dist/providers/provider.interface.js new file mode 100644 index 0000000..53d4404 --- /dev/null +++ b/dist/providers/provider.interface.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=provider.interface.js.map \ No newline at end of file diff --git a/dist/providers/provider.interface.js.map b/dist/providers/provider.interface.js.map new file mode 100644 index 0000000..e57dd6b --- /dev/null +++ b/dist/providers/provider.interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.interface.js","sourceRoot":"","sources":["../../src/providers/provider.interface.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/tools/pr-analysis-tools.d.ts b/dist/tools/pr-analysis-tools.d.ts index e44617e..6a060da 100644 --- a/dist/tools/pr-analysis-tools.d.ts +++ b/dist/tools/pr-analysis-tools.d.ts @@ -15,13 +15,7 @@ export declare function parseDiff(diff: string): DiffFile[]; export declare function createFileAnalyzerTool(): DynamicStructuredTool, { +}, z.core.$strip>, { filePath: string; diffContent: string; }, { @@ -34,13 +28,7 @@ export declare function createFileAnalyzerTool(): DynamicStructuredTool; -}, "strip", z.ZodTypeAny, { - diff: string; - context?: string | undefined; -}, { - diff: string; - context?: string | undefined; -}>, { +}, z.core.$strip>, { diff: string; context?: string | undefined; }, { @@ -51,15 +39,9 @@ export declare function createRiskDetectorTool(): DynamicStructuredTool; + filesAnalyzed: z.ZodArray; totalChanges: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - filesAnalyzed: any[]; - totalChanges: number; -}, { - filesAnalyzed: any[]; - totalChanges: number; -}>, { +}, z.core.$strip>, { filesAnalyzed: any[]; totalChanges: number; }, { @@ -70,15 +52,9 @@ export declare function createComplexityScorerTool(): DynamicStructuredTool; + files: z.ZodArray; title: z.ZodOptional; -}, "strip", z.ZodTypeAny, { - files: any[]; - title?: string | undefined; -}, { - files: any[]; - title?: string | undefined; -}>, { +}, z.core.$strip>, { files: any[]; title?: string | undefined; }, { @@ -94,28 +70,16 @@ export declare function createCodeSuggestionTool(): DynamicStructuredTool; prContext: z.ZodOptional; -}, "strip", z.ZodTypeAny, { - filePath: string; - reviewerComment: string; - codeSnippet: string; - prTitle?: string | undefined; - prContext?: string | undefined; -}, { - filePath: string; +}, z.core.$strip>, { reviewerComment: string; codeSnippet: string; - prTitle?: string | undefined; - prContext?: string | undefined; -}>, { filePath: string; - reviewerComment: string; - codeSnippet: string; prTitle?: string | undefined; prContext?: string | undefined; }, { - filePath: string; reviewerComment: string; codeSnippet: string; + filePath: string; prTitle?: string | undefined; prContext?: string | undefined; }, string>; diff --git a/dist/utils/arch-docs-parser.d.ts b/dist/utils/arch-docs-parser.d.ts new file mode 100644 index 0000000..08778d4 --- /dev/null +++ b/dist/utils/arch-docs-parser.d.ts @@ -0,0 +1,50 @@ +/** + * Arch-Docs Parser + * Parses .arch-docs markdown files for RAG system + */ +export interface ArchDoc { + filename: string; + title: string; + content: string; + sections: ArchDocSection[]; + metadata?: Record; +} +export interface ArchDocSection { + heading: string; + level: number; + content: string; + lineStart: number; + lineEnd: number; +} +/** + * Check if .arch-docs folder exists + */ +export declare function archDocsExists(repoPath?: string): boolean; +/** + * Get all markdown files from .arch-docs folder + */ +export declare function getArchDocsFiles(repoPath?: string): string[]; +/** + * Parse a markdown file into structured sections + */ +export declare function parseMarkdownFile(filePath: string): ArchDoc; +/** + * Parse all arch-docs files + */ +export declare function parseAllArchDocs(repoPath?: string): ArchDoc[]; +/** + * Search arch-docs by keyword (simple text search) + */ +export declare function searchArchDocs(docs: ArchDoc[], query: string, maxResults?: number): Array<{ + doc: ArchDoc; + section: ArchDocSection; + relevance: number; +}>; +/** + * Get specific arch-docs by filename + */ +export declare function getArchDocByFilename(docs: ArchDoc[], filename: string): ArchDoc | undefined; +/** + * Get arch-docs summary (index.md content if available) + */ +export declare function getArchDocsSummary(docs: ArchDoc[]): string; diff --git a/dist/utils/arch-docs-parser.js b/dist/utils/arch-docs-parser.js new file mode 100644 index 0000000..8a3c424 --- /dev/null +++ b/dist/utils/arch-docs-parser.js @@ -0,0 +1,142 @@ +/** + * Arch-Docs Parser + * Parses .arch-docs markdown files for RAG system + */ +import * as fs from 'fs'; +import * as path from 'path'; +/** + * Check if .arch-docs folder exists + */ +export function archDocsExists(repoPath = process.cwd()) { + const archDocsPath = path.join(repoPath, '.arch-docs'); + return fs.existsSync(archDocsPath) && fs.statSync(archDocsPath).isDirectory(); +} +/** + * Get all markdown files from .arch-docs folder + */ +export function getArchDocsFiles(repoPath = process.cwd()) { + const archDocsPath = path.join(repoPath, '.arch-docs'); + if (!archDocsExists(repoPath)) { + return []; + } + try { + const files = fs.readdirSync(archDocsPath); + return files + .filter(file => file.endsWith('.md')) + .map(file => path.join(archDocsPath, file)); + } + catch (error) { + console.warn('Error reading .arch-docs folder:', error); + return []; + } +} +/** + * Parse a markdown file into structured sections + */ +export function parseMarkdownFile(filePath) { + const content = fs.readFileSync(filePath, 'utf-8'); + const filename = path.basename(filePath, '.md'); + const lines = content.split('\n'); + const sections = []; + let currentSection; + let title = filename.charAt(0).toUpperCase() + filename.slice(1).replace(/-/g, ' '); + for (let index = 0; index < lines.length; index++) { + const line = lines[index]; + const headingMatch = line.match(/^(#{1,6})\s+(.+)$/); + if (headingMatch) { + // Save previous section + if (currentSection) { + currentSection.lineEnd = index - 1; + sections.push(currentSection); + } + // Extract title from first heading + if (sections.length === 0 && headingMatch[1].length === 1) { + title = headingMatch[2]; + } + // Start new section + currentSection = { + heading: headingMatch[2], + level: headingMatch[1].length, + content: '', + lineStart: index, + lineEnd: index, + }; + } + else if (currentSection) { + // Add content to current section + currentSection.content += line + '\n'; + } + } + // Save last section + if (currentSection) { + currentSection.lineEnd = lines.length - 1; + sections.push(currentSection); + } + return { + filename, + title, + content, + sections, + }; +} +/** + * Parse all arch-docs files + */ +export function parseAllArchDocs(repoPath = process.cwd()) { + const files = getArchDocsFiles(repoPath); + return files.map(file => parseMarkdownFile(file)); +} +/** + * Search arch-docs by keyword (simple text search) + */ +export function searchArchDocs(docs, query, maxResults = 5) { + const results = []; + const queryLower = query.toLowerCase(); + const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2); + for (const doc of docs) { + for (const section of doc.sections) { + const sectionText = (section.heading + ' ' + section.content).toLowerCase(); + // Calculate relevance score + let relevance = 0; + // Exact phrase match + if (sectionText.includes(queryLower)) { + relevance += 10; + } + // Word matches + for (const word of queryWords) { + const matches = (sectionText.match(new RegExp(word, 'g')) || []).length; + relevance += matches * 2; + } + // Heading match bonus + if (section.heading.toLowerCase().includes(queryLower)) { + relevance += 5; + } + if (relevance > 0) { + results.push({ doc, section, relevance }); + } + } + } + // Sort by relevance and return top results + return results + .sort((a, b) => b.relevance - a.relevance) + .slice(0, maxResults); +} +/** + * Get specific arch-docs by filename + */ +export function getArchDocByFilename(docs, filename) { + return docs.find(doc => doc.filename === filename); +} +/** + * Get arch-docs summary (index.md content if available) + */ +export function getArchDocsSummary(docs) { + const indexDoc = getArchDocByFilename(docs, 'index'); + if (indexDoc) { + return indexDoc.content; + } + // Fallback: create summary from available docs + const fileList = docs.map(doc => `- ${doc.title} (${doc.filename}.md)`).join('\n'); + return `Available Architecture Documentation:\n\n${fileList}`; +} +//# sourceMappingURL=arch-docs-parser.js.map \ No newline at end of file diff --git a/dist/utils/arch-docs-parser.js.map b/dist/utils/arch-docs-parser.js.map new file mode 100644 index 0000000..e41cd9d --- /dev/null +++ b/dist/utils/arch-docs-parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arch-docs-parser.js","sourceRoot":"","sources":["../../src/utils/arch-docs-parser.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/utils/arch-docs-rag.d.ts b/dist/utils/arch-docs-rag.d.ts new file mode 100644 index 0000000..5560eba --- /dev/null +++ b/dist/utils/arch-docs-rag.d.ts @@ -0,0 +1,44 @@ +/** + * Arch-Docs RAG System + * Retrieval Augmented Generation for architecture documentation + */ +import { ArchDoc } from './arch-docs-parser.js'; +export interface ArchDocsContext { + available: boolean; + summary: string; + relevantDocs: Array<{ + filename: string; + title: string; + section: string; + content: string; + relevance: number; + }>; + totalDocs: number; +} +/** + * Build context from arch-docs based on PR analysis needs + */ +export declare function buildArchDocsContext(docs: ArchDoc[], prContext: { + title?: string; + files: Array<{ + path: string; + diff?: string; + }>; + diff?: string; +}): ArchDocsContext; +/** + * Format arch-docs context for inclusion in prompts + */ +export declare function formatArchDocsForPrompt(context: ArchDocsContext): string; +/** + * Get specific context for risk analysis + */ +export declare function getSecurityContext(docs: ArchDoc[]): string; +/** + * Get specific context for architecture understanding + */ +export declare function getArchitectureContext(docs: ArchDoc[]): string; +/** + * Get specific context for patterns + */ +export declare function getPatternsContext(docs: ArchDoc[]): string; diff --git a/dist/utils/arch-docs-rag.js b/dist/utils/arch-docs-rag.js new file mode 100644 index 0000000..afffec5 --- /dev/null +++ b/dist/utils/arch-docs-rag.js @@ -0,0 +1,211 @@ +/** + * Arch-Docs RAG System + * Retrieval Augmented Generation for architecture documentation + */ +import { searchArchDocs } from './arch-docs-parser.js'; +/** + * Build context from arch-docs based on PR analysis needs + */ +export function buildArchDocsContext(docs, prContext) { + if (docs.length === 0) { + return { + available: false, + summary: '', + relevantDocs: [], + totalDocs: 0, + }; + } + // Extract keywords from PR context + const keywords = extractKeywords(prContext); + // Search for relevant sections + const relevantResults = new Map(); + // Search for each keyword and aggregate results + for (const keyword of keywords) { + const results = searchArchDocs(docs, keyword, 3); + for (const result of results) { + const key = `${result.doc.filename}:${result.section.heading}`; + const existing = relevantResults.get(key); + if (!existing || result.relevance > existing.relevance) { + relevantResults.set(key, result); + } + } + } + // Also always include key documents + const keyDocs = ['architecture', 'patterns', 'file-structure', 'security']; + for (const keyDoc of keyDocs) { + const doc = docs.find(d => d.filename === keyDoc); + if (doc && doc.sections.length > 0) { + const key = `${doc.filename}:${doc.sections[0].heading}`; + if (!relevantResults.has(key)) { + relevantResults.set(key, { + doc, + section: doc.sections[0], + relevance: 3, // Base relevance for key docs + }); + } + } + } + // Convert to array and sort by relevance + const sortedResults = Array.from(relevantResults.values()) + .sort((a, b) => b.relevance - a.relevance) + .slice(0, 10); // Top 10 most relevant sections + // Build context + const relevantDocs = sortedResults.map(result => ({ + filename: result.doc.filename, + title: result.doc.title, + section: result.section.heading, + content: result.section.content.trim(), + relevance: result.relevance, + })); + // Build summary + const summary = buildContextSummary(docs, relevantDocs); + return { + available: true, + summary, + relevantDocs, + totalDocs: docs.length, + }; +} +/** + * Extract keywords from PR context for semantic search + */ +function extractKeywords(prContext) { + const keywords = new Set(); + // From title + if (prContext.title) { + const titleWords = prContext.title + .toLowerCase() + .split(/\s+/) + .filter(w => w.length > 3 && !isCommonWord(w)); + titleWords.forEach(w => keywords.add(w)); + } + // From file paths + for (const file of prContext.files) { + const pathParts = file.path.split(/[\/\-_\.]/); + for (const part of pathParts) { + if (part.length > 3 && !isCommonWord(part.toLowerCase())) { + keywords.add(part.toLowerCase()); + } + } + // Extract from file extensions and directories + if (file.path.includes('test')) + keywords.add('testing'); + if (file.path.includes('api')) + keywords.add('api'); + if (file.path.includes('auth')) + keywords.add('authentication'); + if (file.path.includes('db') || file.path.includes('database')) + keywords.add('database'); + if (file.path.includes('security')) + keywords.add('security'); + if (file.path.includes('schema')) + keywords.add('schema'); + if (file.path.includes('config')) + keywords.add('configuration'); + if (file.path.includes('migration')) + keywords.add('migration'); + } + // From diff content (look for imports, function names, etc.) + if (prContext.diff) { + // Extract import statements + const importMatches = prContext.diff.matchAll(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g); + for (const match of importMatches) { + const importPath = match[1]; + const parts = importPath.split(/[\/\-_]/); + for (const part of parts) { + if (part.length > 3 && !isCommonWord(part)) { + keywords.add(part); + } + } + } + // Extract class and function names + const classMatches = prContext.diff.matchAll(/class\s+(\w+)/g); + for (const match of classMatches) { + keywords.add(match[1].toLowerCase()); + } + const functionMatches = prContext.diff.matchAll(/function\s+(\w+)/g); + for (const match of functionMatches) { + if (match[1].length > 3) { + keywords.add(match[1].toLowerCase()); + } + } + } + return Array.from(keywords).slice(0, 20); // Limit to top 20 keywords +} +/** + * Check if a word is too common to be useful + */ +function isCommonWord(word) { + const commonWords = new Set([ + 'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'been', + 'will', 'your', 'more', 'when', 'some', 'them', 'than', 'into', 'only', + 'other', 'then', 'also', 'make', 'made', 'like', 'time', 'very', 'just', + 'file', 'code', 'test', 'docs', 'info', 'data', 'type', 'name', 'index', + ]); + return commonWords.has(word); +} +/** + * Build a summary of the context + */ +function buildContextSummary(docs, relevantDocs) { + const docTitles = docs.map(d => d.title).join(', '); + const relevantCount = relevantDocs.length; + let summary = `Architecture Documentation Context:\n`; + summary += `- Total documents: ${docs.length}\n`; + summary += `- Available: ${docTitles}\n`; + summary += `- Relevant sections retrieved: ${relevantCount}\n\n`; + if (relevantCount > 0) { + summary += `Most relevant sections:\n`; + relevantDocs.slice(0, 5).forEach((doc, i) => { + summary += `${i + 1}. ${doc.title} - ${doc.section} (relevance: ${doc.relevance})\n`; + }); + } + return summary; +} +/** + * Format arch-docs context for inclusion in prompts + */ +export function formatArchDocsForPrompt(context) { + if (!context.available || context.relevantDocs.length === 0) { + return ''; + } + let prompt = '\n## Repository Architecture Context\n\n'; + prompt += 'The following sections from the architecture documentation are relevant to this PR:\n\n'; + for (const doc of context.relevantDocs) { + prompt += `### ${doc.title} - ${doc.section}\n\n`; + prompt += doc.content + '\n\n'; + prompt += '---\n\n'; + } + return prompt; +} +/** + * Get specific context for risk analysis + */ +export function getSecurityContext(docs) { + const securityDoc = docs.find(d => d.filename === 'security'); + if (securityDoc) { + return securityDoc.content; + } + return ''; +} +/** + * Get specific context for architecture understanding + */ +export function getArchitectureContext(docs) { + const archDoc = docs.find(d => d.filename === 'architecture'); + if (archDoc) { + return archDoc.content; + } + return ''; +} +/** + * Get specific context for patterns + */ +export function getPatternsContext(docs) { + const patternsDoc = docs.find(d => d.filename === 'patterns'); + if (patternsDoc) { + return patternsDoc.content; + } + return ''; +} +//# sourceMappingURL=arch-docs-rag.js.map \ No newline at end of file diff --git a/dist/utils/arch-docs-rag.js.map b/dist/utils/arch-docs-rag.js.map new file mode 100644 index 0000000..065e2b2 --- /dev/null +++ b/dist/utils/arch-docs-rag.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arch-docs-rag.js","sourceRoot":"","sources":["../../src/utils/arch-docs-rag.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/utils/branch-resolver.d.ts b/dist/utils/branch-resolver.d.ts new file mode 100644 index 0000000..dca3627 --- /dev/null +++ b/dist/utils/branch-resolver.d.ts @@ -0,0 +1,20 @@ +/** + * Branch resolution utilities + * Handles detection of default branch from GitHub API or git commands + */ +export interface BranchResolutionOptions { + configBranch?: string; + githubToken?: string; + repoOwner?: string; + repoName?: string; + fallbackToGit?: boolean; +} +export interface BranchResolutionResult { + branch: string; + source: 'config' | 'github' | 'git' | 'fallback'; + warning?: string; +} +/** + * Resolve the default branch to use for analysis + */ +export declare function resolveDefaultBranch(options?: BranchResolutionOptions): Promise; diff --git a/dist/utils/branch-resolver.js b/dist/utils/branch-resolver.js new file mode 100644 index 0000000..82c6406 --- /dev/null +++ b/dist/utils/branch-resolver.js @@ -0,0 +1,173 @@ +/** + * Branch resolution utilities + * Handles detection of default branch from GitHub API or git commands + */ +import { execSync } from 'child_process'; +import { Octokit } from '@octokit/rest'; +import { GitHubAPIError, ConfigurationError } from './errors.js'; +/** + * Get repository info from git remote + */ +function getRepoInfo() { + try { + const remoteUrl = execSync('git config --get remote.origin.url', { + encoding: 'utf-8', + }).trim(); + // Handle both HTTPS and SSH URLs + // https://github.com/owner/repo.git + // git@github.com:owner/repo.git + const match = remoteUrl.match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/) || + remoteUrl.match(/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?$/); + if (match) { + return { + owner: match[1], + name: match[2].replace(/\.git$/, ''), + }; + } + } + catch { + // Not a git repo or no remote + } + return null; +} +/** + * Get default branch from GitHub API + */ +async function getDefaultBranchFromGitHub(owner, repo, token) { + if (!token) { + return null; + } + try { + const octokit = new Octokit({ auth: token }); + const response = await octokit.repos.get({ + owner, + repo, + }); + return response.data.default_branch; + } + catch (error) { + if (error.status === 404) { + throw new GitHubAPIError(`Repository ${owner}/${repo} not found. Check repository name and access permissions.`, 404, error); + } + else if (error.status === 401 || error.status === 403) { + throw new GitHubAPIError(`GitHub API authentication failed. Check your GITHUB_TOKEN.`, error.status, error); + } + else { + throw new GitHubAPIError(`Failed to fetch repository info from GitHub: ${error.message}`, error.status, error); + } + } +} +/** + * Get default branch from git commands + */ +function getDefaultBranchFromGit() { + try { + // Try to get default branch from git symbolic-ref + try { + const branch = execSync('git symbolic-ref refs/remotes/origin/HEAD', { + encoding: 'utf-8', + }) + .trim() + .replace(/^refs\/remotes\/origin\//, ''); + if (branch) { + return `origin/${branch}`; + } + } + catch { + // Fall through to other methods + } + // Try common branch names + const commonBranches = ['origin/main', 'main', 'origin/master', 'master']; + for (const branch of commonBranches) { + try { + execSync(`git rev-parse --verify ${branch}`, { stdio: 'ignore' }); + return branch; + } + catch { + // Continue to next branch + } + } + return null; + } + catch { + return null; + } +} +/** + * Resolve the default branch to use for analysis + */ +export async function resolveDefaultBranch(options = {}) { + const { configBranch, githubToken, repoOwner, repoName, fallbackToGit = true } = options; + // 1. Use config branch if provided and valid + if (configBranch && configBranch.trim().length > 0) { + // Validate the branch name exists + try { + execSync(`git rev-parse --verify ${configBranch}`, { stdio: 'ignore' }); + return { + branch: configBranch, + source: 'config', + }; + } + catch { + // Config branch doesn't exist, continue to other methods + if (!fallbackToGit) { + throw new ConfigurationError(`Configured branch "${configBranch}" not found. Run: pr-agent config --set git.defaultBranch=`, 'git.defaultBranch'); + } + } + } + // 2. Try GitHub API if token and repo info available + if (githubToken) { + const repoInfo = repoOwner && repoName ? { owner: repoOwner, name: repoName } : getRepoInfo(); + if (repoInfo) { + try { + const defaultBranch = await getDefaultBranchFromGitHub(repoInfo.owner, repoInfo.name, githubToken); + if (defaultBranch) { + const branchRef = `origin/${defaultBranch}`; + // Verify branch exists locally + try { + execSync(`git rev-parse --verify ${branchRef}`, { stdio: 'ignore' }); + return { + branch: branchRef, + source: 'github', + }; + } + catch { + // Branch exists on GitHub but not locally + return { + branch: branchRef, + source: 'github', + warning: `Branch ${branchRef} exists on GitHub but not locally. Run: git fetch origin ${defaultBranch}`, + }; + } + } + } + catch (error) { + // GitHub API failed, but continue to git fallback if enabled + if (error instanceof GitHubAPIError && fallbackToGit) { + // Log warning but continue + console.warn(`⚠️ ${error.message}`); + } + else { + throw error; + } + } + } + } + // 3. Fall back to git commands + if (fallbackToGit) { + const gitBranch = getDefaultBranchFromGit(); + if (gitBranch) { + return { + branch: gitBranch, + source: 'git', + }; + } + } + // 4. Final fallback to common defaults + return { + branch: 'origin/main', + source: 'fallback', + warning: 'Could not detect default branch. Using "origin/main" as fallback. Set git.defaultBranch in config to override.', + }; +} +//# sourceMappingURL=branch-resolver.js.map \ No newline at end of file diff --git a/dist/utils/branch-resolver.js.map b/dist/utils/branch-resolver.js.map new file mode 100644 index 0000000..cc5c2a6 --- /dev/null +++ b/dist/utils/branch-resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"branch-resolver.js","sourceRoot":"","sources":["../../src/utils/branch-resolver.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/utils/config-validator.d.ts b/dist/utils/config-validator.d.ts new file mode 100644 index 0000000..3043a25 --- /dev/null +++ b/dist/utils/config-validator.d.ts @@ -0,0 +1,58 @@ +/** + * Configuration validation using Zod + */ +import { z } from 'zod'; +import { UserConfig } from '../cli/utils/config-loader.js'; +/** + * Zod schema for validating UserConfig + */ +export declare const UserConfigSchema: z.ZodObject<{ + apiKeys: z.ZodOptional; + openai: z.ZodOptional; + google: z.ZodOptional; + }, z.core.$strip>>; + ai: z.ZodOptional>; + model: z.ZodOptional; + temperature: z.ZodOptional; + maxTokens: z.ZodOptional; + }, z.core.$strip>>; + analysis: z.ZodOptional>; + maxCost: z.ZodOptional; + autoDetectAgent: z.ZodOptional; + agentThreshold: z.ZodOptional; + }, z.core.$strip>>; + git: z.ZodOptional; + includeUntracked: z.ZodOptional; + excludePatterns: z.ZodOptional>; + }, z.core.$strip>>; + output: z.ZodOptional; + showStrategy: z.ZodOptional; + showRecommendations: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * Validate configuration object + */ +export declare function validateConfig(config: UserConfig): { + success: boolean; + errors: string[]; + sanitizedConfig?: UserConfig; +}; +/** + * Validate and throw if invalid + */ +export declare function validateConfigOrThrow(config: UserConfig, configPath?: string): UserConfig; diff --git a/dist/utils/config-validator.js b/dist/utils/config-validator.js new file mode 100644 index 0000000..9fb780a --- /dev/null +++ b/dist/utils/config-validator.js @@ -0,0 +1,105 @@ +/** + * Configuration validation using Zod + */ +import { z } from 'zod'; +import { ConfigurationError } from './errors.js'; +/** + * Zod schema for validating UserConfig + */ +export const UserConfigSchema = z.object({ + apiKeys: z + .object({ + anthropic: z.string().optional(), + openai: z.string().optional(), + google: z.string().optional(), + }) + .optional(), + ai: z + .object({ + provider: z.enum(['anthropic', 'openai', 'google']).optional(), + model: z.string().optional(), + temperature: z.number().min(0).max(2).optional(), + maxTokens: z.number().positive().int().optional(), + }) + .optional(), + analysis: z + .object({ + defaultMode: z.enum(['full', 'summary', 'risks', 'complexity']).optional(), + maxCost: z.number().nonnegative().optional(), + autoDetectAgent: z.boolean().optional(), + agentThreshold: z.number().nonnegative().int().optional(), + }) + .optional(), + git: z + .object({ + defaultBranch: z + .string() + .min(1) + .refine((val) => { + // Allow origin/branch, branch, or just branch name + // Reject empty strings and invalid patterns + if (!val || val.trim().length === 0) + return false; + // Basic validation: should not contain dangerous characters + if (/[<>"|\\\x00-\x1f]/.test(val)) + return false; + return true; + }, { + message: 'defaultBranch must be a valid branch name (e.g., "origin/main", "main", "master")', + }) + .optional(), + includeUntracked: z.boolean().optional(), + excludePatterns: z.array(z.string()).optional(), + }) + .optional(), + output: z + .object({ + verbose: z.boolean().optional(), + showStrategy: z.boolean().optional(), + showRecommendations: z.boolean().optional(), + }) + .optional(), +}); +/** + * Validate configuration object + */ +export function validateConfig(config) { + try { + const result = UserConfigSchema.safeParse(config); + if (result.success) { + return { + success: true, + errors: [], + sanitizedConfig: result.data, + }; + } + else { + const errors = result.error.issues.map((err) => { + const path = err.path.join('.'); + return `${path}: ${err.message}`; + }); + return { + success: false, + errors, + }; + } + } + catch (error) { + return { + success: false, + errors: [`Validation error: ${error instanceof Error ? error.message : String(error)}`], + }; + } +} +/** + * Validate and throw if invalid + */ +export function validateConfigOrThrow(config, configPath) { + const validation = validateConfig(config); + if (!validation.success) { + const errorMessage = `Invalid configuration${configPath ? ` in ${configPath}` : ''}:\n${validation.errors.map((e) => ` • ${e}`).join('\n')}\n\nRun: pr-agent config --init to fix configuration.`; + throw new ConfigurationError(errorMessage, 'config'); + } + return validation.sanitizedConfig; +} +//# sourceMappingURL=config-validator.js.map \ No newline at end of file diff --git a/dist/utils/config-validator.js.map b/dist/utils/config-validator.js.map new file mode 100644 index 0000000..4afe478 --- /dev/null +++ b/dist/utils/config-validator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config-validator.js","sourceRoot":"","sources":["../../src/utils/config-validator.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/dist/utils/errors.d.ts b/dist/utils/errors.d.ts new file mode 100644 index 0000000..13c90d7 --- /dev/null +++ b/dist/utils/errors.d.ts @@ -0,0 +1,25 @@ +/** + * Custom error types for PR Agent + */ +/** + * Configuration-related errors + */ +export declare class ConfigurationError extends Error { + readonly field?: string | undefined; + constructor(message: string, field?: string | undefined); +} +/** + * GitHub API-related errors + */ +export declare class GitHubAPIError extends Error { + readonly statusCode?: number | undefined; + readonly apiError?: any | undefined; + constructor(message: string, statusCode?: number | undefined, apiError?: any | undefined); +} +/** + * Git operation errors + */ +export declare class GitError extends Error { + readonly command?: string | undefined; + constructor(message: string, command?: string | undefined); +} diff --git a/dist/utils/errors.js b/dist/utils/errors.js new file mode 100644 index 0000000..c1c1502 --- /dev/null +++ b/dist/utils/errors.js @@ -0,0 +1,42 @@ +/** + * Custom error types for PR Agent + */ +/** + * Configuration-related errors + */ +export class ConfigurationError extends Error { + field; + constructor(message, field) { + super(message); + this.field = field; + this.name = 'ConfigurationError'; + Object.setPrototypeOf(this, ConfigurationError.prototype); + } +} +/** + * GitHub API-related errors + */ +export class GitHubAPIError extends Error { + statusCode; + apiError; + constructor(message, statusCode, apiError) { + super(message); + this.statusCode = statusCode; + this.apiError = apiError; + this.name = 'GitHubAPIError'; + Object.setPrototypeOf(this, GitHubAPIError.prototype); + } +} +/** + * Git operation errors + */ +export class GitError extends Error { + command; + constructor(message, command) { + super(message); + this.command = command; + this.name = 'GitError'; + Object.setPrototypeOf(this, GitError.prototype); + } +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/dist/utils/errors.js.map b/dist/utils/errors.js.map new file mode 100644 index 0000000..22b12a1 --- /dev/null +++ b/dist/utils/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/utils/errors.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IACE;IAA7C,YAAY,OAAe,EAAkB,KAAc;QACzD,KAAK,CAAC,OAAO,CAAC,CAAC;QAD4B,UAAK,GAAL,KAAK,CAAS;QAEzD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,cAAe,SAAQ,KAAK;IAGrB;IACA;IAHlB,YACE,OAAe,EACC,UAAmB,EACnB,QAAc;QAE9B,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,eAAU,GAAV,UAAU,CAAS;QACnB,aAAQ,GAAR,QAAQ,CAAM;QAG9B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACY;IAA7C,YAAY,OAAe,EAAkB,OAAgB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QAD4B,YAAO,GAAP,OAAO,CAAS;QAE3D,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;IAClD,CAAC;CACF"} \ No newline at end of file diff --git a/jest.config.js b/jest.config.js index 6744036..31c4ca4 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,9 +1,25 @@ -module.exports = { +export default { preset: 'ts-jest', testEnvironment: 'node', roots: ['/src', '/tests'], testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], + extensionsToTreatAsEsm: ['.ts'], + transform: { + '^.+\\.ts$': ['ts-jest', { + useESM: true, + isolatedModules: true, + diagnostics: { + ignoreCodes: [151002], + }, + }], + }, + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, + transformIgnorePatterns: [ + 'node_modules/(?!@octokit)', + ], collectCoverageFrom: [ 'src/**/*.ts', '!src/**/*.d.ts', diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..36d9467 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,9362 @@ +{ + "name": "pr-agent", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pr-agent", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "@actions/core": "^1.11.1", + "@actions/github": "^6.0.1", + "@anthropic-ai/sdk": "^0.24.3", + "@langchain/anthropic": "^1.1.3", + "@langchain/core": "^1.1.0", + "@langchain/google-genai": "^2.0.0", + "@langchain/langgraph": "^1.0.2", + "@langchain/openai": "^1.1.3", + "@octokit/rest": "^22.0.1", + "chalk": "^4.1.2", + "commander": "^14.0.2", + "inquirer": "^12.10.0", + "langchain": "^1.1.1", + "ora": "^9.0.0", + "probot": "^12.3.1" + }, + "bin": { + "pr-agent": "dist/cli/index.js" + }, + "devDependencies": { + "@types/jest": "^29.5.12", + "@types/node": "^24.7.1", + "@vercel/ncc": "^0.38.4", + "jest": "^29.7.0", + "ts-jest": "^29.1.2", + "tsx": "^4.0.0", + "typescript": "^5.2.2", + "zod": "^4.1.13" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@actions/core": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.11.1.tgz", + "integrity": "sha512-hXJCSrkwfA46Vd9Z3q4cpEpHB1rL5NG04+/rbqW9d3+CSvtB1tYe8UTpAlixa1vj0m/ULglfEK2UKxMGxCxv5A==", + "license": "MIT", + "dependencies": { + "@actions/exec": "^1.1.1", + "@actions/http-client": "^2.0.1" + } + }, + "node_modules/@actions/exec": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.1.1.tgz", + "integrity": "sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==", + "license": "MIT", + "dependencies": { + "@actions/io": "^1.0.1" + } + }, + "node_modules/@actions/github": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@actions/github/-/github-6.0.1.tgz", + "integrity": "sha512-xbZVcaqD4XnQAe35qSQqskb3SqIAfRyLBrHMd/8TuL7hJSz2QtbDwnNM8zWx4zO5l2fnGtseNE3MbEvD7BxVMw==", + "license": "MIT", + "dependencies": { + "@actions/http-client": "^2.2.0", + "@octokit/core": "^5.0.1", + "@octokit/plugin-paginate-rest": "^9.2.2", + "@octokit/plugin-rest-endpoint-methods": "^10.4.0", + "@octokit/request": "^8.4.1", + "@octokit/request-error": "^5.1.1", + "undici": "^5.28.5" + } + }, + "node_modules/@actions/http-client": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz", + "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==", + "license": "MIT", + "dependencies": { + "tunnel": "^0.0.6", + "undici": "^5.25.4" + } + }, + "node_modules/@actions/io": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@actions/io/-/io-1.1.3.tgz", + "integrity": "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==", + "license": "MIT" + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.24.3", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.24.3.tgz", + "integrity": "sha512-916wJXO6T6k8R6BAAcLhLPv/pnLGy7YSEBZXZ1XTFbLcTZE8oTy3oDW9WJf9KKZwMvVcePIfoTSvzXHRcGxkQQ==", + "license": "MIT", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + } + }, + "node_modules/@anthropic-ai/sdk/node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@anthropic-ai/sdk/node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "license": "MIT" + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", + "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz", + "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz", + "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-module-transforms": "^7.28.3", + "@babel/helpers": "^7.28.4", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz", + "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.27.2", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", + "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.27.2", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz", + "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.27.1", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz", + "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.27.1", + "@babel/helper-validator-identifier": "^7.27.1", + "@babel/traverse": "^7.28.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz", + "integrity": "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.28.4", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz", + "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.27.1.tgz", + "integrity": "sha512-oFT0FrKHgF53f4vOsZGi2Hh3I35PfSmVs4IBFLFj4dnafP+hIWDLg3VyKmUHfLoLHlyxY4C7DGtmHuJgn+IGww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.27.1.tgz", + "integrity": "sha512-y8YTNIeKoyhGd9O0Jiyzyyqk8gdjnumGTQPsz0xOZOQ2RmkVJeZ1vmmfIvFEKqucBG6axJGBZDE/7iI5suUI/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.27.1.tgz", + "integrity": "sha512-xfYCBMxveHrRMnAWl1ZlPXOZjzkN82THFvLhQhFXFt81Z5HnN+EtUkZhv/zcKpmT3fzmWZB0ywiBrbC3vogbwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.28.4", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz", + "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.27.2", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", + "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/parser": "^7.27.2", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.5.tgz", + "integrity": "sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.5", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@cfworker/json-schema": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", + "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", + "license": "MIT" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.0.tgz", + "integrity": "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.0.tgz", + "integrity": "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.0.tgz", + "integrity": "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.0.tgz", + "integrity": "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.0.tgz", + "integrity": "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.0.tgz", + "integrity": "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.0.tgz", + "integrity": "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.0.tgz", + "integrity": "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.0.tgz", + "integrity": "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.0.tgz", + "integrity": "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.0.tgz", + "integrity": "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.0.tgz", + "integrity": "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.0.tgz", + "integrity": "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.0.tgz", + "integrity": "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.0.tgz", + "integrity": "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.0.tgz", + "integrity": "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.0.tgz", + "integrity": "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.0.tgz", + "integrity": "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.0.tgz", + "integrity": "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.0.tgz", + "integrity": "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.0.tgz", + "integrity": "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.0.tgz", + "integrity": "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.0.tgz", + "integrity": "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.0.tgz", + "integrity": "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.0.tgz", + "integrity": "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.0.tgz", + "integrity": "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@fastify/busboy": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", + "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@google/generative-ai": { + "version": "0.24.1", + "resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.24.1.tgz", + "integrity": "sha512-MqO+MLfM6kjxcKoy0p1wRzG3b4ZZXtPI+z2IE26UogS2Cm/XHO+7gGRBh6gcJsOiIVoH93UwKvW4HdgiOZCy9Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@hapi/bourne": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@hapi/bourne/-/bourne-2.1.0.tgz", + "integrity": "sha512-i1BpaNDVLJdRBEKeJWkVO6tYX6DMFBuwMhSuWqLsY4ufeTKGVuV5rBsUhxPayXqnnWHgXUAmWK16H/ykO5Wj4Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@inquirer/ansi": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-1.0.2.tgz", + "integrity": "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-4.3.2.tgz", + "integrity": "sha512-VXukHf0RR1doGe6Sm4F0Em7SWYLTHSsbGfJdS9Ja2bX5/D5uwVOEjr07cncLROdBvmnvCATYEWlHqYmXv2IlQA==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^1.0.2", + "@inquirer/core": "^10.3.2", + "@inquirer/figures": "^1.0.15", + "@inquirer/type": "^3.0.10", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "5.1.21", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-5.1.21.tgz", + "integrity": "sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "10.3.2", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-10.3.2.tgz", + "integrity": "sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^1.0.2", + "@inquirer/figures": "^1.0.15", + "@inquirer/type": "^3.0.10", + "cli-width": "^4.1.0", + "mute-stream": "^2.0.0", + "signal-exit": "^4.1.0", + "wrap-ansi": "^6.2.0", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/editor": { + "version": "4.2.23", + "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-4.2.23.tgz", + "integrity": "sha512-aLSROkEwirotxZ1pBaP8tugXRFCxW94gwrQLxXfrZsKkfjOYC1aRvAZuhpJOb5cu4IBTJdsCigUlf2iCOu4ZDQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/external-editor": "^1.0.3", + "@inquirer/type": "^3.0.10" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand": { + "version": "4.0.23", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-4.0.23.tgz", + "integrity": "sha512-nRzdOyFYnpeYTTR2qFwEVmIWypzdAx/sIkCMeTNTcflFOovfqUk+HcFhQQVBftAh9gmGrpFj6QcGEqrDMDOiew==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.3.tgz", + "integrity": "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA==", + "license": "MIT", + "dependencies": { + "chardet": "^2.1.1", + "iconv-lite": "^0.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "1.0.15", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.15.tgz", + "integrity": "sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@inquirer/input": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-4.3.1.tgz", + "integrity": "sha512-kN0pAM4yPrLjJ1XJBjDxyfDduXOuQHrBB8aLDMueuwUGn+vNpF7Gq7TvyVxx8u4SHlFFj4trmj+a2cbpG4Jn1g==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number": { + "version": "3.0.23", + "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-3.0.23.tgz", + "integrity": "sha512-5Smv0OK7K0KUzUfYUXDXQc9jrf8OHo4ktlEayFlelCjwMXz0299Y8OrI+lj7i4gCBY15UObk76q0QtxjzFcFcg==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password": { + "version": "4.0.23", + "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-4.0.23.tgz", + "integrity": "sha512-zREJHjhT5vJBMZX/IUbyI9zVtVfOLiTO66MrF/3GFZYZ7T4YILW5MSkEYHceSii/KtRk+4i3RE7E1CUXA2jHcA==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^1.0.2", + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/prompts": { + "version": "7.10.1", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-7.10.1.tgz", + "integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==", + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^4.3.2", + "@inquirer/confirm": "^5.1.21", + "@inquirer/editor": "^4.2.23", + "@inquirer/expand": "^4.0.23", + "@inquirer/input": "^4.3.1", + "@inquirer/number": "^3.0.23", + "@inquirer/password": "^4.0.23", + "@inquirer/rawlist": "^4.1.11", + "@inquirer/search": "^3.2.2", + "@inquirer/select": "^4.4.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-4.1.11.tgz", + "integrity": "sha512-+LLQB8XGr3I5LZN/GuAHo+GpDJegQwuPARLChlMICNdwW7OwV2izlCSCxN6cqpL0sMXmbKbFcItJgdQq5EBXTw==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/type": "^3.0.10", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-3.2.2.tgz", + "integrity": "sha512-p2bvRfENXCZdWF/U2BXvnSI9h+tuA8iNqtUKb9UWbmLYCRQxd8WkvwWvYn+3NgYaNwdUkHytJMGG4MMLucI1kA==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.3.2", + "@inquirer/figures": "^1.0.15", + "@inquirer/type": "^3.0.10", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-4.4.2.tgz", + "integrity": "sha512-l4xMuJo55MAe+N7Qr4rX90vypFwCajSakx59qe/tMaC1aEHWLyw68wF4o0A4SLAY4E0nd+Vt+EyskeDIqu1M6w==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^1.0.2", + "@inquirer/core": "^10.3.2", + "@inquirer/figures": "^1.0.15", + "@inquirer/type": "^3.0.10", + "yoctocolors-cjs": "^2.1.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-3.0.10.tgz", + "integrity": "sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@ioredis/commands": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.0.tgz", + "integrity": "sha512-eUgLqrMf8nJkZxT24JvVRrQya1vZkQh8BBeYNwGDqa5I0VUi8ACx7uFvAaLxintokpTenkK6DASvo/bvNbBGow==", + "license": "MIT" + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", + "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/core": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/environment": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", + "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.7.0", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", + "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", + "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "*", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", + "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/types": "^29.6.3", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", + "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", + "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@langchain/anthropic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-1.1.3.tgz", + "integrity": "sha512-vJN7Rfl+8lDO+aVFfccDUFxIMwGtf8xHSWvqmeytOB5UBzGxNMRW2Zdu6Gv8vWrKlS6Ca7/8oB1suw1SN0FKGA==", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "^0.71.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.0.0" + } + }, + "node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk": { + "version": "0.71.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.71.0.tgz", + "integrity": "sha512-go1XeWXmpxuiTkosSXpb8tokLk2ZLkIRcXpbWVwJM6gH5OBtHOVsfPfGuqI1oW7RRt4qc59EmYbrXRZ0Ng06Jw==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@langchain/core": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.1.0.tgz", + "integrity": "sha512-yJ6JHcU9psjnQbzRFkXjIdNTA+3074dA+2pHdH8ewvQCSleSk6JcjkCMIb5+NASjeMoi1ZuntlLKVsNqF38YxA==", + "license": "MIT", + "dependencies": { + "@cfworker/json-schema": "^4.0.2", + "ansi-styles": "^5.0.0", + "camelcase": "6", + "decamelize": "1.2.0", + "js-tiktoken": "^1.0.12", + "langsmith": "^0.3.64", + "mustache": "^4.2.0", + "p-queue": "^6.6.2", + "p-retry": "^7.0.0", + "uuid": "^10.0.0", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@langchain/google-genai": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@langchain/google-genai/-/google-genai-2.0.0.tgz", + "integrity": "sha512-PaAWkogQdF+Y2bhhXWXUrC2nO7sTgWLtobBbZl/0V8Aa1F/KG2wrMECie3S17bAdFu/6VmQOuFFrlgSMwQC5KA==", + "license": "MIT", + "dependencies": { + "@google/generative-ai": "^0.24.0", + "uuid": "^11.1.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "1.1.0" + } + }, + "node_modules/@langchain/google-genai/node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/@langchain/langgraph": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@langchain/langgraph/-/langgraph-1.0.2.tgz", + "integrity": "sha512-syxzzWTnmpCL+RhUEvalUeOXFoZy/KkzHa2Da2gKf18zsf9Dkbh3rfnRDrTyUGS1XSTejq07s4rg1qntdEDs2A==", + "license": "MIT", + "dependencies": { + "@langchain/langgraph-checkpoint": "^1.0.0", + "@langchain/langgraph-sdk": "~1.0.0", + "uuid": "^10.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@langchain/core": "^1.0.1", + "zod": "^3.25.32 || ^4.1.0", + "zod-to-json-schema": "^3.x" + }, + "peerDependenciesMeta": { + "zod-to-json-schema": { + "optional": true + } + } + }, + "node_modules/@langchain/langgraph-checkpoint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-checkpoint/-/langgraph-checkpoint-1.0.0.tgz", + "integrity": "sha512-xrclBGvNCXDmi0Nz28t3vjpxSH6UYx6w5XAXSiiB1WEdc2xD2iY/a913I3x3a31XpInUW/GGfXXfePfaghV54A==", + "license": "MIT", + "dependencies": { + "uuid": "^10.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@langchain/core": "^1.0.1" + } + }, + "node_modules/@langchain/langgraph-sdk": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.0.3.tgz", + "integrity": "sha512-6M4i0XsVO5Eb2vv/3OtIPHW3UqO4zYyXl6AOfS0Jf6d7JiWiSXqzLN8UoS0hpu1ItkcW1j575CRiP/6jn6XXFg==", + "license": "MIT", + "dependencies": { + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^9.0.0" + }, + "peerDependencies": { + "@langchain/core": "^1.0.1", + "react": "^18 || ^19", + "react-dom": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@langchain/core": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/@langchain/langgraph-sdk/node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@langchain/langgraph-sdk/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@langchain/openai": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@langchain/openai/-/openai-1.1.3.tgz", + "integrity": "sha512-p+xR+4HRms5Ozjf5miC6U2AYRyNVSTdO7AMBkMYs1Tp6DWHBd+mQ72H8Ogd2dKrPuS5UDJ5dbpI1fS+OrTbgQQ==", + "license": "MIT", + "dependencies": { + "js-tiktoken": "^1.0.12", + "openai": "^6.9.0", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.0.0" + } + }, + "node_modules/@octokit/auth-app": { + "version": "4.0.13", + "resolved": "https://registry.npmjs.org/@octokit/auth-app/-/auth-app-4.0.13.tgz", + "integrity": "sha512-NBQkmR/Zsc+8fWcVIFrwDgNXS7f4XDrkd9LHdi9DPQw1NdGHLviLzRO2ZBwTtepnwHXW5VTrVU9eFGijMUqllg==", + "license": "MIT", + "dependencies": { + "@octokit/auth-oauth-app": "^5.0.0", + "@octokit/auth-oauth-user": "^2.0.0", + "@octokit/request": "^6.0.0", + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0", + "deprecation": "^2.3.1", + "lru-cache": "^9.0.0", + "universal-github-app-jwt": "^1.1.1", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-app/node_modules/@octokit/endpoint": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.6.tgz", + "integrity": "sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-app/node_modules/@octokit/openapi-types": { + "version": "18.1.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", + "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "license": "MIT" + }, + "node_modules/@octokit/auth-app/node_modules/@octokit/request": { + "version": "6.2.8", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.8.tgz", + "integrity": "sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^7.0.0", + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.7", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-app/node_modules/@octokit/request-error": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", + "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-app/node_modules/@octokit/types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", + "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^18.0.0" + } + }, + "node_modules/@octokit/auth-app/node_modules/lru-cache": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-9.1.2.tgz", + "integrity": "sha512-ERJq3FOzJTxBbFjZ7iDs+NiK4VI9Wz+RdrrAB8dio1oV+YvdPzUEE4QNiT2VD51DkIbCYRUUzCRkssXCHqSnKQ==", + "license": "ISC", + "engines": { + "node": "14 || >=16.14" + } + }, + "node_modules/@octokit/auth-oauth-app": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@octokit/auth-oauth-app/-/auth-oauth-app-5.0.6.tgz", + "integrity": "sha512-SxyfIBfeFcWd9Z/m1xa4LENTQ3l1y6Nrg31k2Dcb1jS5ov7pmwMJZ6OGX8q3K9slRgVpeAjNA1ipOAMHkieqyw==", + "license": "MIT", + "dependencies": { + "@octokit/auth-oauth-device": "^4.0.0", + "@octokit/auth-oauth-user": "^2.0.0", + "@octokit/request": "^6.0.0", + "@octokit/types": "^9.0.0", + "@types/btoa-lite": "^1.0.0", + "btoa-lite": "^1.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-app/node_modules/@octokit/endpoint": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.6.tgz", + "integrity": "sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-app/node_modules/@octokit/openapi-types": { + "version": "18.1.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", + "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "license": "MIT" + }, + "node_modules/@octokit/auth-oauth-app/node_modules/@octokit/request": { + "version": "6.2.8", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.8.tgz", + "integrity": "sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^7.0.0", + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.7", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-app/node_modules/@octokit/request-error": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", + "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-app/node_modules/@octokit/types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", + "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^18.0.0" + } + }, + "node_modules/@octokit/auth-oauth-device": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@octokit/auth-oauth-device/-/auth-oauth-device-4.0.5.tgz", + "integrity": "sha512-XyhoWRTzf2ZX0aZ52a6Ew5S5VBAfwwx1QnC2Np6Et3MWQpZjlREIcbcvVZtkNuXp6Z9EeiSLSDUqm3C+aMEHzQ==", + "license": "MIT", + "dependencies": { + "@octokit/oauth-methods": "^2.0.0", + "@octokit/request": "^6.0.0", + "@octokit/types": "^9.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-device/node_modules/@octokit/endpoint": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.6.tgz", + "integrity": "sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-device/node_modules/@octokit/openapi-types": { + "version": "18.1.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", + "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "license": "MIT" + }, + "node_modules/@octokit/auth-oauth-device/node_modules/@octokit/request": { + "version": "6.2.8", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.8.tgz", + "integrity": "sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^7.0.0", + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.7", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-device/node_modules/@octokit/request-error": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", + "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-device/node_modules/@octokit/types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", + "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^18.0.0" + } + }, + "node_modules/@octokit/auth-oauth-user": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@octokit/auth-oauth-user/-/auth-oauth-user-2.1.2.tgz", + "integrity": "sha512-kkRqNmFe7s5GQcojE3nSlF+AzYPpPv7kvP/xYEnE57584pixaFBH8Vovt+w5Y3E4zWUEOxjdLItmBTFAWECPAg==", + "license": "MIT", + "dependencies": { + "@octokit/auth-oauth-device": "^4.0.0", + "@octokit/oauth-methods": "^2.0.0", + "@octokit/request": "^6.0.0", + "@octokit/types": "^9.0.0", + "btoa-lite": "^1.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-user/node_modules/@octokit/endpoint": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.6.tgz", + "integrity": "sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-user/node_modules/@octokit/openapi-types": { + "version": "18.1.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", + "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "license": "MIT" + }, + "node_modules/@octokit/auth-oauth-user/node_modules/@octokit/request": { + "version": "6.2.8", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.8.tgz", + "integrity": "sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^7.0.0", + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.7", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-user/node_modules/@octokit/request-error": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", + "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-oauth-user/node_modules/@octokit/types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", + "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^18.0.0" + } + }, + "node_modules/@octokit/auth-token": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-4.0.0.tgz", + "integrity": "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==", + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@octokit/auth-unauthenticated": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@octokit/auth-unauthenticated/-/auth-unauthenticated-3.0.5.tgz", + "integrity": "sha512-yH2GPFcjrTvDWPwJWWCh0tPPtTL5SMgivgKPA+6v/XmYN6hGQkAto8JtZibSKOpf8ipmeYhLNWQ2UgW0GYILCw==", + "license": "MIT", + "dependencies": { + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/openapi-types": { + "version": "18.1.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", + "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "license": "MIT" + }, + "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/request-error": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", + "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", + "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^18.0.0" + } + }, + "node_modules/@octokit/core": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.2.tgz", + "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", + "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^4.0.0", + "@octokit/graphql": "^7.1.0", + "@octokit/request": "^8.4.1", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.0.0", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@octokit/endpoint": { + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz", + "integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@octokit/graphql": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-7.1.1.tgz", + "integrity": "sha512-3mkDltSfcDUoa176nlGoA32RGjeWjl3K7F/BwHwRMJUW/IteSa4bnSV8p2ThNkcIcZU2umkZWxwETSSCJf2Q7g==", + "license": "MIT", + "dependencies": { + "@octokit/request": "^8.4.1", + "@octokit/types": "^13.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@octokit/oauth-authorization-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@octokit/oauth-authorization-url/-/oauth-authorization-url-5.0.0.tgz", + "integrity": "sha512-y1WhN+ERDZTh0qZ4SR+zotgsQUE1ysKnvBt1hvDRB2WRzYtVKQjn97HEPzoehh66Fj9LwNdlZh+p6TJatT0zzg==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/oauth-methods": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@octokit/oauth-methods/-/oauth-methods-2.0.6.tgz", + "integrity": "sha512-l9Uml2iGN2aTWLZcm8hV+neBiFXAQ9+3sKiQe/sgumHlL6HDg0AQ8/l16xX/5jJvfxueqTW5CWbzd0MjnlfHZw==", + "license": "MIT", + "dependencies": { + "@octokit/oauth-authorization-url": "^5.0.0", + "@octokit/request": "^6.2.3", + "@octokit/request-error": "^3.0.3", + "@octokit/types": "^9.0.0", + "btoa-lite": "^1.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/oauth-methods/node_modules/@octokit/endpoint": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.6.tgz", + "integrity": "sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/oauth-methods/node_modules/@octokit/openapi-types": { + "version": "18.1.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-18.1.1.tgz", + "integrity": "sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==", + "license": "MIT" + }, + "node_modules/@octokit/oauth-methods/node_modules/@octokit/request": { + "version": "6.2.8", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.8.tgz", + "integrity": "sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^7.0.0", + "@octokit/request-error": "^3.0.0", + "@octokit/types": "^9.0.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.7", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/oauth-methods/node_modules/@octokit/request-error": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz", + "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^9.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@octokit/oauth-methods/node_modules/@octokit/types": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.3.2.tgz", + "integrity": "sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^18.0.0" + } + }, + "node_modules/@octokit/openapi-types": { + "version": "24.2.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-24.2.0.tgz", + "integrity": "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-enterprise-compatibility": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-enterprise-compatibility/-/plugin-enterprise-compatibility-1.3.0.tgz", + "integrity": "sha512-h34sMGdEOER/OKrZJ55v26ntdHb9OPfR1fwOx6Q4qYyyhWA104o11h9tFxnS/l41gED6WEI41Vu2G2zHDVC5lQ==", + "license": "MIT", + "dependencies": { + "@octokit/request-error": "^2.1.0", + "@octokit/types": "^6.0.3" + } + }, + "node_modules/@octokit/plugin-enterprise-compatibility/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-enterprise-compatibility/node_modules/@octokit/request-error": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz", + "integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.3", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "node_modules/@octokit/plugin-enterprise-compatibility/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/@octokit/plugin-paginate-rest": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-9.2.2.tgz", + "integrity": "sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^12.6.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/openapi-types": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", + "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/types": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", + "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^20.0.0" + } + }, + "node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-10.4.1.tgz", + "integrity": "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^12.6.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@octokit/core": "5" + } + }, + "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/openapi-types": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", + "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", + "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^20.0.0" + } + }, + "node_modules/@octokit/plugin-retry": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/@octokit/plugin-retry/-/plugin-retry-3.0.9.tgz", + "integrity": "sha512-r+fArdP5+TG6l1Rv/C9hVoty6tldw6cE2pRHNGmFPdyfrc696R6JjrQ3d7HdVqGwuzfyrcaLAKD7K8TX8aehUQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.3", + "bottleneck": "^2.15.3" + } + }, + "node_modules/@octokit/plugin-retry/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-retry/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/@octokit/request": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz", + "integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^9.0.6", + "@octokit/request-error": "^5.1.1", + "@octokit/types": "^13.1.0", + "universal-user-agent": "^6.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@octokit/request-error": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz", + "integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^13.1.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@octokit/rest": { + "version": "22.0.1", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-22.0.1.tgz", + "integrity": "sha512-Jzbhzl3CEexhnivb1iQ0KJ7s5vvjMWcmRtq5aUsKmKDrRW6z3r84ngmiFKFvpZjpiU/9/S6ITPFRpn5s/3uQJw==", + "license": "MIT", + "dependencies": { + "@octokit/core": "^7.0.6", + "@octokit/plugin-paginate-rest": "^14.0.0", + "@octokit/plugin-request-log": "^6.0.0", + "@octokit/plugin-rest-endpoint-methods": "^17.0.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/auth-token": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-6.0.0.tgz", + "integrity": "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==", + "license": "MIT", + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/core": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.6.tgz", + "integrity": "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==", + "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^6.0.0", + "@octokit/graphql": "^9.0.3", + "@octokit/request": "^10.0.6", + "@octokit/request-error": "^7.0.2", + "@octokit/types": "^16.0.0", + "before-after-hook": "^4.0.0", + "universal-user-agent": "^7.0.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/endpoint": { + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.2.tgz", + "integrity": "sha512-4zCpzP1fWc7QlqunZ5bSEjxc6yLAlRTnDwKtgXfcI/FxxGoqedDG8V2+xJ60bV2kODqcGB+nATdtap/XYq2NZQ==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0", + "universal-user-agent": "^7.0.2" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/graphql": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.3.tgz", + "integrity": "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==", + "license": "MIT", + "dependencies": { + "@octokit/request": "^10.0.6", + "@octokit/types": "^16.0.0", + "universal-user-agent": "^7.0.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/openapi-types": { + "version": "27.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-27.0.0.tgz", + "integrity": "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==", + "license": "MIT" + }, + "node_modules/@octokit/rest/node_modules/@octokit/plugin-paginate-rest": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-14.0.0.tgz", + "integrity": "sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/plugin-request-log": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-6.0.0.tgz", + "integrity": "sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "17.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-17.0.0.tgz", + "integrity": "sha512-B5yCyIlOJFPqUUeiD0cnBJwWJO8lkJs5d8+ze9QDP6SvfiXSz1BF+91+0MeI1d2yxgOhU/O+CvtiZ9jSkHhFAw==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/request": { + "version": "10.0.7", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.7.tgz", + "integrity": "sha512-v93h0i1yu4idj8qFPZwjehoJx4j3Ntn+JhXsdJrG9pYaX6j/XRz2RmasMUHtNgQD39nrv/VwTWSqK0RNXR8upA==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^11.0.2", + "@octokit/request-error": "^7.0.2", + "@octokit/types": "^16.0.0", + "fast-content-type-parse": "^3.0.0", + "universal-user-agent": "^7.0.2" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/request-error": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.0.tgz", + "integrity": "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/@octokit/rest/node_modules/@octokit/types": { + "version": "16.0.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-16.0.0.tgz", + "integrity": "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^27.0.0" + } + }, + "node_modules/@octokit/rest/node_modules/before-after-hook": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz", + "integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==", + "license": "Apache-2.0" + }, + "node_modules/@octokit/rest/node_modules/universal-user-agent": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", + "integrity": "sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==", + "license": "ISC" + }, + "node_modules/@octokit/types": { + "version": "13.10.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.10.0.tgz", + "integrity": "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^24.2.0" + } + }, + "node_modules/@octokit/webhooks": { + "version": "9.26.3", + "resolved": "https://registry.npmjs.org/@octokit/webhooks/-/webhooks-9.26.3.tgz", + "integrity": "sha512-DLGk+gzeVq5oK89Bo601txYmyrelMQ7Fi5EnjHE0Xs8CWicy2xkmnJMKptKJrBJpstqbd/9oeDFi/Zj2pudBDQ==", + "license": "MIT", + "dependencies": { + "@octokit/request-error": "^2.0.2", + "@octokit/webhooks-methods": "^2.0.0", + "@octokit/webhooks-types": "5.8.0", + "aggregate-error": "^3.1.0" + } + }, + "node_modules/@octokit/webhooks-methods": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@octokit/webhooks-methods/-/webhooks-methods-2.0.0.tgz", + "integrity": "sha512-35cfQ4YWlnZnmZKmIxlGPUPLtbkF8lr/A/1Sk1eC0ddLMwQN06dOuLc+dI3YLQS+T+MoNt3DIQ0NynwgKPilig==", + "license": "MIT" + }, + "node_modules/@octokit/webhooks-types": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@octokit/webhooks-types/-/webhooks-types-5.8.0.tgz", + "integrity": "sha512-8adktjIb76A7viIdayQSFuBEwOzwhDC+9yxZpKNHjfzrlostHCw0/N7JWpWMObfElwvJMk2fY2l1noENCk9wmw==", + "license": "MIT" + }, + "node_modules/@octokit/webhooks/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/@octokit/webhooks/node_modules/@octokit/request-error": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz", + "integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.3", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "node_modules/@octokit/webhooks/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/@probot/get-private-key": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@probot/get-private-key/-/get-private-key-1.2.1.tgz", + "integrity": "sha512-ejh5fK4d0zJES+3aR2IiD8+afuzgpe4Nr3UzTSKbBVU8+u8R/nVCQJawJ5s3QilzgXFftjYkGxZFvXkZ0+u4wA==", + "license": "ISC" + }, + "node_modules/@probot/octokit-plugin-config": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@probot/octokit-plugin-config/-/octokit-plugin-config-1.1.6.tgz", + "integrity": "sha512-L29wmnFvilzSfWn9tUgItxdLv0LJh2ICjma3FmLr80Spu3wZ9nHyRrKMo9R5/K2m7VuWmgoKnkgRt2zPzAQBEQ==", + "license": "MIT", + "dependencies": { + "@types/js-yaml": "^4.0.5", + "js-yaml": "^4.1.0" + }, + "peerDependencies": { + "@octokit/core": ">=3" + } + }, + "node_modules/@probot/octokit-plugin-config/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/@probot/octokit-plugin-config/node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@probot/pino": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@probot/pino/-/pino-2.5.0.tgz", + "integrity": "sha512-I7zI6MWP1wz9qvTY8U3wOWeRXY2NiuTDqf91v/LQl9oiffUHl+Z1YelRvNcvHbaUo/GK7E1mJr+Sw4dHuSGxpg==", + "license": "MIT", + "dependencies": { + "@sentry/node": "^7.119.2", + "pino-pretty": "^6.0.0", + "pump": "^3.0.0", + "readable-stream": "^3.6.0", + "split2": "^4.0.0" + }, + "bin": { + "pino-probot": "cli.js" + } + }, + "node_modules/@sentry-internal/tracing": { + "version": "7.120.4", + "resolved": "https://registry.npmjs.org/@sentry-internal/tracing/-/tracing-7.120.4.tgz", + "integrity": "sha512-Fz5+4XCg3akeoFK+K7g+d7HqGMjmnLoY2eJlpONJmaeT9pXY7yfUyXKZMmMajdE2LxxKJgQ2YKvSCaGVamTjHw==", + "license": "MIT", + "dependencies": { + "@sentry/core": "7.120.4", + "@sentry/types": "7.120.4", + "@sentry/utils": "7.120.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@sentry/core": { + "version": "7.120.4", + "resolved": "https://registry.npmjs.org/@sentry/core/-/core-7.120.4.tgz", + "integrity": "sha512-TXu3Q5kKiq8db9OXGkWyXUbIxMMuttB5vJ031yolOl5T/B69JRyAoKuojLBjRv1XX583gS1rSSoX8YXX7ATFGA==", + "license": "MIT", + "dependencies": { + "@sentry/types": "7.120.4", + "@sentry/utils": "7.120.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@sentry/integrations": { + "version": "7.120.4", + "resolved": "https://registry.npmjs.org/@sentry/integrations/-/integrations-7.120.4.tgz", + "integrity": "sha512-kkBTLk053XlhDCg7OkBQTIMF4puqFibeRO3E3YiVc4PGLnocXMaVpOSCkMqAc1k1kZ09UgGi8DxfQhnFEjUkpA==", + "license": "MIT", + "dependencies": { + "@sentry/core": "7.120.4", + "@sentry/types": "7.120.4", + "@sentry/utils": "7.120.4", + "localforage": "^1.8.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@sentry/node": { + "version": "7.120.4", + "resolved": "https://registry.npmjs.org/@sentry/node/-/node-7.120.4.tgz", + "integrity": "sha512-qq3wZAXXj2SRWhqErnGCSJKUhPSlZ+RGnCZjhfjHpP49KNpcd9YdPTIUsFMgeyjdh6Ew6aVCv23g1hTP0CHpYw==", + "license": "MIT", + "dependencies": { + "@sentry-internal/tracing": "7.120.4", + "@sentry/core": "7.120.4", + "@sentry/integrations": "7.120.4", + "@sentry/types": "7.120.4", + "@sentry/utils": "7.120.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@sentry/types": { + "version": "7.120.4", + "resolved": "https://registry.npmjs.org/@sentry/types/-/types-7.120.4.tgz", + "integrity": "sha512-cUq2hSSe6/qrU6oZsEP4InMI5VVdD86aypE+ENrQ6eZEVLTCYm1w6XhW1NvIu3UuWh7gZec4a9J7AFpYxki88Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@sentry/utils": { + "version": "7.120.4", + "resolved": "https://registry.npmjs.org/@sentry/utils/-/utils-7.120.4.tgz", + "integrity": "sha512-zCKpyDIWKHwtervNK2ZlaK8mMV7gVUijAgFeJStH+CU/imcdquizV3pFLlSQYRswG+Lbyd6CT/LGRh3IbtkCFw==", + "license": "MIT", + "dependencies": { + "@sentry/types": "7.120.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", + "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", + "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/btoa-lite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@types/btoa-lite/-/btoa-lite-1.0.2.tgz", + "integrity": "sha512-ZYbcE2x7yrvNFJiU7xJGrpF/ihpkM7zKgw8bha3LNJSesvTtUNxbpzaT7WXBIryf6jovisrxTBvymxMeLLj1Mg==", + "license": "MIT" + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", + "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/graceful-fs": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", + "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "license": "MIT" + }, + "node_modules/@types/ioredis": { + "version": "4.28.10", + "resolved": "https://registry.npmjs.org/@types/ioredis/-/ioredis-4.28.10.tgz", + "integrity": "sha512-69LyhUgrXdgcNDv7ogs1qXZomnfOEnSmrmMFqKgt1XMJxmoOSG/u3wYy13yACIfKuMJ8IhKgHafDO3sx19zVQQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", + "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", + "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", + "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.5.14", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", + "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/js-yaml": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz", + "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==", + "license": "MIT" + }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.10", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz", + "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==", + "license": "MIT", + "dependencies": { + "@types/ms": "*", + "@types/node": "*" + } + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "license": "MIT" + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.10.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", + "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/@types/pino": { + "version": "6.3.12", + "resolved": "https://registry.npmjs.org/@types/pino/-/pino-6.3.12.tgz", + "integrity": "sha512-dsLRTq8/4UtVSpJgl9aeqHvbh6pzdmjYD3C092SYgLD2TyoCqHpTJk6vp8DvCTGGc7iowZ2MoiYiVUUCcu7muw==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/pino-pretty": "*", + "@types/pino-std-serializers": "*", + "sonic-boom": "^2.1.0" + } + }, + "node_modules/@types/pino-http": { + "version": "5.8.4", + "resolved": "https://registry.npmjs.org/@types/pino-http/-/pino-http-5.8.4.tgz", + "integrity": "sha512-UTYBQ2acmJ2eK0w58vVtgZ9RAicFFndfrnWC1w5cBTf8zwn/HEy8O+H7psc03UZgTzHmlcuX8VkPRnRDEj+FUQ==", + "license": "MIT", + "dependencies": { + "@types/pino": "6.3" + } + }, + "node_modules/@types/pino-pretty": { + "version": "4.7.5", + "resolved": "https://registry.npmjs.org/@types/pino-pretty/-/pino-pretty-4.7.5.tgz", + "integrity": "sha512-rfHe6VIknk14DymxGqc9maGsRe8/HQSvM2u46EAz2XrS92qsAJnW16dpdFejBuZKD8cRJX6Aw6uVZqIQctMpAg==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/pino": "6.3" + } + }, + "node_modules/@types/pino-std-serializers": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@types/pino-std-serializers/-/pino-std-serializers-2.4.1.tgz", + "integrity": "sha512-17XcksO47M24IVTVKPeAByWUd3Oez7EbIjXpSbzMPhXVzgjGtrOa49gKBwxH9hb8dKv58OelsWQ+A1G1l9S3wQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "license": "MIT" + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/stack-utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", + "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vercel/ncc": { + "version": "0.38.4", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.38.4.tgz", + "integrity": "sha512-8LwjnlP39s08C08J5NstzriPvW1SP8Zfpp1BvC2sI35kPeZnHfxVkCwu4/+Wodgnd60UtT1n8K8zw+Mp7J9JmQ==", + "dev": true, + "license": "MIT", + "bin": { + "ncc": "dist/ncc/cli.js" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "license": "MIT", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "license": "MIT", + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/args": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/args/-/args-5.0.3.tgz", + "integrity": "sha512-h6k/zfFgusnv3i5TU08KQkVKuCPBtL/PWQbWkHUxvJrZ2nAyeaUupneemcrgn1xmqxPQsPIzwkUhOpoqPDRZuA==", + "license": "MIT", + "dependencies": { + "camelcase": "5.0.0", + "chalk": "2.4.2", + "leven": "2.1.0", + "mri": "1.1.4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/args/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/args/node_modules/camelcase": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.0.0.tgz", + "integrity": "sha512-faqwZqnWxbxn+F1d399ygeamQNy3lPp/H9H6rNrqYh4FSVCtcY+3cub1MxA8o9mDd55mM8Aghuu/kuyYA6VTsA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/args/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/args/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/args/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/args/node_modules/leven": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", + "integrity": "sha512-nvVPLpIHUxCUoRLrFqTgSxXJ614d8AgQoWl7zPe/2VadE8+1dpU3LBhowRuBAcuwruWtOdD8oYC9jDNJjXDPyA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/args/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/babel-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", + "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/transform": "^29.7.0", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.6.3", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", + "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", + "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-import-attributes": "^7.24.7", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5" + }, + "peerDependencies": { + "@babel/core": "^7.0.0 || ^8.0.0-0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", + "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", + "dev": true, + "license": "MIT", + "dependencies": { + "babel-plugin-jest-hoist": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.8.32", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.32.tgz", + "integrity": "sha512-OPz5aBThlyLFgxyhdwf/s2+8ab3OvT7AdTNvKHBwpXomIYeXqpUUuT8LrdtxZSsWJ4R4CU1un4XGh5Ez3nlTpw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/before-after-hook": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", + "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==", + "license": "Apache-2.0" + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/bottleneck": { + "version": "2.19.5", + "resolved": "https://registry.npmjs.org/bottleneck/-/bottleneck-2.19.5.tgz", + "integrity": "sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.0.tgz", + "integrity": "sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.8.25", + "caniuse-lite": "^1.0.30001754", + "electron-to-chromium": "^1.5.249", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.1.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-json-stable-stringify": "2.x" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "node_modules/btoa-lite": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/btoa-lite/-/btoa-lite-1.0.0.tgz", + "integrity": "sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA==", + "license": "MIT" + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001757", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001757.tgz", + "integrity": "sha512-r0nnL/I28Zi/yjk1el6ilj27tKcdjLsNqAOZr0yVjWPrSQyHgKI2INaEWw21bAQSv2LXRt1XuCS/GomNpWOxsQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/chalk/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/chalk/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/chardet": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.1.tgz", + "integrity": "sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==", + "license": "MIT" + }, + "node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.3.0.tgz", + "integrity": "sha512-/+40ljC3ONVnYIttjMWrlL51nItDAbBrq2upN8BPyvGU/2n5Oxw3tbNwORCaNuNqLJnxGqOfjUuhsv7l5Q4IsQ==", + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cliui/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/cliui/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", + "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", + "dev": true, + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "license": "MIT" + }, + "node_modules/colorette": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", + "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/console-table-printer": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.15.0.tgz", + "integrity": "sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw==", + "license": "MIT", + "dependencies": { + "simple-wcswidth": "^1.1.2" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" + }, + "bin": { + "create-jest": "bin/create-jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/dateformat": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", + "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dedent": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.0.tgz", + "integrity": "sha512-HGFtf8yhuhGhqO07SV79tRp+br4MnbdjeVxotpn1QBl30pcLLCQjX5b2295ll0fv8RKDKsmWYrl05usHM9CewQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/denque": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/denque/-/denque-1.5.1.tgz", + "integrity": "sha512-XwE+iZ4D6ZUB7mfYRMb5wByE8L74HCn30FBN7sWnXksWc1LO1bPDl67pBR9o/kC4z/xSNAwkMYcGgqDV3BE3Hw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/deprecation": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", + "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==", + "license": "ISC" + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/dotenv": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.6.0.tgz", + "integrity": "sha512-IrPdXQsk2BbzvCBGBOTmmSH5SodmqZNt4ERAZDmW4CT+tL8VtvinqywuANaFu4bOMWki16nqf0e4oC0QIaDr/g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=10" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.262", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.262.tgz", + "integrity": "sha512-NlAsMteRHek05jRUxUR0a5jpjYq9ykk6+kO0yRaMi5moe7u0fVIOeQ3Y30A8dIiWFBNUoQGi1ljb1i5VtS9WQQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.0.tgz", + "integrity": "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.0", + "@esbuild/android-arm": "0.27.0", + "@esbuild/android-arm64": "0.27.0", + "@esbuild/android-x64": "0.27.0", + "@esbuild/darwin-arm64": "0.27.0", + "@esbuild/darwin-x64": "0.27.0", + "@esbuild/freebsd-arm64": "0.27.0", + "@esbuild/freebsd-x64": "0.27.0", + "@esbuild/linux-arm": "0.27.0", + "@esbuild/linux-arm64": "0.27.0", + "@esbuild/linux-ia32": "0.27.0", + "@esbuild/linux-loong64": "0.27.0", + "@esbuild/linux-mips64el": "0.27.0", + "@esbuild/linux-ppc64": "0.27.0", + "@esbuild/linux-riscv64": "0.27.0", + "@esbuild/linux-s390x": "0.27.0", + "@esbuild/linux-x64": "0.27.0", + "@esbuild/netbsd-arm64": "0.27.0", + "@esbuild/netbsd-x64": "0.27.0", + "@esbuild/openbsd-arm64": "0.27.0", + "@esbuild/openbsd-x64": "0.27.0", + "@esbuild/openharmony-arm64": "0.27.0", + "@esbuild/sunos-x64": "0.27.0", + "@esbuild/win32-arm64": "0.27.0", + "@esbuild/win32-ia32": "0.27.0", + "@esbuild/win32-x64": "0.27.0" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/execa/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-handlebars": { + "version": "6.0.7", + "resolved": "https://registry.npmjs.org/express-handlebars/-/express-handlebars-6.0.7.tgz", + "integrity": "sha512-iYeMFpc/hMD+E6FNAZA5fgWeXnXr4rslOSPkeEV6TwdmpJ5lEXuWX0u9vFYs31P2MURctQq2batR09oeNj0LIg==", + "license": "BSD-3-Clause", + "dependencies": { + "glob": "^8.1.0", + "graceful-fs": "^4.2.10", + "handlebars": "^4.7.7" + }, + "engines": { + "node": ">=v12.22.9" + } + }, + "node_modules/express-handlebars/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/express-handlebars/node_modules/glob": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", + "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/express-handlebars/node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/fast-content-type-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-3.0.0.tgz", + "integrity": "sha512-ZvLdcY8P+N8mGQJahJV5G4U88CSvT1rP8ApL6uETe88MBXrBHAkZlSEySdUlyztF7ccb+Znos3TFqaepHxdhBg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-redact": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz", + "integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/fast-url-parser": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/fast-url-parser/-/fast-url-parser-1.1.3.tgz", + "integrity": "sha512-5jOCVXADYNuRkKFzNJ0dCCewsZiYo0dz8QNYljkOpFC6r2U4OBmKtvm/Tsuh4w1YYdDqDb31a8TVhBJ2OJKdqQ==", + "license": "MIT", + "dependencies": { + "punycode": "^1.3.2" + } + }, + "node_modules/fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bser": "2.1.1" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/flatstr": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/flatstr/-/flatstr-1.0.12.tgz", + "integrity": "sha512-4zPxDyhCyiN2wIAtSLI6gc82/EjqZc1onI4Mz/l0pWrAlsSfYH/2ZIcU+e3oA2wDwbzIWNKwa23F8rh6+DRWkw==", + "license": "MIT" + }, + "node_modules/form-data": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", + "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", + "license": "MIT" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "license": "MIT", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", + "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", + "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/handlebars": { + "version": "4.7.8", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz", + "integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.5", + "neo-async": "^2.6.2", + "source-map": "^0.6.1", + "wordwrap": "^1.0.0" + }, + "bin": { + "handlebars": "bin/handlebars" + }, + "engines": { + "node": ">=0.4.7" + }, + "optionalDependencies": { + "uglify-js": "^3.1.4" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/inquirer": { + "version": "12.11.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-12.11.1.tgz", + "integrity": "sha512-9VF7mrY+3OmsAfjH3yKz/pLbJ5z22E23hENKw3/LNSaA/sAt3v49bDRY+Ygct1xwuKT+U+cBfTzjCPySna69Qw==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^1.0.2", + "@inquirer/core": "^10.3.2", + "@inquirer/prompts": "^7.10.1", + "@inquirer/type": "^3.0.10", + "mute-stream": "^2.0.0", + "run-async": "^4.0.6", + "rxjs": "^7.8.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/ioredis": { + "version": "4.30.1", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-4.30.1.tgz", + "integrity": "sha512-17Ed70njJ7wT7JZsdTVLb0j/cmwHwfQCFu+AP6jY7nFKd+CA7MBW7nX121mM64eT8S9ekAVtYYt8nGQPmm3euA==", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "^1.0.2", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.1", + "denque": "^1.1.0", + "lodash.defaults": "^4.2.0", + "lodash.flatten": "^4.4.0", + "lodash.isarguments": "^3.1.0", + "p-map": "^2.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT" + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-network-error": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.0.tgz", + "integrity": "sha512-6oIwpsgRfnDiyEDLMay/GqCl3HoAtH5+RUKW29gYkL0QA+ipzpDLA16yQs7/RHCSu+BwgbJaOUqa4A99qNVQVw==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-plain-object": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", + "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", + "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.23.9", + "@babel/parser": "^7.23.9", + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-instrument/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-cli": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-diff": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", + "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-docblock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-environment-node": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", + "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", + "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", + "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-mock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", + "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", + "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "natural-compare": "^1.4.0", + "pretty-format": "^29.7.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", + "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-watcher": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", + "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.7.0", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", + "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/jmespath": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", + "integrity": "sha512-+kHj8HXArPfpPEKGLZ+kB5ONRTCiGQXo8RQYL0hH8t6pWXUBBK5KkkQmTNOwKK4LEsd0yTsgtjJVm4UBSZea4w==", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/js-tiktoken": { + "version": "1.0.21", + "resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz", + "integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.5.1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jsonwebtoken/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/langchain": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/langchain/-/langchain-1.1.1.tgz", + "integrity": "sha512-z7cOFhLOzbu/lRlIE8GZ5rlfi7obvvHThhMdts1KsUBusJmWLmh1Yik28MHYzJRXclUbqs4u/9D2yNmr36wf0A==", + "license": "MIT", + "dependencies": { + "@langchain/langgraph": "^1.0.0", + "@langchain/langgraph-checkpoint": "^1.0.0", + "langsmith": "~0.3.74", + "uuid": "^10.0.0", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "1.1.0" + } + }, + "node_modules/langsmith": { + "version": "0.3.82", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.82.tgz", + "integrity": "sha512-RTcxtRm0zp2lV+pMesMW7EZSsIlqN7OmR2F6sZ/sOFQwmcLVl+VErMPV4VkX4Sycs4/EIAFT5hpr36EqiHoikQ==", + "license": "MIT", + "dependencies": { + "@types/uuid": "^10.0.0", + "chalk": "^4.1.2", + "console-table-printer": "^2.12.1", + "p-queue": "^6.6.2", + "semver": "^7.6.3", + "uuid": "^10.0.0" + }, + "peerDependencies": { + "@opentelemetry/api": "*", + "@opentelemetry/exporter-trace-otlp-proto": "*", + "@opentelemetry/sdk-trace-base": "*", + "openai": "*" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-proto": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "openai": { + "optional": true + } + } + }, + "node_modules/langsmith/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lie": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz", + "integrity": "sha512-RiNhHysUjhrDQntfYSfY4MU24coXXdEOgw9WGcKHNeEwffDYbF//u87M1EWaMGzuFoSbqW0C9C6lEEhDOAswfw==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/load-json-file": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-5.3.0.tgz", + "integrity": "sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.15", + "parse-json": "^4.0.0", + "pify": "^4.0.1", + "strip-bom": "^3.0.0", + "type-fest": "^0.3.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/load-json-file/node_modules/parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==", + "license": "MIT", + "dependencies": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/load-json-file/node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/load-json-file/node_modules/type-fest": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.3.1.tgz", + "integrity": "sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=6" + } + }, + "node_modules/localforage": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/localforage/-/localforage-1.10.0.tgz", + "integrity": "sha512-14/H1aX7hzBBmmh7sGPd+AOMkkIrHM3Z1PAyGgZigA1H1p5O5ANnMyWzvpAETtG68/dC4pC0ncy3+PPGzXZHPg==", + "license": "Apache-2.0", + "dependencies": { + "lie": "3.1.1" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" + }, + "node_modules/lodash.flatten": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==", + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", + "integrity": "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==", + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mri": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.1.4.tgz", + "integrity": "sha512-6y7IjGPm8AzlvoUrwAaw1tLnUBudaS3752vcd8JtrpGGQn+rXIe63LFVHm/YMwtqAuh+LJPCFdlLYPWM1nYn6w==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/mute-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-2.0.0.tgz", + "integrity": "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "license": "MIT" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/octokit-auth-probot": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/octokit-auth-probot/-/octokit-auth-probot-1.2.9.tgz", + "integrity": "sha512-mMjw6Y760EwJnW2tSVooJK8BMdsG6D40SoCclnefVf/5yWjaNVquEu8NREBVWb60OwbpnMEz4vREXHB5xdMFYQ==", + "license": "ISC", + "dependencies": { + "@octokit/auth-app": "^4.0.2", + "@octokit/auth-token": "^3.0.0", + "@octokit/auth-unauthenticated": "^3.0.0", + "@octokit/types": "^8.0.0" + }, + "peerDependencies": { + "@octokit/core": ">=3.2" + } + }, + "node_modules/octokit-auth-probot/node_modules/@octokit/auth-token": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-3.0.4.tgz", + "integrity": "sha512-TWFX7cZF2LXoCvdmJWY7XVPi74aSY0+FfBZNSXEXFkMpjcqsQwDSYVv5FhRFaI0V1ECnwbz4j59T/G+rXNWaIQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/octokit-auth-probot/node_modules/@octokit/openapi-types": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-14.0.0.tgz", + "integrity": "sha512-HNWisMYlR8VCnNurDU6os2ikx0s0VyEjDYHNS/h4cgb8DeOxQ0n72HyinUtdDVxJhFy3FWLGl0DJhfEWk3P5Iw==", + "license": "MIT" + }, + "node_modules/octokit-auth-probot/node_modules/@octokit/types": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-8.2.1.tgz", + "integrity": "sha512-8oWMUji8be66q2B9PmEIUyQm00VPDPun07umUWSaCwxmeaquFBro4Hcc3ruVoDo3zkQyZBlRvhIMEYS3pBhanw==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^14.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/openai": { + "version": "6.9.1", + "resolved": "https://registry.npmjs.org/openai/-/openai-6.9.1.tgz", + "integrity": "sha512-vQ5Rlt0ZgB3/BNmTa7bIijYFhz3YBceAA3Z4JuoMSBftBF9YqFHIEhZakSs+O/Ad7EaoEimZvHxD5ylRjN11Lg==", + "license": "Apache-2.0", + "bin": { + "openai": "bin/cli" + }, + "peerDependencies": { + "ws": "^8.18.0", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/ora": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/ora/-/ora-9.0.0.tgz", + "integrity": "sha512-m0pg2zscbYgWbqRR6ABga5c3sZdEon7bSgjnlXC64kxtxLOyjRcbbUkLj7HFyy/FTD+P2xdBWu8snGhYI0jc4A==", + "license": "MIT", + "dependencies": { + "chalk": "^5.6.2", + "cli-cursor": "^5.0.0", + "cli-spinners": "^3.2.0", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.1.0", + "log-symbols": "^7.0.1", + "stdin-discarder": "^0.2.2", + "string-width": "^8.1.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ora/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-map": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz", + "integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-7.1.0.tgz", + "integrity": "sha512-xL4PiFRQa/f9L9ZvR4/gUCRNus4N8YX80ku8kv9Jqz+ZokkiZLM0bcvX0gm1F3PDi9SPRsww1BDsTWgE6Y1GLQ==", + "license": "MIT", + "dependencies": { + "is-network-error": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pino": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-6.14.0.tgz", + "integrity": "sha512-iuhEDel3Z3hF9Jfe44DPXR8l07bhjuFY3GMHIXbjnY9XcafbyDDwl2sN2vw2GjMPf5Nkoe+OFao7ffn9SXaKDg==", + "license": "MIT", + "dependencies": { + "fast-redact": "^3.0.0", + "fast-safe-stringify": "^2.0.8", + "flatstr": "^1.0.12", + "pino-std-serializers": "^3.1.0", + "process-warning": "^1.0.0", + "quick-format-unescaped": "^4.0.3", + "sonic-boom": "^1.0.2" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-http": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/pino-http/-/pino-http-5.8.0.tgz", + "integrity": "sha512-YwXiyRb9y0WCD1P9PcxuJuh3Dc5qmXde/paJE86UGYRdiFOi828hR9iUGmk5gaw6NBT9gLtKANOHFimvh19U5w==", + "license": "MIT", + "dependencies": { + "fast-url-parser": "^1.1.3", + "pino": "^6.13.0", + "pino-std-serializers": "^4.0.0" + } + }, + "node_modules/pino-http/node_modules/pino-std-serializers": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-4.0.0.tgz", + "integrity": "sha512-cK0pekc1Kjy5w9V2/n+8MkZwusa6EyyxfeQCB799CQRhRt/CqYKiWs5adeu8Shve2ZNffvfC/7J64A2PJo1W/Q==", + "license": "MIT" + }, + "node_modules/pino-pretty": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-6.0.0.tgz", + "integrity": "sha512-jyeR2fXXWc68st1DTTM5NhkHlx8p+1fKZMfm84Jwq+jSw08IwAjNaZBZR6ts69hhPOfOjg/NiE1HYW7vBRPL3A==", + "license": "MIT", + "dependencies": { + "@hapi/bourne": "^2.0.0", + "args": "^5.0.1", + "colorette": "^1.3.0", + "dateformat": "^4.5.1", + "fast-safe-stringify": "^2.0.7", + "jmespath": "^0.15.0", + "joycon": "^3.0.0", + "pump": "^3.0.0", + "readable-stream": "^3.6.0", + "rfdc": "^1.3.0", + "split2": "^3.1.1", + "strip-json-comments": "^3.1.1" + }, + "bin": { + "pino-pretty": "bin.js" + } + }, + "node_modules/pino-pretty/node_modules/split2": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/split2/-/split2-3.2.2.tgz", + "integrity": "sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg==", + "license": "ISC", + "dependencies": { + "readable-stream": "^3.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-3.2.0.tgz", + "integrity": "sha512-EqX4pwDPrt3MuOAAUBMU0Tk5kR/YcCM5fNPEzgCO2zJ5HfX0vbiH9HbJglnyeQsN96Kznae6MWD47pZB5avTrg==", + "license": "MIT" + }, + "node_modules/pino/node_modules/sonic-boom": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-1.4.1.tgz", + "integrity": "sha512-LRHh/A8tpW7ru89lrlkU4AszXt1dbwSjVWguGrmlxE7tawVmDBlI1PILMkXAxJTwqhgsEeTHzj36D5CmHgQmNg==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0", + "flatstr": "^1.0.12" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-conf": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/pkg-conf/-/pkg-conf-3.1.0.tgz", + "integrity": "sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ==", + "license": "MIT", + "dependencies": { + "find-up": "^3.0.0", + "load-json-file": "^5.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "license": "MIT", + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "license": "MIT", + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-conf/node_modules/p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-conf/node_modules/path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/probot": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/probot/-/probot-12.4.0.tgz", + "integrity": "sha512-DbW4ME9rzGVwnsFjoWWxKtRvnxPlFaCg726ge1sYHwZ3UzMlcF3B8Qf7MptfhGRyFw8sSCqsbgzb0E5d/BrQEA==", + "license": "ISC", + "dependencies": { + "@octokit/core": "^3.6.0", + "@octokit/plugin-enterprise-compatibility": "^1.2.8", + "@octokit/plugin-paginate-rest": "^2.6.2", + "@octokit/plugin-rest-endpoint-methods": "^5.0.1", + "@octokit/plugin-retry": "^3.0.6", + "@octokit/plugin-throttling": "^3.3.4", + "@octokit/types": "^8.0.0", + "@octokit/webhooks": "^9.26.3", + "@probot/get-private-key": "^1.1.0", + "@probot/octokit-plugin-config": "^1.0.0", + "@probot/pino": "^2.2.0", + "@types/express": "^4.17.9", + "@types/ioredis": "^4.27.1", + "@types/pino": "^6.3.4", + "@types/pino-http": "^5.0.6", + "commander": "^6.2.0", + "deepmerge": "^4.2.2", + "deprecation": "^2.3.1", + "dotenv": "^8.2.0", + "eventsource": "^2.0.2", + "express": "^4.17.1", + "express-handlebars": "^6.0.3", + "ioredis": "^4.27.8", + "js-yaml": "^3.14.1", + "lru-cache": "^6.0.0", + "octokit-auth-probot": "^1.2.6", + "pino": "^6.14.0", + "pino-http": "^5.3.0", + "pkg-conf": "^3.1.0", + "resolve": "^1.19.0", + "semver": "^7.3.4", + "update-dotenv": "^1.1.1", + "uuid": "^8.3.2" + }, + "bin": { + "probot": "bin/probot.js" + }, + "engines": { + "node": ">=10.21" + } + }, + "node_modules/probot/node_modules/@octokit/auth-token": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.5.0.tgz", + "integrity": "sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.3" + } + }, + "node_modules/probot/node_modules/@octokit/auth-token/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/auth-token/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/core": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.6.0.tgz", + "integrity": "sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q==", + "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^2.4.4", + "@octokit/graphql": "^4.5.8", + "@octokit/request": "^5.6.3", + "@octokit/request-error": "^2.0.5", + "@octokit/types": "^6.0.3", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/probot/node_modules/@octokit/core/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/core/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/endpoint": { + "version": "6.0.12", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.12.tgz", + "integrity": "sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.3", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/probot/node_modules/@octokit/endpoint/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/endpoint/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/graphql": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.8.0.tgz", + "integrity": "sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==", + "license": "MIT", + "dependencies": { + "@octokit/request": "^5.6.0", + "@octokit/types": "^6.0.3", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/probot/node_modules/@octokit/graphql/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/graphql/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/openapi-types": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-14.0.0.tgz", + "integrity": "sha512-HNWisMYlR8VCnNurDU6os2ikx0s0VyEjDYHNS/h4cgb8DeOxQ0n72HyinUtdDVxJhFy3FWLGl0DJhfEWk3P5Iw==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/plugin-paginate-rest": { + "version": "2.21.3", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz", + "integrity": "sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.40.0" + }, + "peerDependencies": { + "@octokit/core": ">=2" + } + }, + "node_modules/probot/node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "5.16.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz", + "integrity": "sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.39.0", + "deprecation": "^2.3.1" + }, + "peerDependencies": { + "@octokit/core": ">=3" + } + }, + "node_modules/probot/node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/plugin-throttling": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-throttling/-/plugin-throttling-3.7.0.tgz", + "integrity": "sha512-qrKT1Yl/KuwGSC6/oHpLBot3ooC9rq0/ryDYBCpkRtoj+R8T47xTMDT6Tk2CxWopFota/8Pi/2SqArqwC0JPow==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.1", + "bottleneck": "^2.15.3" + }, + "peerDependencies": { + "@octokit/core": "^3.5.0" + } + }, + "node_modules/probot/node_modules/@octokit/plugin-throttling/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/plugin-throttling/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/request": { + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz", + "integrity": "sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==", + "license": "MIT", + "dependencies": { + "@octokit/endpoint": "^6.0.1", + "@octokit/request-error": "^2.1.0", + "@octokit/types": "^6.16.1", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.7", + "universal-user-agent": "^6.0.0" + } + }, + "node_modules/probot/node_modules/@octokit/request-error": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz", + "integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.3", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "node_modules/probot/node_modules/@octokit/request-error/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/request-error/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/request/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/probot/node_modules/@octokit/request/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, + "node_modules/probot/node_modules/@octokit/types": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-8.2.1.tgz", + "integrity": "sha512-8oWMUji8be66q2B9PmEIUyQm00VPDPun07umUWSaCwxmeaquFBro4Hcc3ruVoDo3zkQyZBlRvhIMEYS3pBhanw==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^14.0.0" + } + }, + "node_modules/probot/node_modules/commander": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", + "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/probot/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/probot/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/probot/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/probot/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/process-warning": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-1.0.0.tgz", + "integrity": "sha512-du4wfLyj4yCZq1VupnVSZmRsPJsNuxoDQFdCFHLaYiEbFBD7QE0a+I4D7hOxrVnh78QE/YipFAj9lXHiXocV+Q==", + "license": "MIT" + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", + "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", + "license": "MIT" + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.3.tgz", + "integrity": "sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/run-async": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-4.0.6.tgz", + "integrity": "sha512-IoDlSLTs3Yq593mb3ZoKWKXMNu3UpObxhgA/Xuid5p4bbfi2jdY1Hj0m1K+0/tEuQTxIGMhQDqGjKb7RuxGpAQ==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-wcswidth": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz", + "integrity": "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==", + "license": "MIT" + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/sonic-boom": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-2.8.0.tgz", + "integrity": "sha512-kuonw1YOYYNOve5iHdSahXPOK49GqwA+LZhI6Wz/l0rP57iKyXXIHaRagOBHAPmGwJC6od2Z9zgvZ5loSgMlVg==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "license": "BSD-3-Clause" + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/stdin-discarder": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", + "integrity": "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-width": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.1.0.tgz", + "integrity": "sha512-Kxl3KJGb/gxkaUMOjRsQ8IrXiGW75O4E3RPjFIINOVH8AMl2SQ/yWdTzWwF3FevIX9LcMAjJW+GRwAlAbTSXdg==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, + "node_modules/ts-jest": { + "version": "29.4.5", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.5.tgz", + "integrity": "sha512-HO3GyiWn2qvTQA4kTgjDcXiMwYQt68a1Y8+JuLRVpdIzm+UOLSHgl/XqR4c6nzJkq5rOkjc02O2I7P7l/Yof0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "bs-logger": "^0.2.6", + "fast-json-stable-stringify": "^2.1.0", + "handlebars": "^4.7.8", + "json5": "^2.2.3", + "lodash.memoize": "^4.1.2", + "make-error": "^1.3.6", + "semver": "^7.7.3", + "type-fest": "^4.41.0", + "yargs-parser": "^21.1.1" + }, + "bin": { + "ts-jest": "cli.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0-beta.0 <8", + "@jest/transform": "^29.0.0 || ^30.0.0", + "@jest/types": "^29.0.0 || ^30.0.0", + "babel-jest": "^29.0.0 || ^30.0.0", + "jest": "^29.0.0 || ^30.0.0", + "jest-util": "^29.0.0 || ^30.0.0", + "typescript": ">=4.3 <6" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@jest/transform": { + "optional": true + }, + "@jest/types": { + "optional": true + }, + "babel-jest": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jest-util": { + "optional": true + } + } + }, + "node_modules/ts-jest/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ts-jest/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tsx": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", + "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", + "license": "MIT", + "engines": { + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "license": "BSD-2-Clause", + "optional": true, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/undici": { + "version": "5.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz", + "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==", + "license": "MIT", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/universal-github-app-jwt": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/universal-github-app-jwt/-/universal-github-app-jwt-1.2.0.tgz", + "integrity": "sha512-dncpMpnsKBk0eetwfN8D8OUHGfiDhhJ+mtsbMl+7PfW7mYjiH8LIcqRmYMtzYLgSh47HjfdBtrBwIQ/gizKR3g==", + "license": "MIT", + "dependencies": { + "@types/jsonwebtoken": "^9.0.0", + "jsonwebtoken": "^9.0.2" + } + }, + "node_modules/universal-user-agent": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", + "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==", + "license": "ISC" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.4.tgz", + "integrity": "sha512-q0SPT4xyU84saUX+tomz1WLkxUbuaJnR1xWt17M7fJtEJigJeWUNGUqrauFXsHnqev9y9JTRGwk13tFBuKby4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/update-dotenv": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/update-dotenv/-/update-dotenv-1.1.1.tgz", + "integrity": "sha512-3cIC18In/t0X/yH793c00qqxcKD8jVCgNOPif/fGQkFpYMGecM9YAc+kaAKXuZsM2dE9I9wFI7KvAuNX22SGMQ==", + "license": "ISC", + "peerDependencies": { + "dotenv": "*" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/v8-to-istanbul": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", + "dev": true, + "license": "ISC", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "license": "MIT" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "dev": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/write-file-atomic/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoctocolors": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.1.2.tgz", + "integrity": "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoctocolors-cjs": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/yoctocolors-cjs/-/yoctocolors-cjs-2.1.3.tgz", + "integrity": "sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.13.tgz", + "integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json index 8e7df7d..77755e4 100644 --- a/package.json +++ b/package.json @@ -14,29 +14,34 @@ ], "scripts": { "build": "npm run build:tsc && npm run build:action", + "build:clean": "rimraf dist && npm run build", "build:tsc": "tsc", - "build:action": "ncc build src/action.ts -o dist --source-map --no-source-map-register", + "build:action": "node -e \"try{require('fs').unlinkSync('dist/index.js')}catch(e){}\" && node -e \"try{require('fs').unlinkSync('dist/index.js.map')}catch(e){}\" && node -e \"try{require('fs').unlinkSync('dist/index.d.ts')}catch(e){}\" && ncc build src/action.ts -o dist --no-source-map-register", "build:probot": "npm run build:tsc", "package": "npm run build", "prepublishOnly": "npm run build", "dev": "tsx src/index.ts", "dev:action": "tsx src/action.ts", "start": "node ./dist/index.js", - "test": "jest" + "cli": "node dist/cli/index.js", + "test": "jest", + "test:watch": "jest --watch", + "test:coverage": "jest --coverage" }, "dependencies": { "@actions/core": "^1.11.1", "@actions/github": "^6.0.1", "@anthropic-ai/sdk": "^0.24.3", - "@langchain/anthropic": "^1.0.0", - "@langchain/core": "^1.0.3", - "@langchain/google-genai": "^1.0.0", - "@langchain/langgraph": "^1.0.1", - "@langchain/openai": "^1.0.0", + "@langchain/anthropic": "^1.1.3", + "@langchain/core": "^1.1.0", + "@langchain/google-genai": "^2.0.0", + "@langchain/langgraph": "^1.0.2", + "@langchain/openai": "^1.1.3", + "@octokit/rest": "^22.0.1", "chalk": "^4.1.2", "commander": "^14.0.2", "inquirer": "^12.10.0", - "langchain": "^1.0.3", + "langchain": "^1.1.1", "ora": "^9.0.0", "probot": "^12.3.1" }, @@ -47,7 +52,8 @@ "jest": "^29.7.0", "ts-jest": "^29.1.2", "tsx": "^4.0.0", - "typescript": "^5.2.2" + "typescript": "^5.2.2", + "zod": "^4.1.13" }, "engines": { "node": ">=18.0.0" diff --git a/src/cli/commands/analyze.command.ts b/src/cli/commands/analyze.command.ts index 680a57c..ba82f01 100644 --- a/src/cli/commands/analyze.command.ts +++ b/src/cli/commands/analyze.command.ts @@ -5,6 +5,8 @@ import ora from 'ora'; import { PRAnalyzerAgent } from '../../agents/pr-analyzer-agent.js'; import { loadUserConfig, getApiKey } from '../utils/config-loader.js'; import { archDocsExists } from '../../utils/arch-docs-parser.js'; +import { resolveDefaultBranch } from '../../utils/branch-resolver.js'; +import { ConfigurationError, GitHubAPIError, GitError } from '../../utils/errors.js'; interface AnalyzeOptions { diff?: string; @@ -73,54 +75,50 @@ async function getUntrackedFiles(): Promise { /** * Get git diff with optional command */ -async function getGitDiff(command?: string): Promise { +async function getGitDiff(command?: string, defaultBranch?: string): Promise { try { let diff: string = ''; const maxBuffer = 200 * 1024 * 1024; // 200MB - if (!command || command === 'origin/main') { + if (!command || command === 'default') { + // Use resolved default branch + const branch = defaultBranch || 'origin/main'; try { - diff = execSync('git diff origin/main', { + diff = execSync(`git diff ${branch}`, { encoding: 'utf-8', maxBuffer, }); - } catch { - // Fallback to main branch - try { - console.log(chalk.yellow('⚠️ origin/main not found, trying main branch...')); - diff = execSync('git diff main', { - encoding: 'utf-8', - maxBuffer, - }); - } catch { - // Fallback to origin/master - try { - console.log(chalk.yellow('⚠️ main not found, trying origin/master branch...')); - diff = execSync('git diff origin/master', { - encoding: 'utf-8', - maxBuffer, - }); - } catch { - // Final fallback to master - console.log(chalk.yellow('⚠️ origin/master not found, trying master branch...')); - diff = execSync('git diff master', { - encoding: 'utf-8', - maxBuffer, - }); - } - } + } catch (error: any) { + throw new GitError( + `Failed to get diff from branch "${branch}". The branch may not exist locally. Run: git fetch origin && git checkout ${branch}`, + `git diff ${branch}`, + ); } } else if (command === 'staged') { - diff = execSync('git diff --staged', { - encoding: 'utf-8', - maxBuffer, - }); + try { + diff = execSync('git diff --staged', { + encoding: 'utf-8', + maxBuffer, + }); + } catch (error: any) { + throw new GitError( + 'Failed to get staged changes. Make sure you have staged files with: git add ', + 'git diff --staged', + ); + } } else { // Custom branch or reference - diff = execSync(`git diff ${command}`, { - encoding: 'utf-8', - maxBuffer, - }); + try { + diff = execSync(`git diff ${command}`, { + encoding: 'utf-8', + maxBuffer, + }); + } catch (error: any) { + throw new GitError( + `Failed to get diff from "${command}". The branch or reference may not exist.`, + `git diff ${command}`, + ); + } } // Normalize diff (remove trailing whitespace but preserve structure) @@ -251,10 +249,24 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { const spinner = ora('Initializing PR analysis...').start(); try { - // Load configuration - const config = await loadUserConfig(false); + // Load and validate configuration + let config; + try { + config = await loadUserConfig(false, true); // Validate config + } catch (error) { + spinner.fail('Configuration error'); + if (error instanceof ConfigurationError) { + console.error(chalk.red(`\n❌ ${error.message}`)); + process.exit(1); + } + throw error; + } // Get provider and API key from config or environment + if (options.verbose) { + console.log(chalk.gray(` Debug: options.provider: ${options.provider || 'undefined'}`)); + console.log(chalk.gray(` Debug: config.ai?.provider: ${config.ai?.provider || 'undefined'}`)); + } const provider = (options.provider || config.ai?.provider || 'anthropic').toLowerCase() as 'anthropic' | 'openai' | 'google'; const apiKey = getApiKey(provider, config); @@ -271,6 +283,41 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { spinner.succeed(`Using AI provider: ${provider}`); + // Resolve default branch if needed + let defaultBranch: string | undefined; + if (!options.diff && !options.file && !options.staged && !options.branch) { + spinner.text = 'Resolving default branch...'; + try { + const branchResult = await resolveDefaultBranch({ + configBranch: config.git?.defaultBranch, + githubToken: process.env.GITHUB_TOKEN, + fallbackToGit: true, + }); + + defaultBranch = branchResult.branch; + + if (branchResult.warning && options.verbose) { + console.log(chalk.yellow(`\n⚠️ ${branchResult.warning}`)); + } + + if (options.verbose) { + console.log(chalk.gray(` Using branch: ${defaultBranch} (source: ${branchResult.source})`)); + } + } catch (error) { + if (error instanceof GitHubAPIError || error instanceof ConfigurationError) { + spinner.fail('Branch resolution failed'); + console.error(chalk.red(`\n❌ ${error.message}`)); + if (error instanceof GitHubAPIError) { + console.error(chalk.gray('\n💡 You can override the branch with:')); + console.error(chalk.gray(' pr-agent analyze --branch ')); + console.error(chalk.gray(' Or set git.defaultBranch in config: pr-agent config --set git.defaultBranch=')); + } + process.exit(1); + } + throw error; + } + } + // Determine analysis mode const mode: AnalysisMode = { summary: options.summary || options.full || false, @@ -289,16 +336,30 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { // Get the diff let diff: string; - if (options.diff) { - diff = options.diff; - } else if (options.file) { - diff = fs.readFileSync(options.file, 'utf-8'); - } else if (options.staged) { - diff = await getGitDiff('staged'); - } else if (options.branch) { - diff = await getGitDiff(options.branch); - } else { - diff = await getGitDiff(); + try { + if (options.diff) { + diff = options.diff; + } else if (options.file) { + diff = fs.readFileSync(options.file, 'utf-8'); + } else if (options.staged) { + diff = await getGitDiff('staged'); + } else if (options.branch) { + diff = await getGitDiff(options.branch); + } else { + diff = await getGitDiff('default', defaultBranch); + } + } catch (error) { + spinner.fail('Failed to get diff'); + if (error instanceof GitError) { + console.error(chalk.red(`\n❌ ${error.message}`)); + console.error(chalk.gray('\n💡 Troubleshooting:')); + console.error(chalk.gray(' • Make sure you are in a git repository')); + console.error(chalk.gray(' • Check that the branch exists: git branch -a')); + console.error(chalk.gray(' • Fetch remote branches: git fetch origin')); + console.error(chalk.gray(' • Use --branch flag to specify a different branch')); + process.exit(1); + } + throw error; } if (!diff) { @@ -351,15 +412,43 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { displayAgentResults(result, mode, options.verbose || false); } catch (error: any) { spinner.fail('Analysis failed'); - if (error.message && error.message.includes('rate-limits')) { + + // Handle specific error types with user-friendly messages + if (error instanceof ConfigurationError) { + console.error(chalk.red(`\n❌ Configuration Error: ${error.message}`)); + console.error(chalk.gray('\n💡 Run: pr-agent config --init to fix configuration')); + process.exit(1); + } else if (error instanceof GitHubAPIError) { + console.error(chalk.red(`\n❌ GitHub API Error: ${error.message}`)); + if (error.statusCode === 401 || error.statusCode === 403) { + console.error(chalk.gray('\n💡 Check your GITHUB_TOKEN environment variable')); + } + process.exit(1); + } else if (error instanceof GitError) { + console.error(chalk.red(`\n❌ Git Error: ${error.message}`)); + process.exit(1); + } else if (error.message && error.message.includes('rate-limits')) { console.error(chalk.red.bold('\n❌ Rate limit error: Your diff is too large for the API.')); console.error( chalk.yellow('\n💡 Try reducing the diff size or adjusting maxTokens in config'), ); + process.exit(1); } else { - console.error(chalk.red('\nError:'), error instanceof Error ? error.message : error); + // Generic error - sanitize output to avoid leaking sensitive info + const errorMessage = error.message || String(error); + // Don't log full stack traces or potential secrets + const sanitizedMessage = errorMessage + .replace(/sk-[a-zA-Z0-9_-]+/g, 'sk-***') + .replace(/ghp_[a-zA-Z0-9]+/g, 'ghp_***') + .substring(0, 500); // Limit length + + console.error(chalk.red(`\n❌ Error: ${sanitizedMessage}`)); + if (options.verbose && error.stack) { + console.error(chalk.gray('\nStack trace:')); + console.error(chalk.gray(error.stack.substring(0, 1000))); + } + process.exit(1); } - process.exit(1); } } diff --git a/src/cli/commands/config.command.ts b/src/cli/commands/config.command.ts index 9322bb8..9e553cd 100644 --- a/src/cli/commands/config.command.ts +++ b/src/cli/commands/config.command.ts @@ -129,6 +129,7 @@ async function initializeConfig(): Promise { ]; } else if (provider === 'openai') { modelChoices = [ + { name: 'GPT-5.1 (Latest)', value: 'gpt-5.1' }, { name: 'GPT-4 Turbo', value: 'gpt-4-turbo-preview' }, { name: 'GPT-4', value: 'gpt-4' }, { name: 'GPT-3.5 Turbo', value: 'gpt-3.5-turbo' }, diff --git a/src/cli/commands/help.command.ts b/src/cli/commands/help.command.ts index 0fb6d6e..437f0e3 100644 --- a/src/cli/commands/help.command.ts +++ b/src/cli/commands/help.command.ts @@ -42,6 +42,14 @@ export function displayHelp(): void { console.log(' --branch Analyze against specific branch'); console.log(' --file Read diff from file'); console.log(' --diff Provide diff directly\n'); + + console.log(chalk.dim(' Default Branch Detection:')); + console.log(' The default branch is determined in this order:'); + console.log(' 1. Config file (git.defaultBranch)'); + console.log(' 2. GitHub API (if GITHUB_TOKEN is set)'); + console.log(' 3. Git commands (local detection)'); + console.log(' 4. Fallback to origin/main'); + console.log(' Use --branch to override for a single analysis\n'); console.log(chalk.dim(' Advanced Options:')); console.log(' --provider AI provider: anthropic|openai|google'); @@ -129,6 +137,7 @@ export function displayHelp(): void { console.log(' • claude-3-5-sonnet-20241022'); console.log(' • claude-3-opus-20240229\n'); console.log(chalk.green(' OpenAI GPT')); + console.log(' • gpt-5.1 (latest)'); console.log(' • gpt-4-turbo-preview'); console.log(' • gpt-4'); console.log(' • gpt-3.5-turbo\n'); diff --git a/src/cli/index.ts b/src/cli/index.ts index bc6b09b..4c4c3d6 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,7 +35,7 @@ program .option('--staged', 'Analyze staged changes (git diff --staged)') .option('--branch ', 'Analyze against specific branch') .option('--title ', 'PR title (auto-detected from git)') - .option('--provider ', 'AI provider (anthropic|openai|google)', 'anthropic') + .option('--provider ', 'AI provider (anthropic|openai|google)') .option('--model ', 'Specific model to use') .option('--agent', 'Force intelligent agent (recommended for large diffs)') .option('--summary', 'Show summary only') diff --git a/src/cli/utils/config-loader.ts b/src/cli/utils/config-loader.ts index 0cc4134..4937347 100644 --- a/src/cli/utils/config-loader.ts +++ b/src/cli/utils/config-loader.ts @@ -1,6 +1,8 @@ import * as fs from 'fs'; import * as path from 'path'; import chalk from 'chalk'; +import { validateConfigOrThrow, validateConfig } from '../../utils/config-validator.js'; +import { ConfigurationError } from '../../utils/errors.js'; const CONFIG_FILE = '.pragent.config.json'; @@ -61,7 +63,10 @@ export function findConfigFile(): string | null { /** * Load user configuration from file */ -export async function loadUserConfig(verbose: boolean = false): Promise { +export async function loadUserConfig( + verbose: boolean = false, + validate: boolean = true, +): Promise { const configPath = findConfigFile(); if (!configPath) { @@ -80,12 +85,41 @@ export async function loadUserConfig(verbose: boolean = false): Promise { } try { - const config = await loadUserConfig(false); + const config = await loadUserConfig(false, true); // Validate config // Basic validation - if (!config.ai?.provider && !process.env.ANTHROPIC_API_KEY) { + if (!config.ai?.provider && !process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY && !process.env.GOOGLE_API_KEY) { console.log(chalk.yellow('\n⚠️ No AI provider configured')); console.log(chalk.gray(' Run: pr-agent config --init\n')); return true; // Don't block execution } + // Validate branch configuration if present + if (config.git?.defaultBranch) { + const validation = validateConfig(config); + if (!validation.success) { + const branchErrors = validation.errors.filter((e) => e.includes('defaultBranch')); + if (branchErrors.length > 0) { + console.log(chalk.yellow('\n⚠️ Invalid branch configuration:')); + branchErrors.forEach((err) => console.log(chalk.gray(` • ${err}`))); + console.log(chalk.gray(' Run: pr-agent config --set git.defaultBranch=\n')); + } + } + } + return true; } catch (error) { - console.error(chalk.red(`❌ Invalid configuration: ${error}`)); + if (error instanceof ConfigurationError) { + console.error(chalk.red(`\n❌ ${error.message}`)); + return false; + } + console.error(chalk.red(`❌ Invalid configuration: ${error instanceof Error ? error.message : String(error)}`)); return false; } } @@ -124,8 +175,11 @@ export async function checkConfiguration(): Promise { */ export function getApiKey(provider: string, config?: UserConfig): string | undefined { // Check config first - if (config?.apiKeys && config.apiKeys[provider as keyof typeof config.apiKeys]) { - return config.apiKeys[provider as keyof typeof config.apiKeys]; + if (config?.apiKeys) { + const key = config.apiKeys[provider as keyof typeof config.apiKeys]; + if (key && key.trim().length > 0) { + return key; + } } // Fall back to environment variables @@ -137,7 +191,10 @@ export function getApiKey(provider: string, config?: UserConfig): string | undef const envVar = envVarMap[provider.toLowerCase()]; if (envVar) { - return process.env[envVar]; + const envKey = process.env[envVar]; + if (envKey && envKey.trim().length > 0) { + return envKey; + } } return undefined; diff --git a/src/cli/utils/config-prompts.ts b/src/cli/utils/config-prompts.ts index c6ac814..6fe099f 100644 --- a/src/cli/utils/config-prompts.ts +++ b/src/cli/utils/config-prompts.ts @@ -70,6 +70,7 @@ export async function promptFullConfig( defaultModel = 'claude-sonnet-4-5-20250929'; } else if (provider === 'openai') { modelChoices = [ + { name: 'GPT-5.1 (Latest)', value: 'gpt-5.1' }, { name: 'GPT-4 Turbo (Recommended)', value: 'gpt-4-turbo-preview' }, { name: 'GPT-4', value: 'gpt-4' }, { name: 'GPT-3.5 Turbo', value: 'gpt-3.5-turbo' }, diff --git a/src/providers/openai.provider.ts b/src/providers/openai.provider.ts index 6564686..f83a767 100644 --- a/src/providers/openai.provider.ts +++ b/src/providers/openai.provider.ts @@ -27,7 +27,7 @@ export class OpenAIProvider implements ILLMProvider { } return new ChatOpenAI({ - openAIApiKey: this.apiKey, + apiKey: this.apiKey, modelName: config.model || this.getDefaultModel(), temperature: config.temperature ?? 0.2, maxTokens: config.maxTokens ?? 4000, diff --git a/src/utils/branch-resolver.ts b/src/utils/branch-resolver.ts new file mode 100644 index 0000000..1b870af --- /dev/null +++ b/src/utils/branch-resolver.ts @@ -0,0 +1,221 @@ +/** + * Branch resolution utilities + * Handles detection of default branch from GitHub API or git commands + */ + +import { execSync } from 'child_process'; +import { Octokit } from '@octokit/rest'; +import { GitHubAPIError, GitError, ConfigurationError } from './errors.js'; + +export interface BranchResolutionOptions { + configBranch?: string; + githubToken?: string; + repoOwner?: string; + repoName?: string; + fallbackToGit?: boolean; +} + +export interface BranchResolutionResult { + branch: string; + source: 'config' | 'github' | 'git' | 'fallback'; + warning?: string; +} + +/** + * Get repository info from git remote + */ +function getRepoInfo(): { owner: string; name: string } | null { + try { + const remoteUrl = execSync('git config --get remote.origin.url', { + encoding: 'utf-8', + }).trim(); + + // Handle both HTTPS and SSH URLs + // https://github.com/owner/repo.git + // git@github.com:owner/repo.git + const match = + remoteUrl.match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/) || + remoteUrl.match(/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?$/); + + if (match) { + return { + owner: match[1], + name: match[2].replace(/\.git$/, ''), + }; + } + } catch { + // Not a git repo or no remote + } + + return null; +} + +/** + * Get default branch from GitHub API + */ +async function getDefaultBranchFromGitHub( + owner: string, + repo: string, + token?: string, +): Promise { + if (!token) { + return null; + } + + try { + const octokit = new Octokit({ auth: token }); + const response = await octokit.repos.get({ + owner, + repo, + }); + + return response.data.default_branch; + } catch (error: any) { + if (error.status === 404) { + throw new GitHubAPIError( + `Repository ${owner}/${repo} not found. Check repository name and access permissions.`, + 404, + error, + ); + } else if (error.status === 401 || error.status === 403) { + throw new GitHubAPIError( + `GitHub API authentication failed. Check your GITHUB_TOKEN.`, + error.status, + error, + ); + } else { + throw new GitHubAPIError( + `Failed to fetch repository info from GitHub: ${error.message}`, + error.status, + error, + ); + } + } +} + +/** + * Get default branch from git commands + */ +function getDefaultBranchFromGit(): string | null { + try { + // Try to get default branch from git symbolic-ref + try { + const branch = execSync('git symbolic-ref refs/remotes/origin/HEAD', { + encoding: 'utf-8', + }) + .trim() + .replace(/^refs\/remotes\/origin\//, ''); + + if (branch) { + return `origin/${branch}`; + } + } catch { + // Fall through to other methods + } + + // Try common branch names + const commonBranches = ['origin/main', 'main', 'origin/master', 'master']; + for (const branch of commonBranches) { + try { + execSync(`git rev-parse --verify ${branch}`, { stdio: 'ignore' }); + return branch; + } catch { + // Continue to next branch + } + } + + return null; + } catch { + return null; + } +} + +/** + * Resolve the default branch to use for analysis + */ +export async function resolveDefaultBranch( + options: BranchResolutionOptions = {}, +): Promise { + const { configBranch, githubToken, repoOwner, repoName, fallbackToGit = true } = options; + + // 1. Use config branch if provided and valid + if (configBranch && configBranch.trim().length > 0) { + // Validate the branch name exists + try { + execSync(`git rev-parse --verify ${configBranch}`, { stdio: 'ignore' }); + return { + branch: configBranch, + source: 'config', + }; + } catch { + // Config branch doesn't exist, continue to other methods + if (!fallbackToGit) { + throw new ConfigurationError( + `Configured branch "${configBranch}" not found. Run: pr-agent config --set git.defaultBranch=`, + 'git.defaultBranch', + ); + } + } + } + + // 2. Try GitHub API if token and repo info available + if (githubToken) { + const repoInfo = repoOwner && repoName ? { owner: repoOwner, name: repoName } : getRepoInfo(); + + if (repoInfo) { + try { + const defaultBranch = await getDefaultBranchFromGitHub( + repoInfo.owner, + repoInfo.name, + githubToken, + ); + + if (defaultBranch) { + const branchRef = `origin/${defaultBranch}`; + // Verify branch exists locally + try { + execSync(`git rev-parse --verify ${branchRef}`, { stdio: 'ignore' }); + return { + branch: branchRef, + source: 'github', + }; + } catch { + // Branch exists on GitHub but not locally + return { + branch: branchRef, + source: 'github', + warning: `Branch ${branchRef} exists on GitHub but not locally. Run: git fetch origin ${defaultBranch}`, + }; + } + } + } catch (error) { + // GitHub API failed, but continue to git fallback if enabled + if (error instanceof GitHubAPIError && fallbackToGit) { + // Log warning but continue + console.warn(`⚠️ ${error.message}`); + } else { + throw error; + } + } + } + } + + // 3. Fall back to git commands + if (fallbackToGit) { + const gitBranch = getDefaultBranchFromGit(); + if (gitBranch) { + return { + branch: gitBranch, + source: 'git', + }; + } + } + + // 4. Final fallback to common defaults + return { + branch: 'origin/main', + source: 'fallback', + warning: 'Could not detect default branch. Using "origin/main" as fallback. Set git.defaultBranch in config to override.', + }; +} + diff --git a/src/utils/config-validator.ts b/src/utils/config-validator.ts new file mode 100644 index 0000000..b9b5838 --- /dev/null +++ b/src/utils/config-validator.ts @@ -0,0 +1,117 @@ +/** + * Configuration validation using Zod + */ + +import { z } from 'zod'; +import { ConfigurationError } from './errors.js'; +import { UserConfig } from '../cli/utils/config-loader.js'; + +/** + * Zod schema for validating UserConfig + */ +export const UserConfigSchema = z.object({ + apiKeys: z + .object({ + anthropic: z.string().optional(), + openai: z.string().optional(), + google: z.string().optional(), + }) + .optional(), + ai: z + .object({ + provider: z.enum(['anthropic', 'openai', 'google']).optional(), + model: z.string().optional(), + temperature: z.number().min(0).max(2).optional(), + maxTokens: z.number().positive().int().optional(), + }) + .optional(), + analysis: z + .object({ + defaultMode: z.enum(['full', 'summary', 'risks', 'complexity']).optional(), + maxCost: z.number().nonnegative().optional(), + autoDetectAgent: z.boolean().optional(), + agentThreshold: z.number().nonnegative().int().optional(), + }) + .optional(), + git: z + .object({ + defaultBranch: z + .string() + .min(1) + .refine( + (val) => { + // Allow origin/branch, branch, or just branch name + // Reject empty strings and invalid patterns + if (!val || val.trim().length === 0) return false; + // Basic validation: should not contain dangerous characters + if (/[<>"|\\\x00-\x1f]/.test(val)) return false; + return true; + }, + { + message: 'defaultBranch must be a valid branch name (e.g., "origin/main", "main", "master")', + }, + ) + .optional(), + includeUntracked: z.boolean().optional(), + excludePatterns: z.array(z.string()).optional(), + }) + .optional(), + output: z + .object({ + verbose: z.boolean().optional(), + showStrategy: z.boolean().optional(), + showRecommendations: z.boolean().optional(), + }) + .optional(), +}); + +/** + * Validate configuration object + */ +export function validateConfig(config: UserConfig): { + success: boolean; + errors: string[]; + sanitizedConfig?: UserConfig; +} { + try { + const result = UserConfigSchema.safeParse(config); + + if (result.success) { + return { + success: true, + errors: [], + sanitizedConfig: result.data as UserConfig, + }; + } else { + const errors = result.error.issues.map((err: any) => { + const path = err.path.join('.'); + return `${path}: ${err.message}`; + }); + + return { + success: false, + errors, + }; + } + } catch (error) { + return { + success: false, + errors: [`Validation error: ${error instanceof Error ? error.message : String(error)}`], + }; + } +} + +/** + * Validate and throw if invalid + */ +export function validateConfigOrThrow(config: UserConfig, configPath?: string): UserConfig { + const validation = validateConfig(config); + + if (!validation.success) { + const errorMessage = `Invalid configuration${configPath ? ` in ${configPath}` : ''}:\n${validation.errors.map((e) => ` • ${e}`).join('\n')}\n\nRun: pr-agent config --init to fix configuration.`; + throw new ConfigurationError(errorMessage, 'config'); + } + + return validation.sanitizedConfig!; +} + diff --git a/src/utils/errors.ts b/src/utils/errors.ts new file mode 100644 index 0000000..04b6792 --- /dev/null +++ b/src/utils/errors.ts @@ -0,0 +1,41 @@ +/** + * Custom error types for PR Agent + */ + +/** + * Configuration-related errors + */ +export class ConfigurationError extends Error { + constructor(message: string, public readonly field?: string) { + super(message); + this.name = 'ConfigurationError'; + Object.setPrototypeOf(this, ConfigurationError.prototype); + } +} + +/** + * GitHub API-related errors + */ +export class GitHubAPIError extends Error { + constructor( + message: string, + public readonly statusCode?: number, + public readonly apiError?: any, + ) { + super(message); + this.name = 'GitHubAPIError'; + Object.setPrototypeOf(this, GitHubAPIError.prototype); + } +} + +/** + * Git operation errors + */ +export class GitError extends Error { + constructor(message: string, public readonly command?: string) { + super(message); + this.name = 'GitError'; + Object.setPrototypeOf(this, GitError.prototype); + } +} + diff --git a/tests/branch-resolver.test.ts b/tests/branch-resolver.test.ts new file mode 100644 index 0000000..ae7b27e --- /dev/null +++ b/tests/branch-resolver.test.ts @@ -0,0 +1,49 @@ +/** + * Tests for branch-resolver.ts + * + * Note: These are integration-style tests that may require actual git repository + * For unit tests, consider mocking git commands more thoroughly + */ + +import { describe, it, expect, beforeEach, jest } from '@jest/globals'; +import { resolveDefaultBranch } from '../src/utils/branch-resolver.js'; +import { ConfigurationError } from '../src/utils/errors.js'; + +// Mock @octokit/rest to avoid ES module issues in tests +jest.mock('@octokit/rest', () => { + return { + Octokit: jest.fn().mockImplementation(() => ({ + repos: { + get: jest.fn(), + }, + })), + }; +}); + +describe('branch-resolver', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('resolveDefaultBranch', () => { + it('should throw ConfigurationError if config branch does not exist and fallback disabled', async () => { + await expect( + resolveDefaultBranch({ + configBranch: 'origin/nonexistent', + fallbackToGit: false, + }), + ).rejects.toThrow(ConfigurationError); + }); + + it('should fallback to origin/main if nothing found', async () => { + const result = await resolveDefaultBranch({ + fallbackToGit: true, + }); + + expect(result.branch).toBe('origin/main'); + expect(result.source).toBe('fallback'); + expect(result.warning).toBeDefined(); + }); + }); +}); + diff --git a/tests/config-loader.test.ts b/tests/config-loader.test.ts new file mode 100644 index 0000000..13dcc52 --- /dev/null +++ b/tests/config-loader.test.ts @@ -0,0 +1,136 @@ +/** + * Tests for config-loader.ts + */ + +import { describe, it, expect, beforeEach, afterEach } from '@jest/globals'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as os from 'os'; +import { + findConfigFile, + loadUserConfig, + getApiKey, +} from '../src/cli/utils/config-loader.js'; +import { ConfigurationError } from '../src/utils/errors.js'; + +describe('config-loader', () => { + let tempDir: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pr-agent-test-')); + process.chdir(tempDir); + jest.clearAllMocks(); + }); + + afterEach(() => { + try { + if (fs.existsSync(tempDir)) { + // Change back to original directory before cleanup + process.chdir(require('os').homedir()); + // Use setTimeout to allow file handles to close on Windows + setTimeout(() => { + try { + fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } catch { + // Ignore cleanup errors on Windows + } + }, 100); + } + } catch { + // Ignore cleanup errors + } + }); + + describe('findConfigFile', () => { + it('should find config file in current directory', () => { + const configPath = path.join(tempDir, '.pragent.config.json'); + fs.writeFileSync(configPath, '{}'); + + const result = findConfigFile(); + expect(result).toBe(configPath); + }); + + it('should return null if no config file exists', () => { + const result = findConfigFile(); + expect(result).toBeNull(); + }); + }); + + describe('loadUserConfig', () => { + it('should load valid config file', async () => { + const configPath = path.join(tempDir, '.pragent.config.json'); + const config = { + ai: { provider: 'openai' as const, model: 'gpt-4' }, + git: { defaultBranch: 'origin/main' }, + }; + + fs.writeFileSync(configPath, JSON.stringify(config)); + + const result = await loadUserConfig(false, true); + expect(result.ai?.provider).toBe('openai'); + expect(result.git?.defaultBranch).toBe('origin/main'); + }); + + it('should throw ConfigurationError for invalid JSON', async () => { + const configPath = path.join(tempDir, '.pragent.config.json'); + fs.writeFileSync(configPath, 'invalid json{'); + + await expect(loadUserConfig(false, true)).rejects.toThrow(ConfigurationError); + }); + + it('should return empty object if no config file', async () => { + const result = await loadUserConfig(false, false); + expect(result).toEqual({}); + }); + }); + + describe('getApiKey', () => { + it('should get API key from config', () => { + const config = { + apiKeys: { + openai: 'sk-test-key-123', + }, + }; + + const result = getApiKey('openai', config); + expect(result).toBe('sk-test-key-123'); + }); + + it('should get API key from environment variable', () => { + process.env.OPENAI_API_KEY = 'sk-env-key-456'; + const result = getApiKey('openai', {}); + expect(result).toBe('sk-env-key-456'); + delete process.env.OPENAI_API_KEY; + }); + + it('should prefer config over environment', () => { + process.env.OPENAI_API_KEY = 'sk-env-key'; + const config = { + apiKeys: { + openai: 'sk-config-key', + }, + }; + + const result = getApiKey('openai', config); + expect(result).toBe('sk-config-key'); + delete process.env.OPENAI_API_KEY; + }); + + it('should return undefined if no key found', () => { + const result = getApiKey('openai', {}); + expect(result).toBeUndefined(); + }); + + it('should handle empty string keys', () => { + const config = { + apiKeys: { + openai: '', + }, + }; + + const result = getApiKey('openai', config); + expect(result).toBeUndefined(); + }); + }); +}); +